View Javadoc
1   /*
2    *
3    * The DbUnit Database Testing Framework
4    * Copyright (C)2002-2004, DbUnit.org
5    *
6    * This library is free software; you can redistribute it and/or
7    * modify it under the terms of the GNU Lesser General Public
8    * License as published by the Free Software Foundation; either
9    * version 2.1 of the License, or (at your option) any later version.
10   *
11   * This library is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   * Lesser General Public License for more details.
15   *
16   * You should have received a copy of the GNU Lesser General Public
17   * License along with this library; if not, write to the Free Software
18   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   *
20   */
21  
22  package org.dbunit.dataset.csv;
23  
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.IOException;
27  import java.net.MalformedURLException;
28  import java.net.URL;
29  import java.sql.DriverManager;
30  import java.sql.ResultSet;
31  import java.sql.SQLException;
32  import java.sql.Statement;
33  import java.util.Properties;
34  
35  import junit.framework.TestCase;
36  
37  import org.dbunit.DatabaseUnitException;
38  import org.dbunit.HypersonicEnvironment;
39  import org.dbunit.ant.AbstractStep;
40  import org.dbunit.ant.Export;
41  import org.dbunit.ant.Operation;
42  import org.dbunit.ant.Query;
43  import org.dbunit.database.DatabaseConfig;
44  import org.dbunit.database.DatabaseConnection;
45  import org.dbunit.database.IDatabaseConnection;
46  import org.dbunit.dataset.CachedDataSet;
47  import org.dbunit.dataset.DataSetException;
48  import org.dbunit.dataset.ITable;
49  import org.dbunit.ext.hsqldb.HsqldbDataTypeFactory;
50  import org.dbunit.operation.DatabaseOperation;
51  import org.dbunit.testutil.TestUtils;
52  import org.dbunit.util.FileHelper;
53  
54  public class CsvURLProducerTest extends TestCase {
55      private String driverClass;
56      private String url;
57      private String user;
58      private String password;
59      private IDatabaseConnection connection;
60      private static final int ORDERS_ROWS_NUMBER = 5;
61      private static final int ORDERS_ROW_ROWS_NUMBER = 3;
62      private static final String THE_DIRECTORY = "csv/orders";
63  
64      public void testProduceFromFolder() throws DataSetException, MalformedURLException {
65          CsvURLProducer producer = new CsvURLProducer(TestUtils.getFile(THE_DIRECTORY).toURL(), CsvDataSet.TABLE_ORDERING_FILE);
66          doTestWithProducer(producer);
67      }
68  
69      public void testProduceFromJar() throws DataSetException, IOException {
70      	File file = TestUtils.getFile(THE_DIRECTORY + "/orders.jar");
71      	URL jarFile = new URL("jar:" + file.toURL() + "!/");
72          CsvURLProducer producer = new CsvURLProducer(jarFile, CsvDataSet.TABLE_ORDERING_FILE);
73          doTestWithProducer(producer);
74      }
75  
76      private void doTestWithProducer(CsvURLProducer producer) throws DataSetException
77      {
78          CachedDataSet consumer = new CachedDataSet();
79          // producer.setConsumer(new CsvDataSetWriter("src/csv/orders-out"));
80  
81          producer.setConsumer(consumer);
82          producer.produce();
83          final ITable[] tables = consumer.getTables();
84          assertEquals("expected 2 tables", 2, tables.length);
85  
86          final ITable orders = consumer.getTable("orders");
87          assertNotNull("orders table not found", orders);
88          assertEquals("wrong number of rows", ORDERS_ROWS_NUMBER, orders.getRowCount());
89          assertEquals("wrong number of columns", 2, orders.getTableMetaData().getColumns().length);
90  
91          final ITable ordersRow = consumer.getTable("orders_row");
92          assertNotNull("orders_row table not found", ordersRow);
93          assertEquals("wrong number of rows", ORDERS_ROW_ROWS_NUMBER, ordersRow.getRowCount());
94          assertEquals("wrong number of columns", ORDERS_ROW_ROWS_NUMBER, ordersRow.getTableMetaData().getColumns().length);
95      	
96      }
97      
98      public void testProduceAndInsertFromFolder() throws ClassNotFoundException, MalformedURLException, DatabaseUnitException, SQLException {
99          produceAndInsertToDatabase();
100         Statement statement = connection.getConnection().createStatement();
101         ResultSet resultSet = statement.executeQuery("select count(*) from orders");
102         resultSet.next();
103         int count = resultSet.getInt(1);
104         assertEquals(ORDERS_ROWS_NUMBER, count);
105         resultSet.close();
106         statement.close();
107     }
108 
109     private void produceAndInsertToDatabase() throws DatabaseUnitException, SQLException, MalformedURLException {
110         CsvURLProducer producer = new CsvURLProducer(TestUtils.getFile(THE_DIRECTORY).toURL(), CsvDataSet.TABLE_ORDERING_FILE);
111         CachedDataSet consumer = new CachedDataSet();
112         producer.setConsumer(consumer);
113         producer.produce();
114         DatabaseOperation operation = DatabaseOperation.INSERT;
115         operation.execute(connection, consumer);
116     }
117 
118     public void testInsertOperationWithCsvFormat() throws SQLException, DatabaseUnitException {
119         Operation operation = new Operation();
120         operation.setFormat(AbstractStep.FORMAT_CSV);
121         operation.setSrc(TestUtils.getFile(THE_DIRECTORY));
122         operation.setType("INSERT");
123         operation.execute(connection);
124         Statement statement = connection.getConnection().createStatement();
125         ResultSet resultSet = statement.executeQuery("select count(*) from orders");
126         resultSet.next();
127         final int count = resultSet.getInt(1);
128         assertEquals("wrong number of row in orders table", ORDERS_ROWS_NUMBER, count);
129         resultSet.close();
130         statement.close();
131     }
132 
133     public void testExportTaskWithCsvFormat() throws MalformedURLException, DatabaseUnitException, SQLException {
134         produceAndInsertToDatabase();
135 
136         final String fromAnt = "target/csv/from-ant";
137         final File dir = new File(fromAnt);
138         try {
139             FileHelper.deleteDirectory(dir);
140     
141             Export export = new Export();
142             export.setFormat(AbstractStep.FORMAT_CSV);
143             export.setDest(dir);
144     
145             Query query = new Query();
146             query.setName("orders");
147             query.setSql("select * from orders");
148             export.addQuery(query);
149     
150             Query query2 = new Query();
151             query2.setName("orders_row");
152             query2.setSql("select * from orders_row");
153             export.addQuery(query2);
154     
155             export.execute(getConnection());
156     
157             final File ordersFile = new File(fromAnt + "/orders.csv");
158             assertTrue("file '" + ordersFile.getAbsolutePath() + "' does not exists", ordersFile.exists());
159             final File ordersRowFile = new File(fromAnt + "/orders_row.csv");
160             assertTrue("file " + ordersRowFile + " does not exists", ordersRowFile.exists());
161         }
162         finally {
163             FileHelper.deleteDirectory(dir);
164         }
165     }
166 
167     private IDatabaseConnection getConnection() throws SQLException, DatabaseUnitException {
168         DatabaseConnection connection = new DatabaseConnection(DriverManager.getConnection(url, user, password));
169         DatabaseConfig config = connection.getConfig();
170         config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
171                 new HsqldbDataTypeFactory());
172         return connection;
173     }
174 
175     protected void setUp() throws Exception {
176         Properties properties = new Properties();
177         final FileInputStream inStream = TestUtils.getFileInputStream("csv/cvs-tests.properties");
178         properties.load(inStream);
179         inStream.close();
180         driverClass = properties.getProperty("cvs-tests.driver.class");
181         url = properties.getProperty("cvs-tests.url");
182         user = properties.getProperty("cvs-tests.user");
183         password = properties.getProperty("cvs-tests.password");
184         assertFalse("".equals(driverClass));
185         assertFalse("".equals(url));
186         assertFalse("".equals(user));
187         Class.forName(driverClass);
188         connection = getConnection();
189         Statement statement = connection.getConnection().createStatement();
190         try {
191             statement.execute("DROP TABLE ORDERS");
192             statement.execute("DROP TABLE ORDERS_ROW");
193         } catch (Exception ignored) {}
194         statement.execute("CREATE TABLE ORDERS (ID INTEGER, DESCRIPTION VARCHAR)");
195         statement.execute("CREATE TABLE ORDERS_ROW (ID INTEGER, DESCRIPTION VARCHAR, QUANTITY INTEGER)");
196         //statement.execute("delete from orders");
197         //statement.execute("delete from orders_row");
198         statement.close();
199     }
200 
201     protected void tearDown() throws Exception {
202         HypersonicEnvironment.shutdown(connection.getConnection());
203         connection.close();
204     }
205 }