Moved tests from testsuite to jdbc

This commit is contained in:
Arjen Poutsma
2008-10-30 17:35:13 +00:00
parent a02ee196b5
commit 6c4941bbc5
17 changed files with 190 additions and 2 deletions

View File

@@ -1,253 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer;
import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer;
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
import org.springframework.jdbc.support.incrementer.PostgreSQLSequenceMaxValueIncrementer;
/**
* @author Juergen Hoeller
* @since 27.02.2004
*/
public class DataFieldMaxValueIncrementerTests extends TestCase {
public void testHsqlMaxValueIncrementer() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 2);
con.createStatement();
conControl.setReturnValue(stmt, 2);
stmt.executeUpdate("insert into myseq values(null)");
stmtControl.setReturnValue(1, 6);
stmt.executeQuery("select max(identity()) from myseq");
stmtControl.setReturnValue(rs, 6);
rs.next();
rsControl.setReturnValue(true, 6);
for (long i = 0; i < 6; i++) {
rs.getLong(1);
rsControl.setReturnValue(i);
}
rs.close();
rsControl.setVoidCallable(6);
stmt.executeUpdate("delete from myseq where seq < 2");
stmtControl.setReturnValue(1);
stmt.executeUpdate("delete from myseq where seq < 5");
stmtControl.setReturnValue(1);
stmt.close();
stmtControl.setVoidCallable(2);
con.close();
conControl.setVoidCallable(2);
dsControl.replay();
conControl.replay();
stmtControl.replay();
rsControl.replay();
HsqlMaxValueIncrementer incrementer = new HsqlMaxValueIncrementer();
incrementer.setDataSource(ds);
incrementer.setIncrementerName("myseq");
incrementer.setColumnName("seq");
incrementer.setCacheSize(3);
incrementer.setPaddingLength(3);
incrementer.afterPropertiesSet();
assertEquals(0, incrementer.nextIntValue());
assertEquals(1, incrementer.nextLongValue());
assertEquals("002", incrementer.nextStringValue());
assertEquals(3, incrementer.nextIntValue());
assertEquals(4, incrementer.nextLongValue());
dsControl.verify();
conControl.verify();
stmtControl.verify();
rsControl.verify();
}
public void testMySQLMaxValueIncrementer() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 2);
con.createStatement();
conControl.setReturnValue(stmt, 2);
stmt.executeUpdate("update myseq set seq = last_insert_id(seq + 2)");
stmtControl.setReturnValue(1, 2);
stmt.executeQuery("select last_insert_id()");
stmtControl.setReturnValue(rs, 2);
rs.next();
rsControl.setReturnValue(true, 2);
rs.getLong(1);
rsControl.setReturnValue(2);
rs.getLong(1);
rsControl.setReturnValue(4);
rs.close();
rsControl.setVoidCallable(2);
stmt.close();
stmtControl.setVoidCallable(2);
con.close();
conControl.setVoidCallable(2);
dsControl.replay();
conControl.replay();
stmtControl.replay();
rsControl.replay();
MySQLMaxValueIncrementer incrementer = new MySQLMaxValueIncrementer();
incrementer.setDataSource(ds);
incrementer.setIncrementerName("myseq");
incrementer.setColumnName("seq");
incrementer.setCacheSize(2);
incrementer.setPaddingLength(1);
incrementer.afterPropertiesSet();
assertEquals(1, incrementer.nextIntValue());
assertEquals(2, incrementer.nextLongValue());
assertEquals("3", incrementer.nextStringValue());
assertEquals(4, incrementer.nextLongValue());
dsControl.verify();
conControl.verify();
stmtControl.verify();
rsControl.verify();
}
public void testPostgreSQLSequenceMaxValueIncrementer() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 2);
con.createStatement();
conControl.setReturnValue(stmt, 2);
stmt.executeQuery("select nextval('myseq')");
stmtControl.setReturnValue(rs, 2);
rs.next();
rsControl.setReturnValue(true, 2);
rs.getLong(1);
rsControl.setReturnValue(10);
rs.getLong(1);
rsControl.setReturnValue(12);
rs.close();
rsControl.setVoidCallable(2);
stmt.close();
stmtControl.setVoidCallable(2);
con.close();
conControl.setVoidCallable(2);
dsControl.replay();
conControl.replay();
stmtControl.replay();
rsControl.replay();
PostgreSQLSequenceMaxValueIncrementer incrementer = new PostgreSQLSequenceMaxValueIncrementer();
incrementer.setDataSource(ds);
incrementer.setIncrementerName("myseq");
incrementer.setPaddingLength(5);
incrementer.afterPropertiesSet();
assertEquals("00010", incrementer.nextStringValue());
assertEquals(12, incrementer.nextIntValue());
dsControl.verify();
conControl.verify();
stmtControl.verify();
rsControl.verify();
}
public void testOracleSequenceMaxValueIncrementer() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 2);
con.createStatement();
conControl.setReturnValue(stmt, 2);
stmt.executeQuery("select myseq.nextval from dual");
stmtControl.setReturnValue(rs, 2);
rs.next();
rsControl.setReturnValue(true, 2);
rs.getLong(1);
rsControl.setReturnValue(10);
rs.getLong(1);
rsControl.setReturnValue(12);
rs.close();
rsControl.setVoidCallable(2);
stmt.close();
stmtControl.setVoidCallable(2);
con.close();
conControl.setVoidCallable(2);
dsControl.replay();
conControl.replay();
stmtControl.replay();
rsControl.replay();
OracleSequenceMaxValueIncrementer incrementer = new OracleSequenceMaxValueIncrementer();
incrementer.setDataSource(ds);
incrementer.setIncrementerName("myseq");
incrementer.setPaddingLength(2);
incrementer.afterPropertiesSet();
assertEquals(10, incrementer.nextLongValue());
assertEquals("12", incrementer.nextStringValue());
dsControl.verify();
conControl.verify();
stmtControl.verify();
rsControl.verify();
}
}

