KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derbyTesting > junit > BaseJDBCTestCase


1 /*
2  *
3  * Derby - Class BaseJDBCTestCase
4  *
5  * Licensed to the Apache Software Foundation (ASF) under one or more
6  * contributor license agreements. See the NOTICE file distributed with
7  * this work for additional information regarding copyright ownership.
8  * The ASF licenses this file to You under the Apache License, Version 2.0
9  * (the "License"); you may not use this file except in compliance with
10  * the License. You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */

20 package org.apache.derbyTesting.junit;
21
22 import java.io.ByteArrayInputStream JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.OutputStream JavaDoc;
26 import java.io.PrintStream JavaDoc;
27 import java.io.Reader JavaDoc;
28 import java.io.UnsupportedEncodingException JavaDoc;
29 import java.sql.*;
30
31 import junit.framework.AssertionFailedError;
32
33 import org.apache.derby.tools.ij;
34
35
36 /**
37  * Base class for JDBC JUnit tests.
38  * A method for getting a default connection is provided, along with methods
39  * for telling if a specific JDBC client is used.
40  */

41 public abstract class BaseJDBCTestCase
42     extends BaseTestCase {
43
44     /**
45      * Maintain a single connection to the default
46      * database, opened at the first call to getConnection.
47      * Typical setup will just require a single connection.
48      * @see BaseJDBCTestCase#getConnection()
49      */

50     private Connection conn;
51     
52     /**
53      * Create a test case with the given name.
54      *
55      * @param name of the test case.
56      */

57     public BaseJDBCTestCase(String JavaDoc name) {
58         super(name);
59     }
60     
61     /**
62      * Obtain the connection to the default database.
63      * This class maintains a single connection returned
64      * by this class, it is opened on the first call to
65      * this method. Subsequent calls will return the same
66      * connection object unless it has been closed. In that
67      * case a new connection object will be returned.
68      * <P>
69      * The tearDown method will close the connection if
70      * it is open.
71      * @see TestConfiguration#openDefaultConnection()
72      */

73     public Connection getConnection() throws SQLException
74     {
75         if (conn != null)
76         {
77             if (!conn.isClosed())
78                 return conn;
79             conn = null;
80         }
81         return conn = openDefaultConnection();
82     }
83     
84     /**
85      * Allow a sub-class to initialize a connection to provide
86      * consistent connection state for its tests. Called once
87      * for each time these method calls open a connection:
88      * <UL>
89      * <LI> getConnection()
90      * <LI> openDefaultConnection()
91      * <LI> openConnection(database)
92      * <LI> getDefaultConnection(String connAttrs)
93      * <LI> getConnection(String databaseName, String connAttrs)
94      * </UL>
95      * when getConnection() opens a new connection. Default
96      * action is to not modify the connection's state from
97      * the initialization provided by the data source.
98      * @param conn Connection to be intialized
99      * @throws SQLException Error setting the initial state.
100      */

101     protected void initializeConnection(Connection conn) throws SQLException
102     {
103     }
104     
105     /**
106      * Utility method to create a Statement using the connection
107      * returned by getConnection.
108      * @return Statement object from getConnection.createStatement()
109      * @throws SQLException
110      */

111     public Statement createStatement() throws SQLException
112     {
113         return getConnection().createStatement();
114     }
115
116     /**
117      * Utility method to create a Statement using the connection
118      * returned by getConnection.
119      * @return Statement object from
120      * getConnection.createStatement(resultSetType, resultSetConcurrency)
121      * @throws SQLException
122      */

123     public Statement createStatement(int resultSetType,
124             int resultSetConcurrency) throws SQLException
125     {
126         return getConnection().createStatement(resultSetType, resultSetConcurrency);
127     }
128     /**
129      * Utility method to create a PreparedStatement using the connection
130      * returned by getConnection.
131      * @return Statement object from
132      * getConnection.prepareStatement(sql)
133      * @throws SQLException
134      */

135     public PreparedStatement prepareStatement(String JavaDoc sql) throws SQLException
136     {
137         return getConnection().prepareStatement(sql);
138     }
139
140     /**
141      * Utility method to create a CallableStatement using the connection
142      * returned by getConnection.
143      * @return Statement object from
144      * getConnection().prepareCall(sql)
145      * @throws SQLException
146      */

147     public CallableStatement prepareCall(String JavaDoc sql) throws SQLException
148     {
149         return getConnection().prepareCall(sql);
150     }
151     
152     /**
153      * Utility method to commit using the connection
154      * returned by getConnection.
155      * @throws SQLException
156      */

157     public void commit() throws SQLException
158     {
159         getConnection().commit();
160     }
161     /**
162      * Utility method to rollback using the connection
163      * returned by getConnection.
164      * @throws SQLException
165      */

166     public void rollback() throws SQLException
167     {
168         getConnection().rollback();
169     }
170     /**
171      * Tear down this fixture, sub-classes should call
172      * super.tearDown(). This cleanups & closes the connection
173      * if it is open.
174      */

175     protected void tearDown()
176     throws java.lang.Exception JavaDoc
177     {
178         JDBC.cleanup(conn);
179         conn = null;
180     }
181
182     /**
183      * Open a connection to the default database.
184      * If the database does not exist, it will be created.
185      * A default username and password will be used for the connection.
186      *
187      * @return connection to default database.
188      * @see TestConfiguration#openDefaultConnection()
189      */

190     public Connection openDefaultConnection()
191         throws SQLException {
192         Connection conn = getTestConfiguration().openDefaultConnection();
193         initializeConnection(conn);
194         return conn;
195     }
196     
197     public Connection openConnection(String JavaDoc databaseName) throws SQLException
198     {
199         Connection conn = getTestConfiguration().openConnection(databaseName);
200         initializeConnection(conn);
201         return conn;
202     }
203     
204     /**
205      * Get a connection to the default database using the specified connection
206      * attributes.
207      *
208      * @param connAttrs connection attributes
209      * @return connection to default database.
210      * @throws SQLException
211      */

212     public Connection getDefaultConnection(String JavaDoc connAttrs)
213         throws SQLException {
214         Connection conn = getTestConfiguration().
215                                 getDefaultConnection(connAttrs);
216         initializeConnection(conn);
217         return conn;
218     }
219
220     /**
221      * Get a connection to a database using the specified connection
222      * attributes.
223      *
224      * @param databaseName database to connect to
225      * @param connAttrs connection attributes
226      * @return connection to database
227      * @throws SQLException
228      */

229     public Connection getConnection(String JavaDoc databaseName, String JavaDoc connAttrs)
230         throws SQLException
231     {
232         Connection conn = getTestConfiguration().getConnection(databaseName,
233                                                                 connAttrs);
234         initializeConnection(conn);
235         return conn;
236     }
237     
238     /**
239      * Run a SQL script through ij discarding the output
240      * using this object's default connection. Intended for
241      * setup scripts.
242      * @throws UnsupportedEncodingException
243      * @throws SQLException
244      */

245     public int runScript(InputStream JavaDoc script, String JavaDoc encoding)
246         throws UnsupportedEncodingException JavaDoc, SQLException
247     {
248         // Sink output.
249
OutputStream JavaDoc sink = new OutputStream JavaDoc() {
250             public void write(byte[] b, int off, int len) {}
251             public void write(int b) {}
252         };
253         
254         // Use the same encoding as the input for the output.
255
return ij.runScript(getConnection(), script, encoding,
256                 sink, encoding);
257     }
258     
259     /**
260      * Run a set of SQL commands from a String discarding the output.
261      * Commands are separated by a semi-colon. Connection used
262      * is this objects default connection.
263      * @param sqlCommands
264      * @return Number of errors executing the script.
265      * @throws UnsupportedEncodingException
266      * @throws SQLException
267      */

268     public int runSQLCommands(String JavaDoc sqlCommands)
269         throws UnsupportedEncodingException JavaDoc, SQLException
270     {
271         byte[] raw = sqlCommands.getBytes("UTF-8");
272         ByteArrayInputStream JavaDoc in = new ByteArrayInputStream JavaDoc(raw);
273         
274         return runScript(in, "UTF-8");
275     }
276     
277     /**
278      * Tell if the client is embedded.
279      *
280      * @return <code>true</code> if using the embedded client
281      * <code>false</code> otherwise.
282      */

283      public static boolean usingEmbedded() {
284          return TestConfiguration.getCurrent().getJDBCClient().isEmbedded();
285      }
286     
287     /**
288     * Tell if the client is DerbyNetClient.
289     *
290     * @return <code>true</code> if using the DerbyNetClient client
291     * <code>false</code> otherwise.
292     */

293     public static boolean usingDerbyNetClient() {
294         return TestConfiguration.getCurrent().getJDBCClient().isDerbyNetClient();
295     }
296     
297     /**
298     * Tell if the client is DerbyNet.
299     *
300     * @return <code>true</code> if using the DerbyNet client
301     * <code>false</code> otherwise.
302     */

303     public static boolean usingDerbyNet() {
304         return TestConfiguration.getCurrent().getJDBCClient().isDB2Client();
305     }
306
307     /**
308      * Assert equality between two <code>Blob</code> objects.
309      * If both input references are <code>null</code>, they are considered
310      * equal. The same is true if both blobs have <code>null</code>-streams.
311      *
312      * @param b1 first <code>Blob</code>.
313      * @param b2 second <code>Blob</code>.
314      * @throws AssertionFailedError if blobs are not equal.
315      * @throws IOException if reading or closing a stream fails
316      * @throws SQLException if obtaining a stream fails
317      */

318     public static void assertEquals(Blob b1, Blob b2)
319             throws IOException JavaDoc, SQLException {
320         if (b1 == null || b2 == null) {
321             assertNull("Blob b2 is null, b1 is not", b1);
322             assertNull("Blob b1 is null, b2 is not", b2);
323             return;
324         }
325         assertEquals("Blobs have different lengths",
326                      b1.length(), b2.length());
327         InputStream JavaDoc is1 = b1.getBinaryStream();
328         InputStream JavaDoc is2 = b2.getBinaryStream();
329         if (is1 == null || is2 == null) {
330             assertNull("Blob b2 has null-stream, blob b1 doesn't", is1);
331             assertNull("Blob b1 has null-stream, blob b2 doesn't", is2);
332             return;
333         }
334         long index = 1;
335         int by1 = is1.read();
336         int by2 = is2.read();
337         do {
338             // Avoid string concatenation for every byte in the stream.
339
if (by1 != by2) {
340                 assertEquals("Blobs differ at index " + index,
341                         by1, by2);
342             }
343             index++;
344             by1 = is1.read();
345             by2 = is2.read();
346         } while ( by1 != -1 || by2 != -1);
347         is1.close();
348         is2.close();
349     }
350
351     /**
352      * Assert equality between two <code>Clob</code> objects.
353      * If both input references are <code>null</code>, they are considered
354      * equal. The same is true if both clobs have <code>null</code>-streams.
355      *
356      * @param c1 first <code>Clob</code>.
357      * @param c2 second <code>Clob</code>.
358      * @throws AssertionFailedError if clobs are not equal.
359      * @throws IOException if reading or closing a stream fails
360      * @throws SQLException if obtaining a stream fails
361      */

362     public static void assertEquals(Clob c1, Clob c2)
363             throws IOException JavaDoc, SQLException {
364         if (c1 == null || c2 == null) {
365             assertNull("Clob c2 is null, c1 is not", c1);
366             assertNull("Clob c1 is null, c2 is not", c2);
367             return;
368         }
369         assertEquals("Clobs have different lengths",
370                      c1.length(), c2.length());
371         Reader JavaDoc r1 = c1.getCharacterStream();
372         Reader JavaDoc r2 = c2.getCharacterStream();
373         if (r1 == null || r2 == null) {
374             assertNull("Clob c2 has null-stream, clob c1 doesn't", r1);
375             assertNull("Clob c1 has null-stream, clob c2 doesn't", r2);
376             return;
377         }
378         long index = 1;
379         int ch1 = r1.read();
380         int ch2 = r2.read();
381         do {
382             // Avoid string concatenation for every char in the stream.
383
if (ch1 != ch2) {
384                 assertEquals("Clobs differ at index " + index,
385                         ch1, ch2);
386             }
387             index++;
388             ch1 = r1.read();
389             ch2 = r2.read();
390         } while (ch1 != -1 || ch2 != -1);
391         r1.close();
392         r2.close();
393     }
394
395     /**
396      * Assert that SQLState is as expected.
397      *
398      * @param message message to print on failure.
399      * @param expected the expected SQLState.
400      * @param exception the exception to check the SQLState of.
401      */

402     public static void assertSQLState(String JavaDoc message,
403                                       String JavaDoc expected,
404                                       SQLException exception) {
405         // Make sure exception is not null. We want to separate between a
406
// null-exception object, and a null-SQLState.
407
assertNotNull("Exception cannot be null when asserting on SQLState",
408                       exception);
409         
410         try {
411             String JavaDoc state = exception.getSQLState();
412             
413             if ( state != null )
414                 assertTrue("The exception's SQL state must be five characters long",
415                         state.length() == 5);
416             
417             if ( expected != null )
418                 assertTrue("The expected SQL state must be five characters long",
419                     expected.length() == 5);
420             
421             assertEquals(message, expected, state);
422         } catch (AssertionFailedError e) {
423             
424             // Save the SQLException
425
// e.initCause(exception);
426

427             throw e;
428         }
429     }
430
431     /**
432      * Assert that SQLState is as expected.
433      *
434      * @param expected the expected SQLState.
435      * @param exception the exception to check the SQLState of.
436      */

437     public static void assertSQLState(String JavaDoc expected, SQLException exception) {
438         assertSQLState("Unexpected SQL state.", expected, exception);
439     }
440     /**
441      * Assert that the query does not compile and throws
442      * a SQLException with the expected state.
443      *
444      * @param sqlstate expected sql state.
445      * @param query the query to compile.
446      */

447     public void assertCompileError(String JavaDoc sqlState, String JavaDoc query) {
448
449         try {
450             prepareStatement(query).close();
451             fail("expected compile error: " + sqlState);
452         } catch (SQLException se) {
453             assertSQLState(sqlState, se);
454         }
455     }
456
457 } // End class BaseJDBCTestCase
458

459
460
Popular Tags