View Javadoc
1   /*
2    * scriptable-dataset (https://github.com/hazendaz/scriptable-dataset)
3    *
4    * Copyright 2011-2025 Hazendaz.
5    *
6    * All rights reserved. This program and the accompanying materials
7    * are made available under the terms of The Apache Software License,
8    * Version 2.0 which accompanies this distribution, and is available at
9    * https://www.apache.org/licenses/LICENSE-2.0.txt
10   *
11   * Contributors:
12   *     Gunnar Morling
13   *     Hazendaz (Jeremy Landis).
14   */
15  package de.gmorling.scriptabledataset;
16  
17  import static org.junit.jupiter.api.Assertions.assertEquals;
18  import static org.junit.jupiter.api.Assertions.assertThrows;
19  import static org.junit.jupiter.api.Assertions.fail;
20  
21  import de.gmorling.scriptabledataset.handlers.JRubyImportAddingInvocationHandler;
22  import de.gmorling.scriptabledataset.handlers.ScriptInvocationHandler;
23  
24  import java.sql.Connection;
25  import java.sql.DriverManager;
26  import java.sql.ResultSet;
27  import java.sql.SQLException;
28  import java.sql.Statement;
29  import java.util.ArrayList;
30  import java.util.Calendar;
31  import java.util.Date;
32  import java.util.List;
33  
34  import org.apache.commons.lang3.time.DateUtils;
35  import org.dbunit.DatabaseUnitException;
36  import org.dbunit.database.DatabaseConnection;
37  import org.dbunit.database.IDatabaseConnection;
38  import org.dbunit.dataset.IDataSet;
39  import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
40  import org.dbunit.operation.DatabaseOperation;
41  import org.junit.jupiter.api.AfterAll;
42  import org.junit.jupiter.api.AfterEach;
43  import org.junit.jupiter.api.BeforeAll;
44  import org.junit.jupiter.api.BeforeEach;
45  import org.junit.jupiter.api.Test;
46  
47  /**
48   * Test for ScriptableDataSet.
49   */
50  class ScriptableDataSetTest {
51  
52      /** The connection. */
53      static Connection connection;
54  
55      /** The db unit connection. */
56      static IDatabaseConnection dbUnitConnection;
57  
58      /** The result set. */
59      ResultSet resultSet;
60  
61      /** The statement. */
62      Statement statement;
63  
64      /**
65       * Initialize connection.
66       *
67       * @throws Exception
68       *             the exception
69       */
70      @BeforeAll
71      static void initializeConnection() throws Exception {
72          connection = DriverManager.getConnection("jdbc:derby:derbyTest;create=true");
73          connection.setAutoCommit(false);
74  
75          dbUnitConnection = new DatabaseConnection(connection);
76      }
77  
78      /**
79       * Creates the table.
80       *
81       * @throws Exception
82       *             the exception
83       */
84      @BeforeEach
85      void createTable() throws Exception {
86          statement = connection.createStatement();
87          statement.execute("create table location(num int, addr varchar(40), date timestamp)");
88      }
89  
90      /**
91       * Rollback transaction.
92       *
93       * @throws Exception
94       *             the exception
95       */
96      @AfterEach
97      void rollbackTransaction() throws Exception {
98          if (resultSet != null) {
99              resultSet.close();
100         }
101         connection.rollback();
102         statement.close();
103     }
104 
105     /**
106      * Close connection.
107      *
108      * @throws Exception
109      *             the exception
110      */
111     @AfterAll
112     static void closeConnection() throws Exception {
113         dbUnitConnection.close();
114         connection.close();
115     }
116 
117     /**
118      * Test for using JRuby as scripting language.
119      *
120      * @throws Exception
121      *             In case of any error.
122      */
123     @Test
124     void jRubyScript() throws Exception {
125         IDataSet dataSet = new ScriptableDataSet(
126                 new FlatXmlDataSetBuilder().build(ScriptableDataSetTest.class.getResourceAsStream("jruby.xml")),
127                 new ScriptableDataSetConfig("jruby", "jruby:"));
128 
129         insertDataSetAndCreateResultSet(dataSet);
130 
131         assertNextRow(resultSet, 6, "teertS retsbeW", addDaysToToday(-14));
132     }
133 
134     /**
135      * Test for using Groovy as scripting language.
136      *
137      * @throws Exception
138      *             In case of any error.
139      */
140     @Test
141     void groovyScript() throws Exception {
142         IDataSet dataSet = new ScriptableDataSet(
143                 new FlatXmlDataSetBuilder().build(ScriptableDataSetTest.class.getResourceAsStream("groovy.xml")),
144                 new ScriptableDataSetConfig("groovy", "groovy:"));
145 
146         insertDataSetAndCreateResultSet(dataSet);
147 
148         assertNextRow(resultSet, 6, "teertS retsbeW", addDaysToToday(-14));
149     }
150 
151     /**
152      * Test for using JRuby and Groovy within one data set file.
153      *
154      * @throws Exception
155      *             In case of any error.
156      */
157     @Test
158     void dataSetWithMultipleLanguages() throws Exception {
159         IDataSet dataSet = new ScriptableDataSet(
160                 new FlatXmlDataSetBuilder()
161                         .build(ScriptableDataSetTest.class.getResourceAsStream("multiple_languages.xml")),
162                 new ScriptableDataSetConfig("jruby", "jruby:"), new ScriptableDataSetConfig("groovy", "groovy:"));
163 
164         insertDataSetAndCreateResultSet(dataSet);
165 
166         assertNextRow(resultSet, 6, "teertS retsbeW", addDaysToToday(-14));
167         assertNextRow(resultSet, 6, "teertS retsbeW", addDaysToToday(-14));
168     }
169 
170     /**
171      * Test for using JRuby as scripting language in conjunction with a special invocation handler.
172      *
173      * @throws Exception
174      *             In case of any error.
175      */
176     @Test
177     void customHandler() throws Exception {
178         List<ScriptInvocationHandler> handlers = new ArrayList<>();
179         handlers.add(new JRubyImportAddingInvocationHandler());
180 
181         IDataSet dataSet = new ScriptableDataSet(
182                 new FlatXmlDataSetBuilder().build(ScriptableDataSetTest.class.getResourceAsStream("customhandler.xml")),
183                 new ScriptableDataSetConfig("jruby", "jruby:", handlers));
184 
185         insertDataSetAndCreateResultSet(dataSet);
186 
187         assertNextRow(resultSet, 1, "Webster Street", addDaysToToday(-14));
188     }
189 
190     /**
191      * Test for usage of an unknown scripting engine.
192      *
193      * @throws Exception
194      *             In case of any error.
195      */
196     @Test
197     void unknownScriptingEngine() throws Exception {
198         IDataSet dataSet = new ScriptableDataSet(
199                 new FlatXmlDataSetBuilder()
200                         .build(ScriptableDataSetTest.class.getResourceAsStream("unknownscriptingengine.xml")),
201                 new ScriptableDataSetConfig("unknown", "unknown:"));
202 
203         assertThrows(RuntimeException.class, () -> {
204             DatabaseOperation.INSERT.execute(dbUnitConnection, dataSet);
205         });
206     }
207 
208     /**
209      * Insert data set and create result set.
210      *
211      * @param dataSet
212      *            the data set
213      *
214      * @throws DatabaseUnitException
215      *             the database unit exception
216      * @throws SQLException
217      *             the SQL exception
218      */
219     void insertDataSetAndCreateResultSet(IDataSet dataSet) throws DatabaseUnitException, SQLException {
220         DatabaseOperation.INSERT.execute(dbUnitConnection, dataSet);
221         resultSet = statement.executeQuery("SELECT num, addr, date FROM location ORDER BY num");
222     }
223 
224     /**
225      * Assert next row.
226      *
227      * @param rs
228      *            the rs
229      * @param expectedInt
230      *            the expected int
231      * @param expectedString
232      *            the expected string
233      * @param expectedDate
234      *            the expected date
235      *
236      * @throws SQLException
237      *             the SQL exception
238      */
239     void assertNextRow(ResultSet rs, int expectedInt, String expectedString, Date expectedDate) throws SQLException {
240         if (!rs.next()) {
241             fail("Data set should have a row.");
242         }
243 
244         assertEquals(expectedInt, rs.getObject(1));
245         assertEquals(expectedString, rs.getObject(2));
246         assertEquals(DateUtils.truncate(expectedDate, Calendar.DATE),
247                 DateUtils.truncate(rs.getObject(3), Calendar.DATE));
248     }
249 
250     /**
251      * Adds the days to today.
252      *
253      * @param numberOfDays
254      *            the number of days
255      *
256      * @return the date
257      */
258     Date addDaysToToday(int numberOfDays) {
259         Calendar calendar = Calendar.getInstance();
260         calendar.add(Calendar.DATE, numberOfDays);
261 
262         return calendar.getTime();
263     }
264 }