View File

@@ -1,161 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
/**
* @author Juergen Hoeller
* @since 17.12.2003
*/
public class DefaultLobHandlerTests extends TestCase {
public void testGetBlobAsBytes() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getBytes(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getBlobAsBytes(rs, 1);
rsControl.verify();
}
public void testGetBlobAsBinaryStream() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getBinaryStream(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getBlobAsBinaryStream(rs, 1);
rsControl.verify();
}
public void testGetClobAsString() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getString(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getClobAsString(rs, 1);
rsControl.verify();
}
public void testGetClobAsAsciiStream() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getAsciiStream(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getClobAsAsciiStream(rs, 1);
rsControl.verify();
}
public void testGetClobAsCharacterStream() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getCharacterStream(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getClobAsCharacterStream(rs, 1);
rsControl.verify();
}
public void testSetBlobAsBytes() throws SQLException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
byte[] content = "testContent".getBytes();
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setBytes(1, content);
psControl.replay();
lobCreator.setBlobAsBytes(ps, 1, content);
psControl.verify();
}
public void testSetBlobAsBinaryStream() throws SQLException, IOException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
InputStream bis = new ByteArrayInputStream("testContent".getBytes());
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setBinaryStream(1, bis, 11);
psControl.replay();
lobCreator.setBlobAsBinaryStream(ps, 1, bis, 11);
psControl.verify();
}
public void testSetClobAsString() throws SQLException, IOException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
String content = "testContent";
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setString(1, content);
psControl.replay();
lobCreator.setClobAsString(ps, 1, content);
psControl.verify();
}
public void testSetClobAsAsciiStream() throws SQLException, IOException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
InputStream bis = new ByteArrayInputStream("testContent".getBytes());
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setAsciiStream(1, bis, 11);
psControl.replay();
lobCreator.setClobAsAsciiStream(ps, 1, bis, 11);
psControl.verify();
}
public void testSetClobAsCharacterStream() throws SQLException, IOException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
Reader str = new StringReader("testContent");
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setCharacterStream(1, str, 11);
psControl.replay();
lobCreator.setClobAsCharacterStream(ps, 1, str, 11);
psControl.verify();
}
}

View File

@@ -1,43 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import junit.framework.TestCase;
/**
* Unit tests for JdbcUtils.
*
* @author Thomas Risberg
*/
public class JdbcUtilsTests extends TestCase {
public void testCommonDatabaseName() {
assertEquals("Wrong db name", "Oracle", JdbcUtils.commonDatabaseName("Oracle"));
assertEquals("Wrong db name", "DB2", JdbcUtils.commonDatabaseName("DB2-for-Spring"));
assertEquals("Wrong db name", "Sybase", JdbcUtils.commonDatabaseName("Sybase SQL Server"));
assertEquals("Wrong db name", "Sybase", JdbcUtils.commonDatabaseName("Adaptive Server Enterprise"));
assertEquals("Wrong db name", "MySQL", JdbcUtils.commonDatabaseName("MySQL"));
}
public void testConvertUnderscoreNameToPropertyName() {
assertEquals("Wrong property name", "myName", JdbcUtils.convertUnderscoreNameToPropertyName("MY_NAME"));
assertEquals("Wrong property name", "yourName", JdbcUtils.convertUnderscoreNameToPropertyName("yOUR_nAME"));
assertEquals("Wrong property name", "AName", JdbcUtils.convertUnderscoreNameToPropertyName("a_name"));
assertEquals("Wrong property name", "someoneElsesName", JdbcUtils.convertUnderscoreNameToPropertyName("someone_elses_name"));
}
}

