JDocCoverage Report - 21.04.2006 22:02:51

Namemethod, %comment, %TODO@see
smallsql.junit.BasicTestCase154,0%   (318/7674)00

/* =============================================================
 * SmallSQL : a free Java DBMS library for the Java(tm) platform
 * =============================================================
 *
 * (C) Copyright 2004-2006, by Volker Berlin.
 *
 * Project Info:  http://www.smallsql.de/
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
 * USA.  
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
 * in the United States and other countries.]
 *
 * ---------------
 * Column.java
 * ---------------
 * BasicTestCase: Volker Berlin
 * 
 */
package smallsql.junit;

import junit.framework.*;

import java.math.BigDecimal;
import java.sql.*;

public class BasicTestCase extends TestCase {

    public BasicTestCase(){
        super();
    }

    public BasicTestCase(String name){
        super(makeNameValid(name));
    }
    
    private static String makeNameValid(String name){
    	return name.replace(',' , ';').replace('(','{');
    }
    
    void dropTable(Connection con, String name){
		try {
			Statement st = con.createStatement();
			st.execute("drop table "+name);
			st.close();
		} catch (SQLException e) {}
    }

    void dropView(Connection con, String name){
		try {
			Statement st = con.createStatement();
			st.execute("drop view "+name);
			st.close();
		} catch (SQLException e) {}
    }

	public void assertRSMetaData( ResultSet rs, String[] colNames, int[] types) throws Exception{
		ResultSetMetaData rm = rs.getMetaData();
		int count = rm.getColumnCount();
		assertEquals( "Column count:", colNames.length, count);
		for(int i=1; i<=count; i++){
			assertEquals("ColName "+i, colNames[i-1], rm.getColumnName(i));
			assertEquals("ColName "+i, colNames[i-1], rm.getColumnLabel(i));
			assertEquals("ColName "+i, types   [i-1], rm.getColumnType(i));
			switch(types[i-1]){
				case Types.VARCHAR:
					assertTrue  ("Wrong Precision (" + rm.getColumnTypeName(i) + ") for Column "+i, rm.getPrecision(i) > 0);
					break;
				case Types.INTEGER:
					assertTrue  ("Wrong Precision (" + rm.getColumnTypeName(i) + ") for Column "+i, rm.getPrecision(i) > 0);
					break;
			}
		}
	}
	
	private final static char[] digits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	private static String bytes2hex( byte[] bytes ){
		StringBuffer buf = new StringBuffer(bytes.length << 1);
		for(int i=0; i<bytes.length; i++){
			buf.append( digits[ (bytes[i] >> 4) & 0x0F ] );
			buf.append( digits[ (bytes[i]     ) & 0x0F ] );
		}
		return buf.toString();
	}
	
	public void assertEqualsObject( String msg, Object obj1, Object obj2 ){
		if(obj1 instanceof byte[]){
			if(!java.util.Arrays.equals( (byte[])obj1, (byte[])obj2)){
				fail(msg + " expexted:" + bytes2hex((byte[])obj1)+ " bat was:"+bytes2hex((byte[])obj2));
			}
		}else{ 
			if(obj1 instanceof BigDecimal)
				if(((BigDecimal)obj1).compareTo((BigDecimal)obj2) == 0) return;
		
			assertEquals( msg, obj1, obj2);
		}
	}
	
    public void assertEqualsObject( String msg, Object obj1, Object obj2, boolean needTrim ){
        if(needTrim && obj1 != null){
            // trim for CHAR and BINARY
            if(obj1 instanceof String) obj1 = ((String)obj1).trim();
            if(obj1 instanceof byte[]){
                byte[] tmp = (byte[])obj1;
                int k=tmp.length-1;
                for(; k>= 0; k--) if(tmp[k] != 0) break;
                k++;
                byte[] tmp2 = new byte[k];
                System.arraycopy( tmp, 0, tmp2, 0, k);
                obj1 = tmp2;
            }
        }
		if(needTrim && obj2 != null){
			// trim for CHAR and BINARY
			if(obj2 instanceof String) obj2 = ((String)obj2).trim();
			if(obj2 instanceof byte[]){
				byte[] tmp = (byte[])obj2;
				int k=tmp.length-1;
				for(; k>= 0; k--) if(tmp[k] != 0) break;
				k++;
				byte[] tmp2 = new byte[k];
				System.arraycopy( tmp, 0, tmp2, 0, k);
				obj2 = tmp2;
			}
		}
		assertEqualsObject( msg, obj1, obj2);
    }
    
