KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > testsuite > BaseTestCase


1 /*
2  Copyright (C) 2002-2004 MySQL AB
3
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of version 2 of the GNU General Public License as
6  published by the Free Software Foundation.
7
8  There are special exceptions to the terms and conditions of the GPL
9  as it is applied to this software. View the full text of the
10  exception in file EXCEPTIONS-CONNECTOR-J in the directory of this
11  software distribution.
12
13  This program is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with this program; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22
23
24  */

25 package testsuite;
26
27 import java.sql.Connection JavaDoc;
28 import java.sql.DriverManager JavaDoc;
29 import java.sql.PreparedStatement JavaDoc;
30 import java.sql.ResultSet JavaDoc;
31 import java.sql.SQLException JavaDoc;
32 import java.sql.Statement JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.Properties JavaDoc;
36
37 import junit.framework.TestCase;
38
39 /**
40  * Base class for all test cases. Creates connections, statements, etc. and
41  * closes them.
42  *
43  * @author Mark Matthews
44  * @version $Id: BaseTestCase.java,v 1.1.2.2 2005/05/19 15:52:24 mmatthews Exp $
45  */

46 public abstract class BaseTestCase extends TestCase {
47     /**
48      * JDBC URL, initialized from com.mysql.jdbc.testsuite.url system property,
49      * or defaults to jdbc:mysql:///test
50      */

51     protected static String JavaDoc dbUrl = "jdbc:mysql:///test";
52
53     /** Instance counter */
54     private static int instanceCount = 1;
55
56     private final static String JavaDoc ADMIN_CONNECTION_PROPERTY_NAME = "com.mysql.jdbc.testsuite.admin-url";
57
58     /** Connection to server, initialized in setUp() Cleaned up in tearDown(). */
59     protected Connection JavaDoc conn = null;
60
61     /**
62      * PreparedStatement to be used in tests, not initialized. Cleaned up in
63      * tearDown().
64      */

65     protected PreparedStatement JavaDoc pstmt = null;
66
67     /**
68      * ResultSet to be used in tests, not initialized. Cleaned up in tearDown().
69      */

70     protected ResultSet JavaDoc rs = null;
71
72     /**
73      * Statement to be used in tests, initialized in setUp(). Cleaned up in
74      * tearDown().
75      */

76     protected Statement JavaDoc stmt = null;
77
78     /** The driver to use */
79     protected String JavaDoc dbClass = "com.mysql.jdbc.Driver";
80
81     /** My instance number */
82     private int myInstanceNumber = 0;
83
84     /** list of Tables to be dropped in tearDown */
85     private List JavaDoc createdTables;
86
87     /**
88      * Creates a new BaseTestCase object.
89      *
90      * @param name
91      * The name of the JUnit test case
92      */

93     public BaseTestCase(String JavaDoc name) {
94         super(name);
95         this.myInstanceNumber = instanceCount++;
96
97         String JavaDoc newDbUrl = System.getProperty("com.mysql.jdbc.testsuite.url");
98
99         if ((newDbUrl != null) && (newDbUrl.trim().length() != 0)) {
100             dbUrl = newDbUrl;
101         }
102
103         String JavaDoc newDriver = System
104                 .getProperty("com.mysql.jdbc.testsuite.driver");
105
106         if ((newDriver != null) && (newDriver.trim().length() != 0)) {
107             this.dbClass = newDriver;
108         }
109     }
110
111     /**
112      * Creates resources used by all tests.
113      *
114      * @throws Exception
115      * if an error occurs.
116      */

117     public void setUp() throws Exception JavaDoc {
118         System.out.println("Loading JDBC driver '" + this.dbClass + "'");
119         Class.forName(this.dbClass).newInstance();
120         System.out.println("Done.\n");
121         createdTables = new ArrayList JavaDoc();
122
123         // System.out.println("Establishing connection to database '" + dbUrl
124
// + "'");
125

126         if (this.dbClass.equals("gwe.sql.gweMysqlDriver")) {
127             try {
128                 this.conn = DriverManager.getConnection(dbUrl, "", "");
129             } catch (Exception JavaDoc ex) {
130                 ex.printStackTrace();
131                 fail();
132             }
133         } else {
134             try {
135                 this.conn = DriverManager.getConnection(dbUrl);
136             } catch (Exception JavaDoc ex) {
137                 ex.printStackTrace();
138                 fail();
139             }
140         }
141
142         System.out.println("Done.\n");
143         this.stmt = this.conn.createStatement();
144
145         try {
146             this.rs = this.stmt.executeQuery("SELECT VERSION()");
147             this.rs.next();
148             logDebug("Connected to " + this.rs.getString(1));
149             this.rs.close();
150             this.rs = null;
151         } finally {
152             if (this.rs != null) {
153                 this.rs.close();
154             }
155         }
156     }
157
158     /**
159      * Destroys resources created during the test case.
160      *
161      * @throws Exception
162      * DOCUMENT ME!
163      */

164     public void tearDown() throws Exception JavaDoc {
165         if (this.rs != null) {
166             try {
167                 this.rs.close();
168             } catch (SQLException JavaDoc SQLE) {
169                 ;
170             }
171         }
172
173         for (int i = 0; i < createdTables.size(); i++) {
174             try {
175                 dropTable((String JavaDoc) createdTables.get(i));
176             } catch (SQLException JavaDoc SQLE) {
177                 ;
178             }
179         }
180
181         if (this.stmt != null) {
182             try {
183                 this.stmt.close();
184             } catch (SQLException JavaDoc SQLE) {
185                 ;
186             }
187         }
188
189         if (this.pstmt != null) {
190             try {
191                 this.pstmt.close();
192             } catch (SQLException JavaDoc SQLE) {
193                 ;
194             }
195         }
196
197         if (this.conn != null) {
198             try {
199                 this.conn.close();
200             } catch (SQLException JavaDoc SQLE) {
201                 ;
202             }
203         }
204     }
205
206     protected Connection JavaDoc getAdminConnection() throws SQLException JavaDoc {
207         return getAdminConnectionWithProps(new Properties JavaDoc());
208     }
209
210     protected boolean isAdminConnectionConfigured() {
211         return System.getProperty(ADMIN_CONNECTION_PROPERTY_NAME) != null;
212     }
213
214     protected Connection JavaDoc getAdminConnectionWithProps(Properties JavaDoc props)
215             throws SQLException JavaDoc {
216         String JavaDoc adminUrl = System.getProperty(ADMIN_CONNECTION_PROPERTY_NAME);
217
218         if (adminUrl != null) {
219             return DriverManager.getConnection(adminUrl, props);
220         } else {
221             return null;
222         }
223     }
224
225     /**
226      * Returns a new connection with the given properties
227      *
228      * @param props
229      * the properties to use (the URL will come from the standard for
230      * this testcase).
231      *
232      * @return a new connection using the given properties.
233      *
234      * @throws SQLException
235      * DOCUMENT ME!
236      */

237     protected Connection JavaDoc getConnectionWithProps(Properties JavaDoc props)
238             throws SQLException JavaDoc {
239         return DriverManager.getConnection(dbUrl, props);
240     }
241
242     /**
243      * Returns the per-instance counter (for messages when multi-threading
244      * stress tests)
245      *
246      * @return int the instance number
247      */

248     protected int getInstanceNumber() {
249         return this.myInstanceNumber;
250     }
251
252     /**
253      * Returns the named MySQL variable from the currently connected server.
254      *
255      * @param variableName
256      * the name of the variable to return
257      *
258      * @return the value of the given variable, or NULL if it doesn't exist
259      *
260      * @throws SQLException
261      * if an error occurs
262      */

263     protected String JavaDoc getMysqlVariable(String JavaDoc variableName) throws SQLException JavaDoc {
264         return getMysqlVariable(this.conn, variableName);
265     }
266
267     protected String JavaDoc getMysqlVariable(Connection JavaDoc c, String JavaDoc variableName)
268             throws SQLException JavaDoc {
269         Object JavaDoc value = getSingleIndexedValueWithQuery(c, 2,
270                 "SHOW VARIABLES LIKE '" + variableName + "'");
271
272         if (value != null) {
273             return value.toString();
274         }
275
276         return null;
277
278     }
279
280     protected int getRowCount(String JavaDoc tableName) throws SQLException JavaDoc {
281         ResultSet JavaDoc countRs = null;
282
283         try {
284             countRs = this.stmt.executeQuery("SELECT COUNT(*) FROM "
285                     + tableName);
286
287             countRs.next();
288
289             return countRs.getInt(1);
290         } finally {
291             if (countRs != null) {
292                 countRs.close();
293             }
294         }
295     }
296
297     protected Object JavaDoc getSingleIndexedValueWithQuery(int columnIndex,
298             String JavaDoc query) throws SQLException JavaDoc {
299         return getSingleIndexedValueWithQuery(this.conn, columnIndex, query);
300     }
301
302     protected Object JavaDoc getSingleIndexedValueWithQuery(Connection JavaDoc c,
303             int columnIndex, String JavaDoc query) throws SQLException JavaDoc {
304         ResultSet JavaDoc valueRs = null;
305
306         Statement JavaDoc svStmt = null;
307
308         try {
309             svStmt = c.createStatement();
310
311             valueRs = svStmt.executeQuery(query);
312
313             if (!valueRs.next()) {
314                 return null;
315             }
316
317             return valueRs.getObject(columnIndex);
318         } finally {
319             if (valueRs != null) {
320                 valueRs.close();
321             }
322
323             if (svStmt != null) {
324                 svStmt.close();
325             }
326         }
327     }
328
329     protected Object JavaDoc getSingleValue(String JavaDoc tableName, String JavaDoc columnName,
330             String JavaDoc whereClause) throws SQLException JavaDoc {
331         return getSingleValueWithQuery("SELECT " + columnName + " FROM "
332                 + tableName + ((whereClause == null) ? "" : whereClause));
333     }
334
335     protected Object JavaDoc getSingleValueWithQuery(String JavaDoc query) throws SQLException JavaDoc {
336         return getSingleIndexedValueWithQuery(1, query);
337     }
338
339     /**
340      * Checks whether a certain system property is defined, in order to
341      * run/not-run certain tests
342      *
343      * @param propName
344      * the property name to check for
345      *
346      * @return true if the property is defined.
347      */

348     protected boolean runTestIfSysPropDefined(String JavaDoc propName) {
349         String JavaDoc prop = System.getProperty(propName);
350
351         return (prop != null) && (prop.length() > 0);
352     }
353
354     /**
355      * Checks whether the database we're connected to meets the given version
356      * minimum
357      *
358      * @param major
359      * the major version to meet
360      * @param minor
361      * the minor version to meet
362      *
363      * @return boolean if the major/minor is met
364      *
365      * @throws SQLException
366      * if an error occurs.
367      */

368     protected boolean versionMeetsMinimum(int major, int minor)
369             throws SQLException JavaDoc {
370         return versionMeetsMinimum(major, minor, 0);
371     }
372
373     /**
374      * Checks whether the database we're connected to meets the given version
375      * minimum
376      *
377      * @param major
378      * the major version to meet
379      * @param minor
380      * the minor version to meet
381      *
382      * @return boolean if the major/minor is met
383      *
384      * @throws SQLException
385      * if an error occurs.
386      */

387     protected boolean versionMeetsMinimum(int major, int minor, int subminor)
388             throws SQLException JavaDoc {
389         return (((com.mysql.jdbc.Connection) this.conn).versionMeetsMinimum(
390                 major, minor, subminor));
391     }
392
393     protected void createTable(String JavaDoc tableName, String JavaDoc columnsAndOtherStuff)
394             throws SQLException JavaDoc {
395         createdTables.add(tableName);
396         dropTable(tableName);
397
398         StringBuffer JavaDoc createSql = new StringBuffer JavaDoc(tableName.length()
399                 + columnsAndOtherStuff.length() + 10);
400         createSql.append("CREATE TABLE ");
401         createSql.append(tableName);
402         createSql.append(" ");
403         createSql.append(columnsAndOtherStuff);
404         this.stmt.executeUpdate(createSql.toString());
405     }
406
407     protected void dropTable(String JavaDoc tableName) throws SQLException JavaDoc {
408         this.stmt.executeUpdate("DROP TABLE IF EXISTS " + tableName);
409     }
410
411     public void logDebug(String JavaDoc message) {
412         if (System.getProperty("com.mysql.jdbc.testsuite.noDebugOutput") == null) {
413             System.err.println(message);
414         }
415     }
416
417     protected final boolean runLongTests() {
418         return runTestIfSysPropDefined("com.mysql.jdbc.testsuite.runLongTests");
419     }
420
421     protected Connection JavaDoc getConnectionWithProps(String JavaDoc url, Properties JavaDoc props)
422             throws SQLException JavaDoc {
423         return DriverManager.getConnection(url, props);
424     }
425 }
426
Popular Tags