View File

@@ -1,112 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import junit.framework.TestCase;
/**
* Tests for the KeyHolder and GeneratedKeyHolder
* and it appears that JdbcUtils doesn't work exactly as documented.
*
* @author trisberg
* @since Jul 18, 2004
*/
public class KeyHolderTests extends TestCase {
private KeyHolder kh;
public void setUp() {
kh = new GeneratedKeyHolder();
}
public void testSingleKey(){
LinkedList l = new LinkedList();
HashMap m = new HashMap(1);
m.put("key", new Integer(1));
l.add(m);
kh.getKeyList().addAll(l);
assertEquals("single key should be returned", 1, kh.getKey().intValue());
}
public void testSingleKeyNonNumeric(){
LinkedList l = new LinkedList();
HashMap m = new HashMap(1);
m.put("key", "1");
l.add(m);
kh.getKeyList().addAll(l);
try {
kh.getKey().intValue();
}
catch (DataRetrievalFailureException e) {
assertTrue(e.getMessage().startsWith("The generated key is not of a supported numeric type."));
}
}
public void testNoKeyReturnedInMap(){
LinkedList l = new LinkedList();
HashMap m = new HashMap();
l.add(m);
kh.getKeyList().addAll(l);
try {
kh.getKey();
}
catch (DataRetrievalFailureException e) {
assertTrue(e.getMessage().startsWith("Unable to retrieve the generated key."));
}
}
public void testMultipleKeys(){
LinkedList l = new LinkedList();
HashMap m = new HashMap(1);
m.put("key", new Integer(1));
m.put("seq", new Integer(2));
l.add(m);
kh.getKeyList().addAll(l);
Map keyMap = kh.getKeys();
assertEquals("two keys should be in the map", 2, keyMap.size());
try {
kh.getKey();
}
catch (InvalidDataAccessApiUsageException e) {
assertTrue(e.getMessage().startsWith("The getKey method should only be used when a single key is returned."));
}
}
public void testMultipleKeyRows(){
LinkedList l = new LinkedList();
HashMap m = new HashMap(1);
m.put("key", new Integer(1));
m.put("seq", new Integer(2));
l.add(m);
l.add(m);
kh.getKeyList().addAll(l);
assertEquals("two rows should be in the list", 2, kh.getKeyList().size());
try {
kh.getKeys();
}
catch (InvalidDataAccessApiUsageException e) {
assertTrue(e.getMessage().startsWith("The getKeys method should only be used when keys for a single row are returned."));
}
}
}

View File

@@ -1,144 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor;
import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor;
/**
* @author Andre Biryukov
* @author Juergen Hoeller
*/
public class NativeJdbcExtractorTests extends TestCase {
public void testSimpleNativeJdbcExtractor() throws SQLException {
SimpleNativeJdbcExtractor extractor = new SimpleNativeJdbcExtractor();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl dbmdControl = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData dbmd = (DatabaseMetaData) dbmdControl.getMock();
MockControl con2Control = MockControl.createControl(Connection.class);
Connection con2 = (Connection) con2Control.getMock();
con.getMetaData();
conControl.setReturnValue(dbmd, 2);
dbmd.getConnection();
dbmdControl.setReturnValue(con2, 2);
conControl.replay();
dbmdControl.replay();
con2Control.replay();
Connection nativeCon = extractor.getNativeConnection(con);
assertEquals(con2, nativeCon);
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
stmt.getConnection();
stmtControl.setReturnValue(con);
stmtControl.replay();
nativeCon = extractor.getNativeConnectionFromStatement(stmt);
assertEquals(con2, nativeCon);
Statement nativeStmt = extractor.getNativeStatement(stmt);
assertEquals(nativeStmt, stmt);
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
psControl.replay();
PreparedStatement nativePs = extractor.getNativePreparedStatement(ps);
assertEquals(ps, nativePs);
MockControl csControl = MockControl.createControl(CallableStatement.class);
CallableStatement cs = (CallableStatement) csControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
cs.getResultSet();
csControl.setReturnValue(rs);
csControl.replay();
rsControl.replay();
CallableStatement nativeCs = extractor.getNativeCallableStatement(cs);
assertEquals(cs, nativeCs);
ResultSet nativeRs = extractor.getNativeResultSet(cs.getResultSet());
assertEquals(nativeRs, rs);
conControl.verify();
dbmdControl.verify();
con2Control.verify();
stmtControl.verify();
psControl.verify();
csControl.verify();
rsControl.verify();
}
public void testCommonsDbcpNativeJdbcExtractor() throws SQLException {
CommonsDbcpNativeJdbcExtractor extractor = new CommonsDbcpNativeJdbcExtractor();
assertFalse(extractor.isNativeConnectionNecessaryForNativeStatements());
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
con.getMetaData();
conControl.setReturnValue(null, 2);
stmt.getConnection();
stmtControl.setReturnValue(con, 1);
conControl.replay();
stmtControl.replay();
Connection nativeConnection = extractor.getNativeConnection(con);
assertEquals(con, nativeConnection);
nativeConnection = extractor.getNativeConnectionFromStatement(stmt);
assertEquals(con, nativeConnection);
assertEquals(stmt, extractor.getNativeStatement(stmt));
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
psControl.replay();
assertEquals(ps, extractor.getNativePreparedStatement(ps));
MockControl csControl = MockControl.createControl(CallableStatement.class);
CallableStatement cs = (CallableStatement) csControl.getMock();
csControl.replay();
assertEquals(cs, extractor.getNativePreparedStatement(cs));
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rsControl.replay();
assertEquals(rs, extractor.getNativeResultSet(rs));
conControl.verify();
stmtControl.verify();
psControl.verify();
}
}

