KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > smallsql > junit > BasicTestCase


1 /* =============================================================
2  * SmallSQL : a free Java DBMS library for the Java(tm) platform
3  * =============================================================
4  *
5  * (C) Copyright 2004-2006, by Volker Berlin.
6  *
7  * Project Info: http://www.smallsql.de/
8  *
9  * This library is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16  * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
17  * License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
22  * USA.
23  *
24  * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
25  * in the United States and other countries.]
26  *
27  * ---------------
28  * Column.java
29  * ---------------
30  * BasicTestCase: Volker Berlin
31  *
32  */

33 package smallsql.junit;
34
35 import junit.framework.*;
36
37 import java.io.*;
38 import java.math.BigDecimal JavaDoc;
39 import java.sql.*;
40
41 public class BasicTestCase extends TestCase {
42
43     public BasicTestCase(){
44         super();
45     }
46
47     public BasicTestCase(String JavaDoc name){
48         super(makeNameValid(name));
49     }
50     
51     private static String JavaDoc makeNameValid(String JavaDoc name){
52         return name.replace(',' , ';').replace('(','{');
53     }
54     
55     void dropTable(Connection con, String JavaDoc name) throws SQLException{
56         try {
57             Statement st = con.createStatement();
58             st.execute("drop table "+name);
59             st.close();
60         } catch (SQLException e) {
61             String JavaDoc msg = "" + e.getMessage();
62             if(msg.indexOf("[SmallSQL]Table")==0 && msg.indexOf(name)>0 && msg.indexOf("can't drop.")>0 ){
63                 return;
64             }
65             throw e;
66         }
67     }
68
69     void dropView(Connection con, String JavaDoc name){
70         try {
71             Statement st = con.createStatement();
72             st.execute("drop view "+name);
73             st.close();
74         } catch (SQLException e) {/* ignore it, if the view not exist */}
75     }
76
77     public void assertRSMetaData( ResultSet rs, String JavaDoc[] colNames, int[] types) throws Exception JavaDoc{
78         ResultSetMetaData rm = rs.getMetaData();
79         int count = rm.getColumnCount();
80         assertEquals( "Column count:", colNames.length, count);
81         for(int i=1; i<=count; i++){
82             assertEquals("Col "+i+" name", colNames[i-1], rm.getColumnName(i));
83             assertEquals("Col "+i+" label", colNames[i-1], rm.getColumnLabel(i));
84             assertEquals("Col "+i+" type", types [i-1], rm.getColumnType(i));
85             switch(types[i-1]){
86                 case Types.VARCHAR:
87                     assertTrue ("Wrong Precision (" + rm.getColumnTypeName(i) + ") for Column "+i+": "+rm.getPrecision(i), rm.getPrecision(i) > 0);
88                     break;
89                 case Types.INTEGER:
90                     assertTrue ("Wrong Precision (" + rm.getColumnTypeName(i) + ") for Column "+i, rm.getPrecision(i) > 0);
91                     break;
92             }
93         }
94     }
95     
96     private final static char[] digits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
97     private static String JavaDoc bytes2hex( byte[] bytes ){
98         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(bytes.length << 1);
99         for(int i=0; i<bytes.length; i++){
100             buf.append( digits[ (bytes[i] >> 4) & 0x0F ] );
101             buf.append( digits[ (bytes[i] ) & 0x0F ] );
102         }
103         return buf.toString();
104     }
105     
106     public void assertEqualsObject( String JavaDoc msg, Object JavaDoc obj1, Object JavaDoc obj2 ){
107         if(obj1 instanceof byte[]){
108             if(!java.util.Arrays.equals( (byte[])obj1, (byte[])obj2)){
109                 fail(msg + " expexted:" + bytes2hex((byte[])obj1)+ " bat was:"+bytes2hex((byte[])obj2));
110             }
111         }else{
112             if(obj1 instanceof BigDecimal JavaDoc)
113                 if(((BigDecimal JavaDoc)obj1).compareTo((BigDecimal JavaDoc)obj2) == 0) return;
114         
115             assertEquals( msg, obj1, obj2);
116         }
117     }
118     
119     public void assertEqualsObject( String JavaDoc msg, Object JavaDoc obj1, Object JavaDoc obj2, boolean needTrim ){
120         if(needTrim && obj1 != null){
121             // trim for CHAR and BINARY
122
if(obj1 instanceof String JavaDoc) obj1 = ((String JavaDoc)obj1).trim();
123             if(obj1 instanceof byte[]){
124                 byte[] tmp = (byte[])obj1;
125                 int k=tmp.length-1;
126                 for(; k>= 0; k--) if(tmp[k] != 0) break;
127                 k++;
128                 byte[] tmp2 = new byte[k];
129                 System.arraycopy( tmp, 0, tmp2, 0, k);
130                 obj1 = tmp2;
131             }
132         }
133         if(needTrim && obj2 != null){
134             // trim for CHAR and BINARY
135
if(obj2 instanceof String JavaDoc) obj2 = ((String JavaDoc)obj2).trim();
136             if(obj2 instanceof byte[]){
137                 byte[] tmp = (byte[])obj2;
138                 int k=tmp.length-1;
139                 for(; k>= 0; k--) if(tmp[k] != 0) break;
140                 k++;
141                 byte[] tmp2 = new byte[k];
142                 System.arraycopy( tmp, 0, tmp2, 0, k);
143                 obj2 = tmp2;
144             }
145         }
146         assertEqualsObject( msg, obj1, obj2);
147     }
148     
149     
150     void assertRowCount(int sollCount, String JavaDoc sql ) throws Exception JavaDoc{
151         Connection con = AllTests.getConnection();
152         Statement st = con.createStatement();
153         ResultSet rs = st.executeQuery(sql);
154         assertRowCount(sollCount,rs);
155     }
156     
157     
158     void assertRowCount(int sollCount, ResultSet rs ) throws Exception JavaDoc{
159         int colCount = rs.getMetaData().getColumnCount();
160         int count = 0;
161         //System.out.println(sql);
162
while(rs.next()){
163             count++;
164             for(int i=1; i<=colCount; i++){
165                 rs.getObject(i);
166                 //System.out.print( " "+rs.getObject(i));
167
}
168             //System.out.println();
169
}
170         assertEquals( "Wrong row count", sollCount, count);
171         for(int i=1; i<=colCount; i++){
172             try{
173                 // if not a SQLException occur then it is an error
174
fail( "Column:"+i+" Value:"+String.valueOf(rs.getObject(i)));
175             }catch(SQLException e){
176                 assertSQLException("01000", 0, e);
177             }
178         }
179         assertFalse( "Scroll after last", rs.next() );
180     }
181
182     
183     /**
184      * Identical to the Implementation from Utils.string2boolean
185      */

186     private boolean string2boolean( String JavaDoc val){
187         try{
188             return Double.parseDouble( val ) != 0;
189         }catch(NumberFormatException JavaDoc e){/*ignore it if it not a number*/}
190         return "true".equalsIgnoreCase( val ) || "yes".equalsIgnoreCase( val ) || "t".equalsIgnoreCase( val );
191     }
192     
193     /**
194      * Test a single Value of a the ResultSet that was produce from the SQL
195      */

196     void assertEqualsRsValue(Object JavaDoc obj, String JavaDoc sql) throws Exception JavaDoc{
197         Connection con = AllTests.getConnection();
198         Statement st = con.createStatement();
199         ResultSet rs = st.executeQuery(sql);
200         assertTrue( "No row produce", rs.next());
201         assertEqualsRsValue(obj,rs,false);
202     }
203     
204     
205     void assertEqualsRsValue(Object JavaDoc obj, ResultSet rs, boolean needTrim) throws Exception JavaDoc{
206         String JavaDoc name = rs.getMetaData().getColumnName(1);
207         assertEqualsObject( "Values not identical on read:", obj, rs.getObject(name), needTrim);
208         if(obj instanceof Time){
209             assertEquals("Time ist unterschiedlich:", obj, rs.getTime(name) );
210             assertEquals("Time String ist unterschiedlich:", obj.toString(), rs.getString(name) );
211         }
212         if(obj instanceof Timestamp){
213             assertEquals("Timestamp ist unterschiedlich:", obj, rs.getTimestamp(name) );
214             assertEquals("Timestamp String ist unterschiedlich:", obj.toString(), rs.getString(name) );
215         }
216         if(obj instanceof Date){
217             assertEquals("Date ist unterschiedlich:", obj, rs.getDate(name) );
218             assertEquals("Date String ist unterschiedlich:", obj.toString(), rs.getString(name) );
219         }
220         if(obj instanceof String JavaDoc){
221             assertEqualsObject("String ist unterschiedlich:", obj, rs.getString(name), needTrim );
222             assertEquals("String Boolean ist unterschiedlich:", string2boolean((String JavaDoc)obj), rs.getBoolean(name) );
223         }
224         if(obj instanceof BigDecimal JavaDoc){
225             if(!needTrim){
226                 assertEquals("BigDecimal ist unterschiedlich:", obj, rs.getBigDecimal(name) );
227                 assertEquals("Scale ist unterschiedlich:", ((BigDecimal JavaDoc)obj).scale(), rs.getMetaData().getScale(1));
228             }
229             assertEquals("Scale Meta ist unterschiedlich:", rs.getBigDecimal(name).scale(), rs.getMetaData().getScale(1));
230             BigDecimal JavaDoc big2 = ((BigDecimal JavaDoc)obj).setScale(2,BigDecimal.ROUND_HALF_EVEN);
231             assertEquals("BigDecimal mit scale ist unterschiedlich:", big2, rs.getBigDecimal(name, 2) );
232         }
233         if(obj instanceof Integer JavaDoc){
234             assertEquals("Scale ist unterschiedlich:", 0, rs.getMetaData().getScale(1));
235         }
236         if(obj instanceof Number JavaDoc){
237             long longValue = ((Number JavaDoc)obj).longValue();
238             int intValue = ((Number JavaDoc)obj).intValue();
239             if(longValue >= Integer.MAX_VALUE)
240                 intValue = Integer.MAX_VALUE;
241             if(longValue <= Integer.MIN_VALUE)
242                 intValue = Integer.MIN_VALUE;
243             assertEquals("int ist unterschiedlich:", intValue, rs.getInt(name) );
244             assertEquals("long ist unterschiedlich:", longValue, rs.getLong(name) );
245             if(intValue >= Short.MIN_VALUE && intValue <= Short.MAX_VALUE)
246                 assertEquals("short ist unterschiedlich:", (short)intValue, rs.getShort(name) );
247             if(intValue >= Byte.MIN_VALUE && intValue <= Byte.MAX_VALUE)
248                 assertEquals("byte ist unterschiedlich:", (byte)intValue, rs.getByte(name) );
249             
250             double value = ((Number JavaDoc)obj).doubleValue();
251             assertEquals("Double ist unterschiedlich:", value, rs.getDouble(name),0.0 );
252             assertEquals("Float ist unterschiedlich:", (float)value, rs.getFloat(name),0.0 );
253             String JavaDoc valueStr = obj.toString();
254             if(!needTrim){
255                 assertEquals("Number String ist unterschiedlich:", valueStr, rs.getString(name) );
256             }
257             BigDecimal JavaDoc decimal = Double.isInfinite(value) || Double.isNaN(value) ? null : new BigDecimal JavaDoc(valueStr);
258             assertEqualsObject("Number BigDecimal ist unterschiedlich:", decimal, rs.getBigDecimal(name) );
259             assertEquals("Number boolean ist unterschiedlich:", value != 0, rs.getBoolean(name) );
260         }
261         if(obj == null){
262             assertNull("String ist unterschiedlich:", rs.getString(name) );
263             assertNull("Date ist unterschiedlich:", rs.getDate(name) );
264             assertNull("Time ist unterschiedlich:", rs.getTime(name) );
265             assertNull("Timestamp ist unterschiedlich:", rs.getTimestamp(name) );
266             assertNull("BigDecimal ist unterschiedlich:", rs.getBigDecimal(name) );
267             assertNull("BigDecimal mit Scale ist unterschiedlich:", rs.getBigDecimal(name, 2) );
268             assertNull("Bytes mit Scale ist unterschiedlich:", rs.getBytes(name) );
269             assertEquals("Double ist unterschiedlich:", 0, rs.getDouble(name),0 );
270             assertEquals("Float ist unterschiedlich:", 0, rs.getFloat(name),0 );
271             assertEquals("Long ist unterschiedlich:", 0, rs.getLong(name) );
272             assertEquals("Int ist unterschiedlich:", 0, rs.getInt(name) );
273             assertEquals("SmallInt ist unterschiedlich:", 0, rs.getShort(name) );
274             assertEquals("TinyInt ist unterschiedlich:", 0, rs.getByte(name) );
275             assertEquals("Boolean ist unterschiedlich:", false, rs.getBoolean(name) );
276         }
277         
278         ResultSetMetaData metaData = rs.getMetaData();
279         String JavaDoc className = metaData.getColumnClassName(1);
280         assertNotNull( "ClassName:", className);
281         if(obj != null){
282             assertTrue("ClassName assignable: "+className+"<->"+obj.getClass().getName(), Class.forName(className).isAssignableFrom(obj.getClass()));
283             assertTrue( "DisplaySize to small "+metaData.getColumnDisplaySize(1)+"<"+rs.getString(name).length()+" ("+rs.getString(name)+")", metaData.getColumnDisplaySize(1)>= rs.getString(name).length() );
284         }
285         
286
287     }
288     
289     
290     void assertSQLException(String JavaDoc sqlstate, int vendorCode, SQLException ex) {
291         StringWriter sw = new StringWriter();
292         ex.printStackTrace(new PrintWriter(sw));
293         assertEquals( "Vendor Errorcode:"+sw, vendorCode, ex.getErrorCode() );
294         assertEquals( "SQL State:"+sw, sqlstate, ex.getSQLState());
295     }
296     
297
298     
299     void printSQL(String JavaDoc sql) throws SQLException{
300         Connection con = AllTests.getConnection();
301         Statement st = con.createStatement();
302         ResultSet rs = st.executeQuery(sql);
303         printRS( rs );
304     }
305     
306     void printRS(ResultSet rs) throws SQLException{
307         int count = rs.getMetaData().getColumnCount();
308         while(rs.next()){
309             for(int i=1; i<=count; i++){
310                 System.out.print(rs.getString(i) + '\t');
311             }
312             System.out.println();
313         }
314
315     }
316 }
Popular Tags