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
|
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package vm.mlvm.share;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Constructor;
import java.util.List;
import com.sun.management.HotSpotDiagnosticMXBean;
import nsk.share.Consts;
import nsk.share.ArgumentParser;
import vm.share.options.IgnoreUnknownArgumentsHandler;
import vm.share.options.OptionSupport;
/**
* This class executes a test based on (a subclass of) either:
* <ul>
* <li>{@link vm.mlvm.share.MlvmTest}
* <li>{@link java.lang.Runnable}
* </ul>
* using a number of launch() methods.
*
* Command-line parameters are parsed and set to the instance fields of the test marked with {@literal@}Option/Options annotations. See {@link vm.share.options} framework for details.
*
* Arguments for test constructor can be passed as well.
*
* Additionally the launch() methods:
* <ul>
* <li>measures test run time
* <li> handles all test status passing methods (via boolean return value, via MlvmTest.markTestFailed() calls, exception thrown from overriden run() method)
* <li>optionally dumps heap after test execution if MlvmTest.setHeapDumpAfer(true) was called
* </ul>
*
* @see vm.mlvm.share.MlvmTest
* @see vm.share.options
*
*/
public class MlvmTestExecutor {
/**
* The heap dump file name. If you call MlvmTest.setHeapDumpAfter(true), the heap is dumped into file
* specified by this constant when test finishes
*/
public static final String HEAP_DUMP_FILENAME = "heap.dump";
/**
* Launches MLVM test.
* Please see documentation for {@link #launch(Class<?> testClass, Object[] constructorArgs)} method.
*
* This version of the method is a syntactic shugar to launch test in this way:
*
* <code>
* public class MyTest extends MlvmTest {
* ...
* public static void main(String[] args) {
* MlvmTestExecutor.launch(new YourCustomArgumentParser(args));
* }
* }
* </code>
*
* @param args Command-line arguments, which are taken from supplied ArgumentParser (ArgumentParser is needed for compatibility with old tests)
and set to appropriate test instance fields using vm.share.options framework
* @see #launch(Class<?> testClass, Object[] constructorArgs)
*/
public static void launch(ArgumentParser argumentParser) {
launch(argumentParser, null);
}
/**
* Launches MLVM test.
* Please see documentation for {@link #launch(Class<?> testClass, Object[] constructorArgs)} method.
*
* This version of the method is a syntactic shugar to launch test in this way:
*
* <code>
* public class MyTest extends MlvmTest {
* ...
* public static void main(String[] args) {
* MlvmTestExecutor.launch(new YourCustomArgumentParser(args), new Object[] { constructor-arguments... });
* }
* }
* </code>
*
* @param args Command-line arguments, which are taken from supplied ArgumentParser (ArgumentParser is needed for compatibility with old tests)
and set to appropriate test instance fields using vm.share.options framework
* @param constructorArgs Arguments, which are parsed to test constructor
* @see #launch(Class<?> testClass, Object[] constructorArgs)
*/
public static void launch(ArgumentParser argumentParser, Object[] constructorArgs) {
Env.init(argumentParser);
launch(constructorArgs);
}
/**
* Launches MLVM test.
* Please see documentation for {@link #launch(Class<?> testClass, Object[] constructorArgs)} method.
*
* This version of the method is a syntactic shugar to launch test in this way:
*
* <code>
* public class MyTest extends MlvmTest {
* ...
* public static void main(String[] args) {
* MlvmTestExecutor.launch(args);
* }
* }
* </code>
*
* @param args Command-line arguments, which are parsed using internal ArgumentParser (for compatibility with old tests) and also set to appropriate test instance fields using vm.share.options framework
* @see #launch(Class<?> testClass, Object[] constructorArgs)
*/
public static void launch(String[] args) {
launch(args, null);
}
/**
* Launches MLVM test.
* Please see documentation for {@link #launch(Class<?> testClass, Object[] constructorArgs)} method.
*
* This version of the method is a syntactic shugar to launch test in this way:
*
* <code>
* public class MyTest extends MlvmTest {
* ...
* public static void main(String[] args) {
* MlvmTestExecutor.launch(args, new Object[] { constructor-arguments... });
* }
* }
* </code>
*
* @param args Command-line arguments, which are parsed using internal ArgumentParser (for compatibility with old tests) and also set to appropriate test instance fields using vm.share.options framework
* @param constructorArgs Arguments, which are parsed to test constructor
* @see #launch(Class<?> testClass, Object[] constructorArgs)
*/
public static void launch(String[] args, Object[] constructorArgs) {
Env.init(args);
launch(constructorArgs);
}
/**
* Launches MLVM test.
* Please see documentation for {@link #launch(Class<?> testClass, Object[] constructorArgs)} method.
*
* This version of the method is a syntactic shugar to launch test in this way:
*
* <code>
* public class MyTest extends MlvmTest {
* ...
* void aMethod() {
* ...
* MlvmTestExecutor.launch(new Object[] { constructor-arguments... });
* }
* }
* </code>
*
* @param constructorArgs Arguments, which are parsed to test constructor
* @see #launch(Class<?> testClass, Object[] constructorArgs)
*/
public static void launch(Object[] constructorArgs) {
Class<?> testClass = getTestClassFromCallerStack();
if (testClass == null) {
throw new RuntimeException("TEST BUG: Can't find an instance of MlvmTest or Runnable in the stacktrace");
}
launch(testClass, constructorArgs);
}
private static Class<?> getTestClassFromCallerStack() {
try {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
// Elements of the stack trace: 0=Thread.getStackTrace(), 1rd=this method, 2nd=launch() method
// So we start searching from the most outer frame and finish searching at element 3
for (int i = stackTrace.length - 1; i >= 3; --i) {
StackTraceElement e = stackTrace[i];
Class<?> klass = Class.forName(e.getClassName());
if (MlvmTest.class.isAssignableFrom(klass)) {
return klass;
}
}
return null;
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to get Class object by its name either due to a different ClassLoader (a test bug) or JVM error", e);
}
}
/**
* Launches MLVM test. The method is the principal MLVM test launcher. This method in conjunction with {@link #runMlvmTest} method:
* <ol>
* <li>instantiates test class (optionally passing arguments to constructor)
* <li>parses command-line arguments using vm.share.options framework and updates the appropriate test fields
* <li>launches the tests
* <li>handles all test status passing methods (see below)
* <li>performs System.exit() with VM-testbase standard exit code 95 (success) or 97 (failure).
* </ol>
*
* <p>The following tests status passing mechanism are available to test writer:
* <ol>
* <li>Return a boolean value (true if test passed, false otherwise. Good for simple tests)
* <li>Assume that test has failed by calling {@link MlvmTest#markTestFailed()} method (suitable for complex logic and multithreaded tests)
* <li>by throwing exception from test {@link MlvmTest#run()} method
* </ol>
* <p>Additionally the launcher:
* <ul>
* <li>measures test run time and logs it
* <li>optionally dumps heap after test execution if {@link MlvmTest#setHeapDumpAfer(true)} was called
* <li>enables verbose logging on error
* </ul>
*
* @param testClass a class to instantiate. Has to be subclass of vm.mlvm.share.MlvmTest or java.lang.Runnable
* @param constructorArgs Arguments to pass to test constructor. Can be null.
* @see #runMlvmTest(Class<?> testClass, Object[] constructorArgs)
*/
public static void launch(Class<?> testClass, Object[] constructorArgs) {
long startTime = System.currentTimeMillis();
boolean passed;
try {
Env.traceDebug(MlvmTest.getName() + " class: " + testClass);
passed = runMlvmTest(testClass, constructorArgs);
} catch (Throwable e) {
Env.complain(e, MlvmTest.getName() + " caught an exception: ");
passed = false;
}
long finishTime = System.currentTimeMillis();
Env.traceNormal("The test took " + (finishTime - startTime) + " ms");
optionallyDumpHeap();
final String testNameUC = MlvmTest.getName().toUpperCase();
if (passed) {
Env.display(testNameUC + " PASSED");
System.exit(Consts.JCK_STATUS_BASE + Consts.TEST_PASSED);
} else {
Env.display(testNameUC + " FAILED");
System.exit(Consts.JCK_STATUS_BASE + Consts.TEST_FAILED);
}
}
private static void dumpHeapWithHotspotDiagnosticMXBean(String fileName) throws IOException {
System.err.println("Dumping heap to " + fileName);
File f = new File(fileName);
if (f.exists())
f.delete();
HotSpotDiagnosticMXBean b = ManagementFactory.getPlatformMXBeans(
com.sun.management.HotSpotDiagnosticMXBean.class).get(0);
b.dumpHeap(fileName, false);
}
private static void optionallyDumpHeap() {
try {
if (MlvmTest.getHeapDumpAfter()) {
dumpHeapWithHotspotDiagnosticMXBean(HEAP_DUMP_FILENAME);
}
} catch (Exception e) {
Env.traceNormal(e, "Error dumping heap: ");
}
}
/**
* Launches MLVM test (syntatic shugar method).
* Calls {@link #runMlvmTest(Class<?> testClass, Object[] constructorArgs)} method providing no arguments to pass to the test constructor.
*
* The method throws unchecked exception when there is an error in test logic or handling.
* Exceptions thrown from MlvmTest.run() method or test constructor are wrapped into java.lang.RuntimeException or java.lang.Error
*
* @param testClass a class to instantiate. Has to be subclass of vm.mlvm.share.MlvmTest or java.lang.Runnable
* @return true if test passed, false otherwise
* @see #runMlvmTest(Class<?> testClass, Object[] constructorArgs)
*/
public static boolean runMlvmTest(Class<?> testClass) {
return runMlvmTest(testClass, null);
}
/**
* Launches MLVM test. In details, it:
* <ol>
* <li>instantiates test class (optionally passing arguments to constructor)
* <li>parses command-line arguments using vm.share.options framework and updates the appropriate test fields
* <li>launches the tests
* <li>handles all test status passing methods (see below)
* </ol>
*
* <p>Unlike {@link #launch()} methods, it does NOT:
* <ul>
* <li>performs System.exit() with VM-testbase standard exit code 95 (success) or 97 (failure).
* <li>measures test run time and logs it
* <li>optionally dumps heap after test execution if {@link MlvmTest#setHeapDumpAfer(true)} was called
* <li>enables verbose logging on error
* </ul>
* Please see {@link #launch(Class<?> testClass, Object[] constructorArgs)} for additional details.
*
* The method throws unchecked exception when there is an error in test logic or handling.
* Exceptions thrown from MlvmTest.run() method or test constructor are wrapped into java.lang.RuntimeException or java.lang.Error
*
* @param testClass a class to instantiate. Has to be subclass of vm.mlvm.share.MlvmTest or java.lang.Runnable
* @param constructorArgs Arguments to pass to test constructor. Can be null.
* @return true if test passed, false otherwise
* @see #launch(Class<?> testClass, Object[] constructorArgs)
*/
public static boolean runMlvmTest(Class<?> testClass, Object[] constructorArgs) {
boolean passed;
Throwable exception = null;
try {
MlvmTest instance = constructMlvmTest(testClass, constructorArgs);
setupMlvmTest(instance);
instance.initializeTest();
try {
passed = runMlvmTestInstance(instance);
} catch(Throwable e) {
exception = e;
passed = false;
}
try {
instance.finalizeTest(passed);
} catch (Throwable e) {
Env.complain(e, "TEST BUG: exception thrown in finalizeTest");
if (exception == null) {
exception = e;
}
passed = false;
}
} catch (Throwable e) {
Env.complain(e, "TEST BUG: exception thrown when instantiating/preparing test for run");
exception = e;
passed = false; // never really needed, but let's keep it
}
if (exception != null) {
Env.throwAsUncheckedException(exception); // always throws
}
return passed;
}
private static void setupMlvmTest(MlvmTest instance) {
MlvmTest.setInstance(instance);
OptionSupport.setup(instance, Env.getArgParser().getRawArguments(), new IgnoreUnknownArgumentsHandler());
}
private static boolean runMlvmTestInstance(MlvmTest instance) throws Throwable {
List<Class<? extends Throwable>> expectedExceptions = instance.getRequiredExceptions();
int runsCount = instance.getRunsNumber() * instance.getStressOptions().getRunsFactor();
if (runsCount < 1) {
throw new RuntimeException("Runs number obtained via command-line options is less than 1");
}
int failedRuns = 0;
try {
for (int run = 1; run <= runsCount; ++run) {
if (runsCount > 1) {
Env.traceNormal("TEST RUN " + run + "/" + runsCount + "; Failed " + failedRuns + " runs");
}
if (run > 1) {
instance.resetTest();
}
boolean instancePassed;
if (expectedExceptions.size() == 0) {
instancePassed = instance.run();
} else {
try {
instance.run();
Env.complain("Expected exceptions: " + expectedExceptions + ", but caught none");
instancePassed = false;
} catch (Throwable e) {
if (checkExpectedException(expectedExceptions, e)) {
instancePassed = true;
} else {
Env.complain(e, "Expected exceptions: " + expectedExceptions + ", but caught: ");
instancePassed = false;
}
}
}
if (instance.isMarkedFailed()) {
instancePassed = false;
}
if (!instancePassed) {
++failedRuns;
}
}
} finally {
if (failedRuns > 0) {
Env.complain("Failed runs: " + failedRuns + " of " + runsCount);
}
}
return failedRuns == 0;
}
private static Object constructTest(Class<?> testClass, Object[] constructorArgs) throws Throwable {
if (constructorArgs == null || constructorArgs.length == 0) {
return testClass.newInstance();
}
for (Constructor<?> c : testClass.getConstructors()) {
Class<?> paramClasses[] = c.getParameterTypes();
if (!parametersAreAssignableFrom(paramClasses, constructorArgs)) {
continue;
}
return c.newInstance(constructorArgs);
}
throw new RuntimeException("Test bug: in class " + testClass.getName() + " no appropriate constructor found for arguments " + constructorArgs);
}
private static MlvmTest constructMlvmTest(Class<?> testClass, Object[] constructorArgs) throws Throwable {
Object testObj = constructTest(testClass, constructorArgs);
MlvmTest instance;
if (testObj instanceof MlvmTest) {
instance = (MlvmTest) testObj;
} else if (testObj instanceof Runnable) {
instance = new RunnableWrapper((Runnable) testObj);
} else {
// You can add wrapping of other types of tests here into MlvmTest if you need
throw new RuntimeException("TEST BUG: Test class should be subclass of MlvmTest or Runnable. Its type is "
+ testObj.getClass().getName());
}
return instance;
}
private static boolean parametersAreAssignableFrom(Class<?>[] paramClasses, Object[] constructorArgs) {
if (paramClasses.length != constructorArgs.length) {
return false;
}
for (int i = 0; i < paramClasses.length; ++i) {
if (!paramClasses[i].isAssignableFrom(constructorArgs[i].getClass())) {
return false;
}
}
return true;
}
private static boolean checkExpectedException(List<Class<? extends Throwable>> expectedExceptions, Throwable caught) throws Throwable {
for (Class<? extends Throwable> expected : expectedExceptions) {
if (expected.isAssignableFrom(caught.getClass())) {
Env.traceNormal("Caught anticipated exception " + caught.getClass().getName() + ". Cause: " + caught.getCause());
return true;
}
}
return false;
}
private static class RunnableWrapper extends MlvmTest {
private Runnable runnable;
public RunnableWrapper(Runnable r) {
runnable = r;
}
@Override
public boolean run() throws Throwable {
runnable.run();
return true;
}
}
}
|