View File

@@ -1,153 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.SQLException;
import java.sql.BatchUpdateException;
import junit.framework.TestCase;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.dao.CannotSerializeTransactionException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.InvalidResultSetAccessException;
/**
* @author Rod Johnson
*/
public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase {
private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes();
static {
ERROR_CODES.setBadSqlGrammarCodes(new String[] { "1", "2" });
ERROR_CODES.setInvalidResultSetAccessCodes(new String[] { "3", "4" });
ERROR_CODES.setDataAccessResourceFailureCodes(new String[] { "5" });
ERROR_CODES.setDataIntegrityViolationCodes(new String[] { "6" });
ERROR_CODES.setCannotAcquireLockCodes(new String[] { "7" });
ERROR_CODES.setDeadlockLoserCodes(new String[] { "8" });
ERROR_CODES.setCannotSerializeTransactionCodes(new String[] { "9" });
}
public void testErrorCodeTranslation() {
SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
SQLException badSqlEx = new SQLException("", "", 1);
BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
assertEquals("SQL", bsgex.getSql());
assertEquals(badSqlEx, bsgex.getSQLException());
SQLException invResEx = new SQLException("", "", 4);
InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
assertEquals("SQL", irsex.getSql());
assertEquals(invResEx, irsex.getSQLException());
checkTranslation(sext, 5, DataAccessResourceFailureException.class);
checkTranslation(sext, 6, DataIntegrityViolationException.class);
checkTranslation(sext, 7, CannotAcquireLockException.class);
checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
checkTranslation(sext, 9, CannotSerializeTransactionException.class);
// Test fallback. We assume that no database will ever return this error code,
// but 07xxx will be bad grammar picked up by the fallback SQLState translator
SQLException sex = new SQLException("", "07xxx", 666666666);
BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
assertEquals("SQL2", bsgex2.getSql());
assertEquals(sex, bsgex2.getSQLException());
}
private void checkTranslation(SQLExceptionTranslator sext, int errorCode, Class exClass) {
SQLException sex = new SQLException("", "", errorCode);
DataAccessException ex = sext.translate("", "", sex);
assertTrue(exClass.isInstance(ex));
assertTrue(ex.getCause() == sex);
}
public void testBatchExceptionTranslation() {
SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
SQLException badSqlEx = new SQLException("", "", 1);
BatchUpdateException batchUdateEx = new BatchUpdateException();
batchUdateEx.setNextException(badSqlEx);
BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", batchUdateEx);
assertEquals("SQL", bsgex.getSql());
assertEquals(badSqlEx, bsgex.getSQLException());
}
public void testCustomTranslateMethodTranslation() {
final String TASK = "TASK";
final String SQL = "SQL SELECT *";
final DataAccessException customDex = new DataAccessException("") {};
final SQLException badSqlEx = new SQLException("", "", 1);
SQLException intVioEx = new SQLException("", "", 6);
SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator() {
protected DataAccessException customTranslate(String task, String sql, SQLException sqlex) {
assertEquals(TASK, task);
assertEquals(SQL, sql);
return (sqlex == badSqlEx) ? customDex : null;
}
};
sext.setSqlErrorCodes(ERROR_CODES);
// Shouldn't custom translate this
assertEquals(customDex, sext.translate(TASK, SQL, badSqlEx));
DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, intVioEx);
assertEquals(intVioEx, diex.getCause());
}
public void testCustomExceptionTranslation() {
final String TASK = "TASK";
final String SQL = "SQL SELECT *";
final SQLErrorCodes customErrorCodes = new SQLErrorCodes();
final CustomSQLErrorCodesTranslation customTranslation = new CustomSQLErrorCodesTranslation();
customErrorCodes.setBadSqlGrammarCodes(new String[] {"1", "2"});
customErrorCodes.setDataIntegrityViolationCodes(new String[] {"3", "4"});
customTranslation.setErrorCodes(new String[] {"1"});
customTranslation.setExceptionClass(CustomErrorCodeException.class);
customErrorCodes.setCustomTranslations(new CustomSQLErrorCodesTranslation[] {customTranslation});
SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator();
sext.setSqlErrorCodes(customErrorCodes);
// Should custom translate this
SQLException badSqlEx = new SQLException("", "", 1);
assertEquals(CustomErrorCodeException.class, sext.translate(TASK, SQL, badSqlEx).getClass());
assertEquals(badSqlEx, sext.translate(TASK, SQL, badSqlEx).getCause());
// Shouldn't custom translate this
SQLException invResEx = new SQLException("", "", 3);
DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, invResEx);
assertEquals(invResEx, diex.getCause());
// Shouldn't custom translate this - invalid class
try {
customTranslation.setExceptionClass(String.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
}

View File

@@ -1,324 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
* Tests for SQLErrorCodes loading.
*
* @author Rod Johnson
* @author Thomas Risberg
*/
public class SQLErrorCodesFactoryTests extends TestCase {
/**
* Check that a default instance returns empty error codes for an unknown database.
*/
public void testDefaultInstanceWithNoSuchDatabase() {
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("xx");
assertTrue(sec.getBadSqlGrammarCodes().length == 0);
assertTrue(sec.getDataIntegrityViolationCodes().length == 0);
}
/**
* Check that a known database produces recognizable codes.
*/
public void testDefaultInstanceWithOracle() {
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("Oracle");
assertIsOracle(sec);
}
private void assertIsOracle(SQLErrorCodes sec) {
assertTrue(sec.getBadSqlGrammarCodes().length > 0);
assertTrue(sec.getDataIntegrityViolationCodes().length > 0);
// This had better be a Bad SQL Grammar code
assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0);
// This had better NOT be
assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "9xx42") >= 0);
}
private void assertIsHsql(SQLErrorCodes sec) {
assertTrue(sec.getBadSqlGrammarCodes().length > 0);
assertTrue(sec.getDataIntegrityViolationCodes().length > 0);
// This had better be a Bad SQL Grammar code
assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-22") >= 0);
// This had better NOT be
assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-9") >= 0);
}
private void assertIsDB2(SQLErrorCodes sec) {
assertTrue(sec.getBadSqlGrammarCodes().length > 0);
assertTrue(sec.getDataIntegrityViolationCodes().length > 0);
assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0);
// This had better NOT be
assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-204") >= 0);
}
public void testLookupOrder() {
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
private int lookups = 0;
protected Resource loadResource(String path) {
++lookups;
if (lookups == 1) {
assertEquals(SQLErrorCodesFactory.SQL_ERROR_CODE_DEFAULT_PATH, path);
return null;
}
else {
// Should have only one more lookup
assertEquals(2, lookups);
assertEquals(SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH, path);
return null;
}
}
}
// Should have failed to load without error
TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory();
assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0);
assertTrue(sf.getErrorCodes("Oracle").getDataIntegrityViolationCodes().length == 0);
}
/**
* Check that user defined error codes take precedence.
*/
public void testFindUserDefinedCodes() {
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
protected Resource loadResource(String path) {
if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) {
return new ClassPathResource("test-error-codes.xml", SQLErrorCodesFactoryTests.class);
}
return null;
}
}
// Should have loaded without error
TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory();
assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0);
assertEquals(2, sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length);
assertEquals("1", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[0]);
assertEquals("2", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[1]);
}
public void testInvalidUserDefinedCodeFormat() {
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
protected Resource loadResource(String path) {
if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) {
// Guaranteed to be on the classpath, but most certainly NOT XML
return new ClassPathResource("SQLExceptionTranslator.class", SQLErrorCodesFactoryTests.class);
}
return null;
}
}
// Should have failed to load without error
TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory();
assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0);
assertEquals(0, sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length);
}
/**
* Check that custom error codes take precedence.
*/
public void testFindCustomCodes() {
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
protected Resource loadResource(String path) {
if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) {
return new ClassPathResource("custom-error-codes.xml", SQLErrorCodesFactoryTests.class);
}
return null;
}
}
// Should have loaded without error
TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory();
assertEquals(1, sf.getErrorCodes("Oracle").getCustomTranslations().length);
CustomSQLErrorCodesTranslation translation =
(CustomSQLErrorCodesTranslation) sf.getErrorCodes("Oracle").getCustomTranslations()[0];
assertEquals(CustomErrorCodeException.class, translation.getExceptionClass());
assertEquals(1, translation.getErrorCodes().length);
}
public void testDataSourceWithNullMetadata() throws Exception {
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setReturnValue(null);
mockConnection.close();
ctrlConnection.setVoidCallable();
ctrlConnection.replay();
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
ctrlDataSource.replay();
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(mockDataSource);
assertIsEmpty(sec);
ctrlConnection.verify();
ctrlDataSource.verify();
}
public void testGetFromDataSourceWithSQLException() throws Exception {
SQLException expectedSQLException = new SQLException();
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setThrowable(expectedSQLException);
ctrlDataSource.replay();
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(mockDataSource);
assertIsEmpty(sec);
ctrlDataSource.verify();
}
private void assertIsEmpty(SQLErrorCodes sec) {
// Codes should be empty
assertEquals(0, sec.getBadSqlGrammarCodes().length);
assertEquals(0, sec.getDataIntegrityViolationCodes().length);
}
private SQLErrorCodes getErrorCodesFromDataSource(String productName, SQLErrorCodesFactory factory) throws Exception {
MockControl mdControl = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData md = (DatabaseMetaData) mdControl.getMock();
md.getDatabaseProductName();
mdControl.setReturnValue(productName);
mdControl.replay();
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setReturnValue(md);
mockConnection.close();
ctrlConnection.setVoidCallable();
ctrlConnection.replay();
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
ctrlDataSource.replay();
SQLErrorCodesFactory secf = null;
if (factory != null) {
secf = factory;
}
else {
secf = SQLErrorCodesFactory.getInstance();
}
SQLErrorCodes sec = secf.getErrorCodes(mockDataSource);
mdControl.verify();
ctrlConnection.verify();
ctrlDataSource.verify();
SQLErrorCodes sec2 = secf.getErrorCodes(mockDataSource);
assertSame("Cached per DataSource", sec2, sec);
return sec;
}
public void testOracleRecognizedFromMetadata() throws Exception {
SQLErrorCodes sec = getErrorCodesFromDataSource("Oracle", null);
assertIsOracle(sec);
}
public void testHsqlRecognizedFromMetadata() throws Exception {
SQLErrorCodes sec = getErrorCodesFromDataSource("HSQL Database Engine", null);
assertIsHsql(sec);
}
public void testDB2RecognizedFromMetadata() throws Exception {
SQLErrorCodes sec = getErrorCodesFromDataSource("DB2", null);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("DB2/", null);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("DB-2", null);
assertIsEmpty(sec);
}
/**
* Check that wild card database name works.
*/
public void testWildCardNameRecognized() throws Exception {
class WildcardSQLErrorCodesFactory extends SQLErrorCodesFactory {
protected Resource loadResource(String path) {
if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) {
return new ClassPathResource("wildcard-error-codes.xml", SQLErrorCodesFactoryTests.class);
}
return null;
}
}
WildcardSQLErrorCodesFactory factory = new WildcardSQLErrorCodesFactory();
SQLErrorCodes sec = getErrorCodesFromDataSource("DB2", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("DB2 UDB for Xxxxx", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("DB3", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("DB3/", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("/DB3", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("/DB3", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("/DB3/", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("DB-3", factory);
assertIsEmpty(sec);
sec = getErrorCodesFromDataSource("DB1", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("DB1/", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("/DB1", factory);
assertIsEmpty(sec);
sec = getErrorCodesFromDataSource("/DB1/", factory);
assertIsEmpty(sec);
sec = getErrorCodesFromDataSource("DB0", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("/DB0", factory);
assertIsDB2(sec);
sec = getErrorCodesFromDataSource("DB0/", factory);
assertIsEmpty(sec);
sec = getErrorCodesFromDataSource("/DB0/", factory);
assertIsEmpty(sec);
}
}

View File

@@ -1,112 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.SQLException;
import junit.framework.TestCase;
import org.springframework.core.JdkVersion;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.PermissionDeniedDataAccessException;
import org.springframework.dao.RecoverableDataAccessException;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.jdbc.BadSqlGrammarException;
/**
* @author Thomas Risberg
*/
public class SQLExceptionSubclassTranslatorTests extends TestCase {
private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes();
static {
ERROR_CODES.setBadSqlGrammarCodes(new String[] { "1" });
}
public void testErrorCodeTranslation() {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_16) {
return;
}
SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 0);
DataIntegrityViolationException divex = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx);
assertEquals(dataIntegrityViolationEx, divex.getCause());
SQLException featureNotSupEx = SQLExceptionSubclassFactory.newSQLFeatureNotSupportedException("", "", 0);
InvalidDataAccessApiUsageException idaex = (InvalidDataAccessApiUsageException) sext.translate("task", "SQL", featureNotSupEx);
assertEquals(featureNotSupEx, idaex.getCause());
SQLException dataIntegrityViolationEx2 = SQLExceptionSubclassFactory.newSQLIntegrityConstraintViolationException("", "", 0);
DataIntegrityViolationException divex2 = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx2);
assertEquals(dataIntegrityViolationEx2, divex2.getCause());
SQLException permissionDeniedEx = SQLExceptionSubclassFactory.newSQLInvalidAuthorizationSpecException("", "", 0);
PermissionDeniedDataAccessException pdaex = (PermissionDeniedDataAccessException) sext.translate("task", "SQL", permissionDeniedEx);
assertEquals(permissionDeniedEx, pdaex.getCause());
SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLNonTransientConnectionException("", "", 0);
DataAccessResourceFailureException darex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataAccessResourceEx);
assertEquals(dataAccessResourceEx, darex.getCause());
SQLException badSqlEx2 = SQLExceptionSubclassFactory.newSQLSyntaxErrorException("", "", 0);
BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", badSqlEx2);
assertEquals("SQL2", bsgex2.getSql());
assertEquals(badSqlEx2, bsgex2.getSQLException());
SQLException tranRollbackEx = SQLExceptionSubclassFactory.newSQLTransactionRollbackException("", "", 0);
ConcurrencyFailureException cfex = (ConcurrencyFailureException) sext.translate("task", "SQL", tranRollbackEx);
assertEquals(tranRollbackEx, cfex.getCause());
SQLException transientConnEx = SQLExceptionSubclassFactory.newSQLTransientConnectionException("", "", 0);
TransientDataAccessResourceException tdarex = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx);
assertEquals(transientConnEx, tdarex.getCause());
SQLException transientConnEx2 = SQLExceptionSubclassFactory.newSQLTimeoutException("", "", 0);
TransientDataAccessResourceException tdarex2 = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx2);
assertEquals(transientConnEx2, tdarex2.getCause());
SQLException recoverableEx = SQLExceptionSubclassFactory.newSQLRecoverableException("", "", 0);
RecoverableDataAccessException rdaex2 = (RecoverableDataAccessException) sext.translate("task", "SQL", recoverableEx);
assertEquals(recoverableEx, rdaex2.getCause());
// Test classic error code translation. We should move there next if the exception we pass in is not one
// of the new sub-classes.
SQLException sexEct = new SQLException("", "", 1);
BadSqlGrammarException bsgEct = (BadSqlGrammarException) sext.translate("task", "SQL-ECT", sexEct);
assertEquals("SQL-ECT", bsgEct.getSql());
assertEquals(sexEct, bsgEct.getSQLException());
// Test fallback. We assume that no database will ever return this error code,
// but 07xxx will be bad grammar picked up by the fallback SQLState translator
SQLException sexFbt = new SQLException("", "07xxx", 666666666);
BadSqlGrammarException bsgFbt = (BadSqlGrammarException) sext.translate("task", "SQL-FBT", sexFbt);
assertEquals("SQL-FBT", bsgFbt.getSql());
assertEquals(sexFbt, bsgFbt.getSQLException());
// and 08xxx will be data resource failure (non-transient) picked up by the fallback SQLState translator
SQLException sexFbt2 = new SQLException("", "08xxx", 666666666);
DataAccessResourceFailureException darfFbt = (DataAccessResourceFailureException) sext.translate("task", "SQL-FBT2", sexFbt2);
assertEquals(sexFbt2, darfFbt.getCause());
}
}

View File

@@ -1,95 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.SQLException;
import junit.framework.TestCase;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.UncategorizedSQLException;
/**
*
* @author Rod Johnson
* @since 13-Jan-03
*/
public class SQLStateExceptionTranslatorTests extends TestCase {
private SQLStateSQLExceptionTranslator trans = new SQLStateSQLExceptionTranslator();
// ALSO CHECK CHAIN of SQLExceptions!?
// also allow chain of translators? default if can't do specific?
public void testBadSqlGrammar() {
String sql = "SELECT FOO FROM BAR";
SQLException sex = new SQLException("Message", "42001", 1);
try {
throw this.trans.translate("task", sql, sex);
}
catch (BadSqlGrammarException ex) {
// OK
assertTrue("SQL is correct", sql.equals(ex.getSql()));
assertTrue("Exception matches", sex.equals(ex.getSQLException()));
}
}
public void testInvalidSqlStateCode() {
String sql = "SELECT FOO FROM BAR";
SQLException sex = new SQLException("Message", "NO SUCH CODE", 1);
try {
throw this.trans.translate("task", sql, sex);
}
catch (UncategorizedSQLException ex) {
// OK
assertTrue("SQL is correct", sql.equals(ex.getSql()));
assertTrue("Exception matches", sex.equals(ex.getSQLException()));
}
}
/**
* PostgreSQL can return null
* SAP DB can apparently return empty SQL code
* Bug 729170
*/
public void testMalformedSqlStateCodes() {
String sql = "SELECT FOO FROM BAR";
SQLException sex = new SQLException("Message", null, 1);
testMalformedSqlStateCode(sex);
sex = new SQLException("Message", "", 1);
testMalformedSqlStateCode(sex);
// One char's not allowed
sex = new SQLException("Message", "I", 1);
testMalformedSqlStateCode(sex);
}
private void testMalformedSqlStateCode(SQLException sex) {
String sql = "SELECT FOO FROM BAR";
try {
throw this.trans.translate("task", sql, sex);
}
catch (UncategorizedSQLException ex) {
// OK
assertTrue("SQL is correct", sql.equals(ex.getSql()));
assertTrue("Exception matches", sex.equals(ex.getSQLException()));
}
}
}

View File

@@ -1,223 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support.rowset;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jdbc.InvalidResultSetAccessException;
/**
* @author Thomas Risberg
*/
public class ResultSetWrappingRowSetTests extends TestCase {
private MockControl rsetControl;
private ResultSet rset;
private ResultSetWrappingSqlRowSet rowset;
public void setUp() throws Exception {
rsetControl = MockControl.createControl(ResultSet.class);
rset = (ResultSet) rsetControl.getMock();
rset.getMetaData();
rsetControl.setReturnValue(null);
}
public void testGetBigDecimalInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), BigDecimal.valueOf(1));
}
public void testGetBigDecimalString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", new Class[] {String.class});
doTest(rset, rowset, "test", BigDecimal.valueOf(1));
}
public void testGetStringInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getString", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), "test");
}
public void testGetStringString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getString", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", new Class[] {String.class});
doTest(rset, rowset, "test", "test");
}
public void testGetTimestampInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Timestamp(1234l));
}
public void testGetTimestampString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", new Class[] {String.class});
doTest(rset, rowset, "test", new Timestamp(1234l));
}
public void testGetDateInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Date(1234l));
}
public void testGetDateString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDate", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", new Class[] {String.class});
doTest(rset, rowset, "test", new Date(1234l));
}
public void testGetTimeInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Time(1234l));
}
public void testGetTimeString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTime", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", new Class[] {String.class});
doTest(rset, rowset, "test", new Time(1234l));
}
public void testGetObjectInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Object());
}
public void testGetObjectString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getObject", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", new Class[] {String.class});
doTest(rset, rowset, "test", new Object());
}
public void testGetIntInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Integer(1));
}
public void testGetIntString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getInt", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", new Class[] {String.class});
doTest(rset, rowset, "test", new Integer(1));
}
public void testGetFloatInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Float(1));
}
public void testGetFloatString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getFloat", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", new Class[] {String.class});
doTest(rset, rowset, "test", new Float(1));
}
public void testGetDoubleInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Double(1));
}
public void testGetDoubleString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDouble", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", new Class[] {String.class});
doTest(rset, rowset, "test", new Double(1));
}
public void testGetLongInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Long(1));
}
public void testGetLongString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getLong", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", new Class[] {String.class});
doTest(rset, rowset, "test", new Long(1));
}
public void testGetBooleanInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Boolean(true));
}
public void testGetBooleanString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", new Class[] {String.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", new Class[] {String.class});
doTest(rset, rowset, "test", new Boolean(true));
}
private void doTest(Method rsetMethod, Method rowsetMethod, Object arg, Object ret) throws Exception {
rsetMethod.invoke(rset, new Object[] {arg});
if (ret instanceof Double) {
rsetControl.setReturnValue(((Double) ret).doubleValue());
}
else if (ret instanceof Float) {
rsetControl.setReturnValue(((Float) ret).floatValue());
}
else if (ret instanceof Integer) {
rsetControl.setReturnValue(((Integer) ret).intValue());
}
else if (ret instanceof Short) {
rsetControl.setReturnValue(((Short) ret).shortValue());
}
else if (ret instanceof Long) {
rsetControl.setReturnValue(((Long) ret).longValue());
}
else if (ret instanceof Boolean) {
rsetControl.setReturnValue(((Boolean) ret).booleanValue());
}
else if (ret instanceof Byte) {
rsetControl.setReturnValue(((Byte) ret).byteValue());
}
else {
rsetControl.setReturnValue(ret);
}
rsetMethod.invoke(rset, new Object[] {arg});
rsetControl.setThrowable(new SQLException("test"));
rsetControl.replay();
rowset = new ResultSetWrappingSqlRowSet(rset);
rowsetMethod.invoke(rowset, new Object[] {arg});
try {
rowsetMethod.invoke(rowset, new Object[] {arg});
fail("InvalidResultSetAccessException should have been thrown");
}
catch (InvocationTargetException ex) {
assertEquals(InvalidResultSetAccessException.class, ex.getTargetException().getClass());
}
}
}