File size: 21,551 Bytes
2795186 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 |
/*
Copyright 2002-2007 MySQL AB, 2008 Sun Microsystems
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
There are special exceptions to the terms and conditions of the GPL
as it is applied to this software. View the full text of the
exception in file EXCEPTIONS-CONNECTOR-J in the directory of this
software distribution.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package testsuite;
import java.lang.reflect.Method;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import junit.framework.TestCase;
import com.mysql.jdbc.NonRegisteringDriver;
import com.mysql.jdbc.StringUtils;
/**
* Base class for all test cases. Creates connections, statements, etc. and
* closes them.
*
* @author Mark Matthews
* @version $Id: BaseTestCase.java 5440 2006-06-27 17:00:53 +0000 (Tue, 27 Jun
* 2006) mmatthews $
*/
public abstract class BaseTestCase extends TestCase {
private final static String ADMIN_CONNECTION_PROPERTY_NAME = "com.mysql.jdbc.testsuite.admin-url";
private final static String NO_MULTI_HOST_PROPERTY_NAME = "com.mysql.jdbc.testsuite.no-multi-hosts-tests";
/**
* JDBC URL, initialized from com.mysql.jdbc.testsuite.url system property,
* or defaults to jdbc:mysql:///test
*/
protected static String dbUrl = "jdbc:mysql:///test";
/** Instance counter */
private static int instanceCount = 1;
/** Connection to server, initialized in setUp() Cleaned up in tearDown(). */
protected Connection conn = null;
/** list of schema objects to be dropped in tearDown */
private List createdObjects;
/** The driver to use */
protected String dbClass = "com.mysql.jdbc.Driver";
/** My instance number */
private int myInstanceNumber = 0;
/**
* PreparedStatement to be used in tests, not initialized. Cleaned up in
* tearDown().
*/
protected PreparedStatement pstmt = null;
/**
* ResultSet to be used in tests, not initialized. Cleaned up in tearDown().
*/
protected ResultSet rs = null;
/**
* Statement to be used in tests, initialized in setUp(). Cleaned up in
* tearDown().
*/
protected Statement stmt = null;
private boolean runningOnJdk131 = false;
/**
* Creates a new BaseTestCase object.
*
* @param name
* The name of the JUnit test case
*/
public BaseTestCase(String name) {
super(name);
this.myInstanceNumber = instanceCount++;
String newDbUrl = System.getProperty("com.mysql.jdbc.testsuite.url");
if ((newDbUrl != null) && (newDbUrl.trim().length() != 0)) {
dbUrl = newDbUrl;
} else {
String defaultDbUrl = System
.getProperty("com.mysql.jdbc.testsuite.url.default");
if ((defaultDbUrl != null) && (defaultDbUrl.trim().length() != 0)) {
dbUrl = defaultDbUrl;
}
}
String newDriver = System
.getProperty("com.mysql.jdbc.testsuite.driver");
if ((newDriver != null) && (newDriver.trim().length() != 0)) {
this.dbClass = newDriver;
}
try {
Blob.class.getMethod("truncate", new Class[] { Long.TYPE });
this.runningOnJdk131 = false;
} catch (NoSuchMethodException nsme) {
this.runningOnJdk131 = true;
}
}
protected void createSchemaObject(String objectType, String objectName,
String columnsAndOtherStuff) throws SQLException {
this.createdObjects.add(new String[] {objectType, objectName});
dropSchemaObject(objectType, objectName);
StringBuffer createSql = new StringBuffer(objectName.length()
+ objectType.length() + columnsAndOtherStuff.length() + 10);
createSql.append("CREATE ");
createSql.append(objectType);
createSql.append(" ");
createSql.append(objectName);
createSql.append(" ");
createSql.append(columnsAndOtherStuff);
try {
this.stmt.executeUpdate(createSql.toString());
} catch (SQLException sqlEx) {
if ("42S01".equals(sqlEx.getSQLState())) {
System.err.println("WARN: Stale mysqld table cache preventing table creation - flushing tables and trying again");
this.stmt.executeUpdate("FLUSH TABLES"); // some bug in 5.1 on the mac causes tables to not disappear from the cache
this.stmt.executeUpdate(createSql.toString());
} else {
throw sqlEx;
}
}
}
protected void createFunction(String functionName, String functionDefn)
throws SQLException {
createSchemaObject("FUNCTION", functionName, functionDefn);
}
protected void dropFunction(String functionName) throws SQLException {
dropSchemaObject("FUNCTION", functionName);
}
protected void createProcedure(String procedureName, String procedureDefn)
throws SQLException {
createSchemaObject("PROCEDURE", procedureName, procedureDefn);
}
protected void dropProcedure(String procedureName) throws SQLException {
dropSchemaObject("PROCEDURE", procedureName);
}
protected void createTable(String tableName, String columnsAndOtherStuff)
throws SQLException {
createSchemaObject("TABLE", tableName, columnsAndOtherStuff);
}
protected void createTable(String tableName, String columnsAndOtherStuff,
String engine) throws SQLException {
createSchemaObject("TABLE", tableName,
columnsAndOtherStuff + " " + getTableTypeDecl() + " = " + engine);
}
protected void dropTable(String tableName) throws SQLException {
dropSchemaObject("TABLE", tableName);
}
protected void dropSchemaObject(String objectType, String objectName)
throws SQLException {
this.stmt.executeUpdate("DROP " + objectType + " IF EXISTS "
+ objectName);
}
protected Connection getAdminConnection() throws SQLException {
return getAdminConnectionWithProps(new Properties());
}
protected Connection getAdminConnectionWithProps(Properties props)
throws SQLException {
String adminUrl = System.getProperty(ADMIN_CONNECTION_PROPERTY_NAME);
if (adminUrl != null) {
return DriverManager.getConnection(adminUrl, props);
} else {
return null;
}
}
protected Connection getConnectionWithProps(String propsList) throws SQLException {
return getConnectionWithProps(dbUrl, propsList);
}
protected Connection getConnectionWithProps(String url, String propsList) throws SQLException {
Properties props = new Properties();
if (propsList != null) {
List keyValuePairs = StringUtils.split(propsList, ",", false);
Iterator iter = keyValuePairs.iterator();
while (iter.hasNext()) {
String kvp = (String)iter.next();
List splitUp = StringUtils.split(kvp, "=", false);
StringBuffer value = new StringBuffer();
for (int i = 1; i < splitUp.size(); i++) {
if (i != 1) {
value.append("=");
}
value.append(splitUp.get(i));
}
props.setProperty(splitUp.get(0).toString().trim(), value.toString());
}
}
return getConnectionWithProps(url, props);
}
/**
* Returns a new connection with the given properties
*
* @param props
* the properties to use (the URL will come from the standard for
* this testcase).
*
* @return a new connection using the given properties.
*
* @throws SQLException
* DOCUMENT ME!
*/
protected Connection getConnectionWithProps(Properties props)
throws SQLException {
return DriverManager.getConnection(dbUrl, props);
}
protected Connection getConnectionWithProps(String url, Properties props)
throws SQLException {
return DriverManager.getConnection(url, props);
}
/**
* Returns the per-instance counter (for messages when multi-threading
* stress tests)
*
* @return int the instance number
*/
protected int getInstanceNumber() {
return this.myInstanceNumber;
}
protected String getMysqlVariable(Connection c, String variableName)
throws SQLException {
Object value = getSingleIndexedValueWithQuery(c, 2,
"SHOW VARIABLES LIKE '" + variableName + "'");
if (value != null) {
if (value instanceof byte[]) {
// workaround for bad 4.1.x bugfix
return new String((byte[]) value);
}
return value.toString();
}
return null;
}
/**
* Returns the named MySQL variable from the currently connected server.
*
* @param variableName
* the name of the variable to return
*
* @return the value of the given variable, or NULL if it doesn't exist
*
* @throws SQLException
* if an error occurs
*/
protected String getMysqlVariable(String variableName) throws SQLException {
return getMysqlVariable(this.conn, variableName);
}
/**
* Returns the properties that represent the default URL used for
* connections for all testcases.
*
* @return properties parsed from com.mysql.jdbc.testsuite.url
*
* @throws SQLException
* if parsing fails
*/
protected Properties getPropertiesFromTestsuiteUrl() throws SQLException {
Properties props = new NonRegisteringDriver().parseURL(dbUrl, null);
String hostname = props
.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
if (hostname == null) {
props.setProperty(NonRegisteringDriver.HOST_PROPERTY_KEY,
"localhost");
} else if (hostname.startsWith(":")) {
props.setProperty(NonRegisteringDriver.HOST_PROPERTY_KEY,
"localhost");
props.setProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, hostname
.substring(1));
}
String portNumber = props
.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);
if (portNumber == null) {
props.setProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, "3306");
}
return props;
}
protected int getRowCount(String tableName) throws SQLException {
ResultSet countRs = null;
try {
countRs = this.stmt.executeQuery("SELECT COUNT(*) FROM "
+ tableName);
countRs.next();
return countRs.getInt(1);
} finally {
if (countRs != null) {
countRs.close();
}
}
}
protected Object getSingleIndexedValueWithQuery(Connection c,
int columnIndex, String query) throws SQLException {
ResultSet valueRs = null;
Statement svStmt = null;
try {
svStmt = c.createStatement();
valueRs = svStmt.executeQuery(query);
if (!valueRs.next()) {
return null;
}
return valueRs.getObject(columnIndex);
} finally {
if (valueRs != null) {
valueRs.close();
}
if (svStmt != null) {
svStmt.close();
}
}
}
protected Object getSingleIndexedValueWithQuery(int columnIndex,
String query) throws SQLException {
return getSingleIndexedValueWithQuery(this.conn, columnIndex, query);
}
protected Object getSingleValue(String tableName, String columnName,
String whereClause) throws SQLException {
return getSingleValueWithQuery("SELECT " + columnName + " FROM "
+ tableName + ((whereClause == null) ? "" : " " + whereClause));
}
protected Object getSingleValueWithQuery(String query) throws SQLException {
return getSingleIndexedValueWithQuery(1, query);
}
protected String getTableTypeDecl() throws SQLException {
if (versionMeetsMinimum(5, 0)) {
return "ENGINE";
}
return "TYPE";
}
protected boolean isAdminConnectionConfigured() {
return System.getProperty(ADMIN_CONNECTION_PROPERTY_NAME) != null;
}
protected boolean isServerRunningOnWindows() throws SQLException {
return (getMysqlVariable("datadir").indexOf('\\') != -1);
}
public void logDebug(String message) {
if (System.getProperty("com.mysql.jdbc.testsuite.noDebugOutput") == null) {
System.err.println(message);
}
}
protected File newTempBinaryFile(String name, long size) throws IOException {
File tempFile = File.createTempFile(name, "tmp");
tempFile.deleteOnExit();
cleanupTempFiles(tempFile, name);
FileOutputStream fos = new FileOutputStream(tempFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for (long i = 0; i < size; i++) {
bos.write((byte) i);
}
bos.close();
assertTrue(tempFile.exists());
assertEquals(size, tempFile.length());
return tempFile;
}
protected final boolean runLongTests() {
return runTestIfSysPropDefined("com.mysql.jdbc.testsuite.runLongTests");
}
/**
* Checks whether a certain system property is defined, in order to
* run/not-run certain tests
*
* @param propName
* the property name to check for
*
* @return true if the property is defined.
*/
protected boolean runTestIfSysPropDefined(String propName) {
String prop = System.getProperty(propName);
return (prop != null) && (prop.length() > 0);
}
protected boolean runMultiHostTests() {
return !runTestIfSysPropDefined(NO_MULTI_HOST_PROPERTY_NAME);
}
/**
* Creates resources used by all tests.
*
* @throws Exception
* if an error occurs.
*/
public void setUp() throws Exception {
System.out.println("Loading JDBC driver '" + this.dbClass + "'");
Class.forName(this.dbClass).newInstance();
System.out.println("Done.\n");
this.createdObjects = new ArrayList();
if (this.dbClass.equals("gwe.sql.gweMysqlDriver")) {
try {
this.conn = DriverManager.getConnection(dbUrl, "", "");
} catch (Exception ex) {
ex.printStackTrace();
fail();
}
} else {
try {
this.conn = DriverManager.getConnection(dbUrl);
} catch (Exception ex) {
ex.printStackTrace();
fail();
}
}
System.out.println("Done.\n");
this.stmt = this.conn.createStatement();
try {
if (dbUrl.indexOf("mysql") != -1) {
this.rs = this.stmt.executeQuery("SELECT VERSION()");
this.rs.next();
logDebug("Connected to " + this.rs.getString(1));
this.rs.close();
this.rs = null;
} else {
logDebug("Connected to "
+ this.conn.getMetaData().getDatabaseProductName()
+ " / "
+ this.conn.getMetaData().getDatabaseProductVersion());
}
} finally {
if (this.rs != null) {
this.rs.close();
}
}
}
/**
* Destroys resources created during the test case.
*
* @throws Exception
* DOCUMENT ME!
*/
public void tearDown() throws Exception {
if (this.rs != null) {
try {
this.rs.close();
} catch (SQLException SQLE) {
;
}
}
for (int i = 0; i < this.createdObjects.size(); i++) {
try {
String[] objectInfo = (String[])this.createdObjects.get(i);
dropSchemaObject(objectInfo[0], objectInfo[1]);
} catch (SQLException SQLE) {
;
}
}
if (this.stmt != null) {
try {
this.stmt.close();
} catch (SQLException SQLE) {
;
}
}
if (this.pstmt != null) {
try {
this.pstmt.close();
} catch (SQLException SQLE) {
;
}
}
if (this.conn != null) {
try {
this.conn.close();
} catch (SQLException SQLE) {
;
}
}
}
/**
* Checks whether the database we're connected to meets the given version
* minimum
*
* @param major
* the major version to meet
* @param minor
* the minor version to meet
*
* @return boolean if the major/minor is met
*
* @throws SQLException
* if an error occurs.
*/
protected boolean versionMeetsMinimum(int major, int minor)
throws SQLException {
return versionMeetsMinimum(major, minor, 0);
}
/**
* Checks whether the database we're connected to meets the given version
* minimum
*
* @param major
* the major version to meet
* @param minor
* the minor version to meet
*
* @return boolean if the major/minor is met
*
* @throws SQLException
* if an error occurs.
*/
protected boolean versionMeetsMinimum(int major, int minor, int subminor)
throws SQLException {
return (((com.mysql.jdbc.Connection) this.conn).versionMeetsMinimum(
major, minor, subminor));
}
protected boolean isRunningOnJdk131() {
return this.runningOnJdk131;
}
protected boolean isClassAvailable(String classname) {
try {
Class.forName(classname);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
protected void closeMemberJDBCResources() {
if (this.rs != null) {
ResultSet toClose = this.rs;
this.rs = null;
try {
toClose.close();
} catch (SQLException sqlEx) {
// ignore
}
}
if (this.pstmt != null) {
PreparedStatement toClose = this.pstmt;
this.pstmt = null;
try {
toClose.close();
} catch (SQLException sqlEx) {
// ignore
}
}
}
protected boolean isRunningOnJRockit() {
String vmVendor = System.getProperty("java.vm.vendor");
return (vmVendor != null && vmVendor.toUpperCase(Locale.US).startsWith(
"BEA"));
}
protected String randomString() {
int length = (int)(Math.random() * 32);
StringBuffer buf = new StringBuffer(length);
for (int i = 0; i < length; i++) {
buf.append((char)((Math.random() * 26) + 'a'));
}
return buf.toString();
}
protected void cleanupTempFiles(final File exampleTempFile, final String tempfilePrefix) {
File tempfilePath = exampleTempFile.getParentFile();
File[] possibleFiles = tempfilePath.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.indexOf(tempfilePrefix) != -1
&& !exampleTempFile.getName().equals(name));
}});
for (int i = 0; i < possibleFiles.length; i++) {
try {
possibleFiles[i].delete();
} catch (Throwable t) {
// ignore, we're only making a best effort cleanup attempt here
}
}
}
protected void assertResultSetLength(ResultSet rs, int len) throws Exception {
assertTrue("Result set is scrollable", rs.getType() != ResultSet.TYPE_FORWARD_ONLY);
int oldRowPos = rs.getRow();
rs.last();
assertEquals("Result set length", len, rs.getRow());
if (oldRowPos > 0)
rs.absolute(oldRowPos);
else
rs.beforeFirst();
}
protected void assertResultSetsEqual(ResultSet control, ResultSet test)
throws Exception {
int controlNumCols = control.getMetaData().getColumnCount();
int testNumCols = test.getMetaData().getColumnCount();
assertEquals(controlNumCols, testNumCols);
StringBuffer rsAsString = new StringBuffer();
while (control.next()) {
test.next();
rsAsString.append("\n");
for (int i = 0; i < controlNumCols; i++) {
Object controlObj = control.getObject(i + 1);
Object testObj = test.getObject(i + 1);
rsAsString.append("" + controlObj);
rsAsString.append("\t = \t");
rsAsString.append("" + testObj);
rsAsString.append(", ");
if (controlObj == null) {
assertNull("Expected null, see last row: \n" + rsAsString.toString(), testObj);
} else {
assertNotNull("Expected non-null, see last row: \n" + rsAsString.toString(), testObj);
}
if (controlObj instanceof Float) {
assertEquals("Float comparison failed, see last row: \n" + rsAsString.toString(), ((Float)controlObj).floatValue(),
((Float)testObj).floatValue(), 0.1);
} else if (controlObj instanceof Double) {
assertEquals("Double comparison failed, see last row: \n" + rsAsString.toString(), ((Double)controlObj).doubleValue(),
((Double)testObj).doubleValue(), 0.1);
} else {
assertEquals("Value comparison failed, see last row: \n" + rsAsString.toString(), controlObj, testObj);
}
}
}
int howMuchMore = 0;
while (test.next()) {
rsAsString.append("\n");
howMuchMore++;
for (int i = 0; i < controlNumCols; i++) {
rsAsString.append("\t = \t");
rsAsString.append("" + test.getObject(i + 1));
rsAsString.append(", ");
}
}
assertTrue("Found " + howMuchMore + " extra rows in result set to be compared: ", howMuchMore == 0);
}
/*
* Set default values for primitives.
* (prevents NPE in Java 1.4 when calling via reflection)
*/
protected void fillPrimitiveDefaults(Class types[], Object vals[], int count) {
for (int i = 0; i < count; ++i) {
if (vals[i] != null)
continue;
String type = types[i].toString();
if (type.equals("short")) {
vals[i] = new Short((short)0);
} else if (type.equals("int")) {
vals[i] = new Integer(0);
} else if (type.equals("long")) {
vals[i] = new Long(0);
} else if (type.equals("boolean")) {
vals[i] = new Boolean(false);
} else if (type.equals("byte")) {
vals[i] = new Byte((byte)0);
} else if (type.equals("double")) {
vals[i] = new Double(0.0);
} else if (type.equals("float")) {
vals[i] = new Float(0.0);
}
}
}
/**
* Retrieve the current system time in milliseconds, using the nanosecond
* time if possible.
*/
protected long currentTimeMillis() {
try {
Method mNanoTime = System.class.getDeclaredMethod("nanoTime", null);
return ((Long)mNanoTime.invoke(null, null)).longValue() / 1000000;
} catch(Exception ex) {
return System.currentTimeMillis();
}
}
}
|