	void assertRowCount(int sollCount, String sql ) throws Exception{
		Connection con = AllTests.getConnection();
		Statement st = con.createStatement();
		ResultSet rs = st.executeQuery(sql);
		int colCount = rs.getMetaData().getColumnCount();
		int count = 0;
		//System.out.println(sql);
		while(rs.next()){
			count++;
			for(int i=1; i<=colCount; i++){
				rs.getObject(i);
				//System.out.print( " "+rs.getObject(i));
			}
			//System.out.println();
		}
		assertEquals( "Wrong row count", sollCount, count);
		for(int i=1; i<=colCount; i++){
			try{
				// if not a SQLException occur then it is an error
				fail( "Column:"+i+" Value:"+String.valueOf(rs.getObject(i)));
			}catch(SQLException e){}
		}
		assertFalse( "Scroll after last", rs.next() );
	}

	
    private boolean string2boolean( String val){
        try{
            return Double.parseDouble( val ) != 0;
        }catch(NumberFormatException e){}
        return "true".equalsIgnoreCase( val ) || "yes".equalsIgnoreCase( val ) || "t".equalsIgnoreCase( val );
    }
	
	/**
	 * Test a single Value of a the ResultSet that was produce from the SQL
	 */
   	void assertEqualsRsValue(Object obj, String sql) throws Exception{
		Connection con = AllTests.getConnection();
		Statement st = con.createStatement();
		ResultSet rs = st.executeQuery(sql);
		assertTrue( "No row produce", rs.next());
        assertEqualsRsValue(obj,rs,false);
    }
    
    
    void assertEqualsRsValue(Object obj, ResultSet rs, boolean needTrim) throws Exception{
		assertEqualsObject( "Values not identical on read:", obj, rs.getObject(1), needTrim);
		if(obj instanceof Time){
			assertEquals("Time ist unterschiedlich:", obj, rs.getTime(1) );
			assertEquals("Time String ist unterschiedlich:", obj.toString(), rs.getString(1) );
		}
		if(obj instanceof Timestamp){
			assertEquals("Timestamp ist unterschiedlich:", obj, rs.getTimestamp(1) );
			assertEquals("Timestamp String ist unterschiedlich:", obj.toString(), rs.getString(1) );
		}
		if(obj instanceof Date){
			assertEquals("Date ist unterschiedlich:", obj, rs.getDate(1) );
			assertEquals("Date String ist unterschiedlich:", obj.toString(), rs.getString(1) );
		}
		if(obj instanceof String){
            assertEqualsObject("String ist unterschiedlich:", obj, rs.getString(1), needTrim );
			assertEquals("String Boolean ist unterschiedlich:", string2boolean((String)obj), rs.getBoolean(1) );
		}
		if(obj instanceof BigDecimal){
            if(!needTrim){
                assertEquals("BigDecimal ist unterschiedlich:", obj, rs.getBigDecimal(1) );
                assertEquals("Scale ist unterschiedlich:", ((BigDecimal)obj).scale(), rs.getMetaData().getScale(1));
            }
            assertEquals("Scale Meta ist unterschiedlich:", rs.getBigDecimal(1).scale(), rs.getMetaData().getScale(1));
			BigDecimal big2 = ((BigDecimal)obj).setScale(2,BigDecimal.ROUND_HALF_EVEN);
			assertEquals("BigDecimal mit scale ist unterschiedlich:", big2, rs.getBigDecimal(1, 2) );
		}
		if(obj instanceof Integer){
			assertEquals("Scale ist unterschiedlich:", 0, rs.getMetaData().getScale(1));
		}
		if(obj instanceof Number){
            long longValue = ((Number)obj).longValue();
			int intValue = ((Number)obj).intValue();
            if(longValue >= Integer.MAX_VALUE)
                intValue = Integer.MAX_VALUE;
            if(longValue <= Integer.MIN_VALUE)
                intValue = Integer.MIN_VALUE;
			assertEquals("int ist unterschiedlich:", intValue, rs.getInt(1) );
			assertEquals("long ist unterschiedlich:", longValue, rs.getLong(1) );
			if(intValue >= Short.MIN_VALUE && intValue <= Short.MAX_VALUE)
				assertEquals("short ist unterschiedlich:", (short)intValue, rs.getShort(1) );
			if(intValue >= Byte.MIN_VALUE && intValue <= Byte.MAX_VALUE)
				assertEquals("byte ist unterschiedlich:", (byte)intValue, rs.getByte(1) );
			
			double value = ((Number)obj).doubleValue();
			assertEquals("Double ist unterschiedlich:", value, rs.getDouble(1),0.0 );
			assertEquals("Float ist unterschiedlich:", (float)value, rs.getFloat(1),0.0 );
			String valueStr = obj.toString();
            if(!needTrim){
                assertEquals("Number String ist unterschiedlich:", valueStr, rs.getString(1) );
            }
			BigDecimal decimal = Double.isInfinite(value) || Double.isNaN(value) ? null : new BigDecimal(valueStr);
            assertEqualsObject("Number BigDecimal ist unterschiedlich:", decimal, rs.getBigDecimal(1) );
			assertEquals("Number boolean ist unterschiedlich:", value != 0, rs.getBoolean(1) );
		}
		if(obj == null){
			assertNull("String ist unterschiedlich:", rs.getString(1) );
			assertNull("Date ist unterschiedlich:", rs.getDate(1) );
			assertNull("Time ist unterschiedlich:", rs.getTime(1) );
			assertNull("Timestamp ist unterschiedlich:", rs.getTimestamp(1) );
			assertNull("BigDecimal ist unterschiedlich:", rs.getBigDecimal(1) );
			assertNull("BigDecimal mit Scale ist unterschiedlich:", rs.getBigDecimal(1, 2) );
			assertNull("Bytes mit Scale ist unterschiedlich:", rs.getBytes(1) );
			assertEquals("Double ist unterschiedlich:", 0, rs.getDouble(1),0 );
			assertEquals("Float ist unterschiedlich:", 0, rs.getFloat(1),0 );
			assertEquals("Long ist unterschiedlich:", 0, rs.getLong(1) );
			assertEquals("Int ist unterschiedlich:", 0, rs.getInt(1) );
			assertEquals("SmallInt ist unterschiedlich:", 0, rs.getShort(1) );
			assertEquals("TinyInt ist unterschiedlich:", 0, rs.getByte(1) );
			assertEquals("Boolean ist unterschiedlich:", false, rs.getBoolean(1) );
		}
		
		ResultSetMetaData metaData = rs.getMetaData();
		String className = metaData.getColumnClassName(1);
		assertNotNull( "ClassName:", className);
		if(obj != null){
			assertTrue("ClassName assignable: "+className+"<->"+obj.getClass().getName(), Class.forName(className).isAssignableFrom(obj.getClass()));
			assertTrue( "DisplaySize to small "+metaData.getColumnDisplaySize(1)+"<"+rs.getString(1).length()+" ("+rs.getString(1)+")", metaData.getColumnDisplaySize(1)>= rs.getString(1).length() );
		}
		

   	}
   	
	void printSQL(String sql) throws SQLException{
		Connection con = AllTests.getConnection();
		Statement st = con.createStatement();
		ResultSet rs = st.executeQuery(sql);
		printRS( rs );
	}
	
   	void printRS(ResultSet rs) throws SQLException{
   		int count = rs.getMetaData().getColumnCount();
		while(rs.next()){ 
			for(int i=1; i<=count; i++){
				System.out.print(rs.getString(i) + '\t');
			} 
			System.out.println();
		}

   	}
}