jdk.test.lib.Utils Java Examples

The following examples show how to use jdk.test.lib.Utils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestCompilerPhase.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Recording recording = new Recording();
    recording.enable(EVENT_NAME);
    recording.start();

    // Provoke compilation
    Method mtd = TestCompilerPhase.class.getDeclaredMethod(METHOD_NAME, new Class[0]);
    WhiteBox WB = WhiteBox.getWhiteBox();
    if (!WB.enqueueMethodForCompilation(mtd, COMP_LEVEL_FULL_OPTIMIZATION)) {
        WB.enqueueMethodForCompilation(mtd, COMP_LEVEL_SIMPLE);
    }
    Utils.waitForCondition(() -> WB.isMethodCompiled(mtd));
    dummyMethod();

    recording.stop();

    List<RecordedEvent> events = Events.fromRecording(recording);
    Events.hasEvents(events);
    for (RecordedEvent event : events) {
        System.out.println("Event:" + event);
        Events.assertField(event, "phase").notEmpty();
        Events.assertField(event, "compileId").atLeast(0);
        Events.assertField(event, "phaseLevel").atLeast((short)0).atMost((short)4);
        Events.assertEventThread(event);
    }
}
 
Example #2
Source File: RandomGeneratorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Verifies that the original output meets expectations
 * depending on the test mode. It compares the output of second execution
 * to original one.
 * @param orig original output
 * @param cmdLine command line arguments
 * @throws Throwable - Throws an exception in case test failure.
 */
public void verify(String orig, String[] cmdLine) {
    String output;
    OutputAnalyzer oa;
    try {
        oa = ProcessTools.executeTestJvm(cmdLine);
    } catch (Throwable t) {
        throw new Error("TESTBUG: Unexpedted exception during jvm execution.", t);
    }
    oa.shouldHaveExitValue(0);
    try {
        output = Utils.fileAsString(name()).trim();
    } catch (IOException ioe) {
        throw new Error("TESTBUG: Problem during IO operation with file: " + name(), ioe);
    }
    if (!isOutputExpected(orig, output)) {
        System.err.println("Initial output: " + orig);
        System.err.println("Second run output: " + output);
        throw new AssertionError("Unexpected random number sequence for mode: " + this.name());
    }
}
 
Example #3
Source File: TestVerifySilently.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static OutputAnalyzer runTest(boolean verifySilently) throws Exception {
  ArrayList<String> vmOpts = new ArrayList();

  Collections.addAll(vmOpts, Utils.getFilteredTestJavaOpts("-Xlog.*"));
  Collections.addAll(vmOpts, new String[] {"-XX:+UnlockDiagnosticVMOptions",
                                           "-XX:+VerifyDuringStartup",
                                           "-XX:+VerifyBeforeGC",
                                           "-XX:+VerifyAfterGC",
                                           (verifySilently ? "-Xlog:gc":"-Xlog:gc+verify=debug"),
                                           RunSystemGC.class.getName()});
  ProcessBuilder pb =
    ProcessTools.createJavaProcessBuilder(vmOpts.toArray(new String[vmOpts.size()]));
  OutputAnalyzer output = new OutputAnalyzer(pb.start());

  System.out.println("Output:\n" + output.getOutput());
  return output;
}
 
Example #4
Source File: GetClassInitializerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void runTest(TestCase tcase) {
    System.out.println(tcase);
    String className = tcase.holder.getName();
    HotSpotResolvedObjectType resolvedClazz = CompilerToVMHelper
            .lookupType(Utils.toJVMTypeSignature(tcase.holder),
                    getClass(), /* resolve = */ true);
    HotSpotResolvedJavaMethod initializer = CompilerToVMHelper
            .getClassInitializer(resolvedClazz);
    if (tcase.isPositive) {
        Asserts.assertNotNull(initializer, "Couldn't get initializer for "
                + className);
        Asserts.assertEQ(initializer.getName(), "<clinit>",
                "Unexpected initializer name for " + className);
    } else {
        Asserts.assertNull(initializer, "Unexpected: found initializer for "
                + className);
    }
}
 
Example #5
Source File: TestNewSizeFlags.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    LinkedList<String> options = new LinkedList<>(
            Arrays.asList(Utils.getFilteredTestJavaOpts("(-Xm[nsx][^ ]+)|"
                            + "(-XX:(Max)?((New)|"
                            + "(Heap))((Size)|"
                            + "(Ratio))=[^ ]+)"))
    );

    // Test NewSize and MaxNewSize
    testNewSizeFlags(20 * M, 10 * M, 30 * M, 40 * M, options, false);
    testNewSizeFlags(10 * M, 20 * M, 30 * M, 80 * M, options, false);
    testNewSizeFlags(-1, 20 * M, 30 * M, 40 * M, options, false);
    testNewSizeFlags(10 * M, -1, 30 * M, 40 * M, options, false);
    testNewSizeFlags(20 * M, 20 * M, 30 * M, 40 * M, options, false);
    testNewSizeFlags(20 * M, 30 * M, 40 * M, 50 * M, options, false);
    testNewSizeFlags(30 * M, 100 * M, 150 * M, 200 * M, options, false);
    testNewSizeFlags(20 * M, 30 * M, 128 * M, 128 * M, options, false);

    // Test -Xmn
    testXmnFlags(0, 30 * M, 40 * M, options, true);
    testXmnFlags(20 * M, 30 * M, 40 * M, options, false);
    testXmnFlags(50 * M, 70 * M, 100 * M, options, false);
}
 
Example #6
Source File: PolynomialRoot.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String [] args)
 {
   if (System.getProperty("os.arch").equals("x86") ||
      System.getProperty("os.arch").equals("amd64") ||
      System.getProperty("os.arch").equals("x86_64")){
     final long t0=System.currentTimeMillis();
     final double eps=1e-6;
     //checkRoots();
     final Random r = Utils.getRandomInstance();
     printSpecialValues();

     final int n_tests=100000;
     //testRoots(2,n_tests,r,eps);
     //testRoots(3,n_tests,r,eps);
     testRoots(4,n_tests,r,eps);
     final long t1=System.currentTimeMillis();
     System.err.println("PolynomialRoot.main: "+n_tests+" tests OK done in "+(t1-t0)+" milliseconds. ver=$Id: PolynomialRoot.java,v 1.105 2012/08/18 00:00:05 mal Exp $");
     System.out.println("PASSED");
  } else {
    System.out.println("PASS test for non-x86");
  }
}
 
Example #7
Source File: AllocateCompileIdTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void runSanityCorrectTest(CompileCodeTestCase testCase) {
    System.out.println(testCase);
    Executable aMethod = testCase.executable;
    // to generate ciTypeFlow
    testCase.invoke(Utils.getNullValues(aMethod.getParameterTypes()));
    int bci = testCase.bci;
    HotSpotResolvedJavaMethod method = CTVMUtilities
            .getResolvedMethod(aMethod);
    for (int i = 0; i < SOME_REPEAT_VALUE; ++i) {
        int wbCompileID = getWBCompileID(testCase);
        int id = CompilerToVMHelper.allocateCompileId(method, bci);
        Asserts.assertNE(id, 0, testCase + " : zero compile id");
        Asserts.assertGT(id, wbCompileID, testCase
                + " : allocated 'compile id' not  greater than existed");
        Asserts.assertTrue(ids.add(wbCompileID), testCase
                + " : vm compilation allocated existing id " + id);
        Asserts.assertTrue(ids.add(id), testCase
                + " : allocateCompileId returned existing id " + id);
    }
}
 
Example #8
Source File: TestPrintMdo.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main (String... args) throws Exception {

        LingeredApp app = null;

        if (!Platform.shouldSAAttach()) {
            System.out.println(
               "SA attach not expected to work - test skipped.");
            return;
        }

        try {
            List<String> vmArgs = new ArrayList<String>();
            vmArgs.add("-XX:+ProfileInterpreter");
            vmArgs.addAll(Utils.getVmOptions());

            app = LingeredApp.startApp(vmArgs);
            System.out.println ("Started LingeredApp with pid " + app.getPid());
            startClhsdbForPrintMdo(app.getPid());
            verifyPrintMdoOutput();
        } finally {
            LingeredApp.stopApp(app);
        }
    }
 
Example #9
Source File: AddExactIRepeatTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void runTest(Verify.BinaryMethod method) {
    Random rnd = Utils.getRandomInstance();
    for (int i = 0; i < 50000; ++i) {
        int x = Integer.MAX_VALUE - 10;
        int y = Integer.MAX_VALUE - 10 + rnd.nextInt(5);

        int c = rnd.nextInt() / 2;
        int d = rnd.nextInt() / 2;

        int a = catchingExact(x, y, method);

        if (a != 36) {
            throw new RuntimeException("a != 36 : " + a);
        }

        int b = nonExact(c, d, method);
        int n = exact(c, d, method);


        if (n != b) {
            throw new RuntimeException("n != b : " + n + " != " + b);
        }
    }
}
 
Example #10
Source File: TestCompilerPhase.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Recording recording = new Recording();
    recording.enable(EVENT_NAME);
    recording.start();

    // Provoke compilation
    Method mtd = TestCompilerPhase.class.getDeclaredMethod(METHOD_NAME, new Class[0]);
    WhiteBox WB = WhiteBox.getWhiteBox();
    if (!WB.enqueueMethodForCompilation(mtd, COMP_LEVEL_FULL_OPTIMIZATION)) {
        WB.enqueueMethodForCompilation(mtd, COMP_LEVEL_SIMPLE);
    }
    Utils.waitForCondition(() -> WB.isMethodCompiled(mtd));
    dummyMethod();

    recording.stop();

    List<RecordedEvent> events = Events.fromRecording(recording);
    Events.hasEvents(events);
    for (RecordedEvent event : events) {
        System.out.println("Event:" + event);
        Events.assertField(event, "phase").notEmpty();
        Events.assertField(event, "compileId").atLeast(0);
        Events.assertField(event, "phaseLevel").atLeast((short)0).atMost((short)4);
        Events.assertEventThread(event);
    }
}
 
Example #11
Source File: DockerTestUtils.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build a docker image that contains JDK under test.
 * The jdk will be placed under the "/jdk/" folder inside the docker file system.
 *
 * @param imageName     name of the image to be created, including version tag
 * @param dockerfile    name of the dockerfile residing in the test source;
 *                      we check for a platform specific dockerfile as well
 *                      and use this one in case it exists
 * @param buildDirName  name of the docker build/staging directory, which will
 *                      be created in the jtreg's scratch folder
 * @throws Exception
 */
public static void
    buildJdkDockerImage(String imageName, String dockerfile, String buildDirName)
        throws Exception {

    Path buildDir = Paths.get(".", buildDirName);
    if (Files.exists(buildDir)) {
        throw new RuntimeException("The docker build directory already exists: " + buildDir);
    }
    // check for the existance of a platform specific docker file as well
    String platformSpecificDockerfile = dockerfile + "-" + Platform.getOsArch();
    if (Files.exists(Paths.get(Utils.TEST_SRC, platformSpecificDockerfile))) {
      dockerfile = platformSpecificDockerfile;
    }

    Path jdkSrcDir = Paths.get(Utils.TEST_JDK);
    Path jdkDstDir = buildDir.resolve("jdk");

    Files.createDirectories(jdkDstDir);

    // Copy JDK-under-test tree to the docker build directory.
    // This step is required for building a docker image.
    Files.walkFileTree(jdkSrcDir, new CopyFileVisitor(jdkSrcDir, jdkDstDir));
    buildDockerImage(imageName, Paths.get(Utils.TEST_SRC, dockerfile), buildDir);
}
 
Example #12
Source File: DockerTestUtils.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run Java inside the docker image with specified parameters and options.
 *
 * @param DockerRunOptions optins for running docker
 *
 * @return output of the run command
 * @throws Exception
 */
public static OutputAnalyzer dockerRunJava(DockerRunOptions opts) throws Exception {
    ArrayList<String> cmd = new ArrayList<>();

    cmd.add("docker");
    cmd.add("run");
    if (opts.tty)
        cmd.add("--tty=true");
    if (opts.removeContainerAfterUse)
        cmd.add("--rm");

    cmd.addAll(opts.dockerOpts);
    cmd.add(opts.imageNameAndTag);
    cmd.add(opts.command);

    cmd.addAll(opts.javaOpts);
    if (opts.appendTestJavaOptions) {
        Collections.addAll(cmd, Utils.getTestJavaOpts());
    }

    cmd.add(opts.classToRun);
    cmd.addAll(opts.classParams);

    return execute(cmd);
}
 
Example #13
Source File: TestVerifySubSet.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static OutputAnalyzer runTest(String subset) throws Exception {
    ArrayList<String> vmOpts = new ArrayList();

    Collections.addAll(vmOpts, Utils.getFilteredTestJavaOpts("-Xlog.*"));
    Collections.addAll(vmOpts, new String[] {"-XX:+UnlockDiagnosticVMOptions",
                                             "-XX:+VerifyBeforeGC",
                                             "-XX:+VerifyAfterGC",
                                             "-Xlog:gc+verify=debug",
                                             "-XX:VerifySubSet="+subset,
                                             RunSystemGC.class.getName()});
    ProcessBuilder pb =
        ProcessTools.createJavaProcessBuilder(vmOpts.toArray(new String[vmOpts.size()]));
    OutputAnalyzer output = new OutputAnalyzer(pb.start());

    System.out.println("Output:\n" + output.getOutput());
    return output;
}
 
Example #14
Source File: TestG1LoggingFailure.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    List<String> options = new ArrayList<>();
    Collections.addAll(options, Utils.getTestJavaOpts());
    Collections.addAll(options,
            "-XX:+UseG1GC",
            "-Xmx20m",
            "-Xmn10m",
            "-Xlog:gc=info",
            "-XX:G1HeapRegionSize=1m"
    );

    options.add(Alloc.class.getName());

    // According to https://bugs.openjdk.java.net/browse/JDK-8146009 failure happens not every time.
    // Will try to reproduce this failure.
    for (int iteration = 0; iteration < 40; ++iteration) {
        startVM(options);
    }
}
 
Example #15
Source File: MultiCommand.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a test containing multiple random commands
 *
 * @param validOnly shows that all commands should be valid
 * @return test instance to run
 */
public static AbstractTestBase generateRandomTest(boolean validOnly) {
    CommandGenerator cmdGen = new CommandGenerator();
    List<Command> commands = cmdGen.generateCommands();
    List<CompileCommand> testCases = new ArrayList<>();
    for (Command cmd : commands) {
        if (validOnly && cmd == Command.NONEXISTENT) {
            // replace with a valid command
            cmd = Command.EXCLUDE;
        }
        Executable exec = Utils.getRandomElement(METHODS).first;
        MethodDescriptor md;
        if (validOnly) {
            md = AbstractTestBase.getValidMethodDescriptor(exec);
        } else {
            md = AbstractTestBase.METHOD_GEN.generateRandomDescriptor(exec);
        }
        CompileCommand cc = cmdGen.generateCompileCommand(cmd, md, null);
        testCases.add(cc);
    }
    return new MultiCommand(testCases);
}
 
Example #16
Source File: TestStartStopRecording.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
    Configuration defaultConfig = Configuration.getConfiguration("default");
    // Memory
    Recording inMemory = new Recording(defaultConfig);
    inMemory.setToDisk(false);

    inMemory.start();

    Path memoryFile = Utils.createTempFile("start-stop-memory-recording", ".jfr");
    inMemory.dump(memoryFile);
    assertValid(memoryFile, "Not a valid memory file.");
    inMemory.stop();
    inMemory.close();
    // Disk
    Recording toDisk = new Recording(defaultConfig);
    toDisk.setToDisk(true);

    toDisk.start();
    toDisk.stop();
    Path diskFile = Utils.createTempFile("start-stop-disk-recording", ".jfr");
    toDisk.dump(diskFile);
    assertValid(diskFile, "Not a valid disk file.");
    toDisk.close();
}
 
Example #17
Source File: DockerTestUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build a docker image that contains JDK under test.
 * The jdk will be placed under the "/jdk/" folder inside the docker file system.
 *
 * @param imageName     name of the image to be created, including version tag
 * @param dockerfile    name of the dockerfile residing in the test source;
 *                      we check for a platform specific dockerfile as well
 *                      and use this one in case it exists
 * @param buildDirName  name of the docker build/staging directory, which will
 *                      be created in the jtreg's scratch folder
 * @throws Exception
 */
public static void
    buildJdkDockerImage(String imageName, String dockerfile, String buildDirName)
        throws Exception {

    Path buildDir = Paths.get(".", buildDirName);
    if (Files.exists(buildDir)) {
        throw new RuntimeException("The docker build directory already exists: " + buildDir);
    }
    // check for the existance of a platform specific docker file as well
    String platformSpecificDockerfile = dockerfile + "-" + Platform.getOsArch();
    if (Files.exists(Paths.get(Utils.TEST_SRC, platformSpecificDockerfile))) {
      dockerfile = platformSpecificDockerfile;
    }

    Path jdkSrcDir = Paths.get(Utils.TEST_JDK);
    Path jdkDstDir = buildDir.resolve("jdk");

    Files.createDirectories(jdkDstDir);

    // Copy JDK-under-test tree to the docker build directory.
    // This step is required for building a docker image.
    Files.walkFileTree(jdkSrcDir, new CopyFileVisitor(jdkSrcDir, jdkDstDir));
    buildDockerImage(imageName, Paths.get(Utils.TEST_SRC, dockerfile), buildDir);
}
 
Example #18
Source File: DockerTestUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run Java inside the docker image with specified parameters and options.
 *
 * @param DockerRunOptions optins for running docker
 *
 * @return output of the run command
 * @throws Exception
 */
public static OutputAnalyzer dockerRunJava(DockerRunOptions opts) throws Exception {
    ArrayList<String> cmd = new ArrayList<>();

    cmd.add("docker");
    cmd.add("run");
    if (opts.tty)
        cmd.add("--tty=true");
    if (opts.removeContainerAfterUse)
        cmd.add("--rm");

    cmd.addAll(opts.dockerOpts);
    cmd.add(opts.imageNameAndTag);
    cmd.add(opts.command);

    cmd.addAll(opts.javaOpts);
    if (opts.appendTestJavaOptions) {
        Collections.addAll(cmd, Utils.getTestJavaOpts());
    }

    cmd.add(opts.classToRun);
    cmd.addAll(opts.classParams);

    return execute(cmd);
}
 
Example #19
Source File: TestRecordingFile.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static Path createBrokenMetadata(Path valid) throws Exception {
    try {
        Path broken = Utils.createTempFile("broken-metadata", ".jfr");
        Files.delete(broken);
        Files.copy(valid, broken);
        RandomAccessFile raf = new RandomAccessFile(broken.toFile(), "rw");
        raf.seek(METADATA_OFFSET);
        long metadataOffset = raf.readLong();
        raf.seek(metadataOffset);
        raf.writeLong(Long.MAX_VALUE);
        raf.writeLong(Long.MAX_VALUE);
        raf.close();
        return broken;
    } catch (IOException ioe) {
        throw new Exception("Could not produce a broken EventSet from file " + valid, ioe);
    }
}
 
Example #20
Source File: ProcessTools.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create ProcessBuilder using the java launcher from the jdk to be tested,
 * and with any platform specific arguments prepended.
 *
 * @param addTestVmAndJavaOptions If true, adds test.vm.opts and test.java.opts
 *        to the java arguments.
 * @param command Arguments to pass to the java command.
 * @return The ProcessBuilder instance representing the java command.
 */
public static ProcessBuilder createJavaProcessBuilder(boolean addTestVmAndJavaOptions, String... command) throws Exception {
    String javapath = JDKToolFinder.getJDKTool("java");

    ArrayList<String> args = new ArrayList<>();
    args.add(javapath);
    Collections.addAll(args, getPlatformSpecificVMArgs());

    args.add("-cp");
    args.add(System.getProperty("java.class.path"));

    if (addTestVmAndJavaOptions) {
        Collections.addAll(args, Utils.getTestJavaOpts());
    }

    Collections.addAll(args, command);

    // Reporting
    StringBuilder cmdLine = new StringBuilder();
    for (String cmd : args)
        cmdLine.append(cmd).append(' ');
    System.out.println("Command line: [" + cmdLine.toString() + "]");

    return new ProcessBuilder(args.toArray(new String[args.size()]));
}
 
Example #21
Source File: ProcessTools.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create ProcessBuilder using the java launcher from the jdk to be tested,
 * and with any platform specific arguments prepended.
 *
 * @param addTestVmAndJavaOptions If true, adds test.vm.opts and test.java.opts
 *        to the java arguments.
 * @param command Arguments to pass to the java command.
 * @return The ProcessBuilder instance representing the java command.
 */
public static ProcessBuilder createJavaProcessBuilder(boolean addTestVmAndJavaOptions, String... command) {
    String javapath = JDKToolFinder.getJDKTool("java");

    ArrayList<String> args = new ArrayList<>();
    args.add(javapath);

    args.add("-cp");
    args.add(System.getProperty("java.class.path"));

    if (addTestVmAndJavaOptions) {
        Collections.addAll(args, Utils.getTestJavaOpts());
    }

    Collections.addAll(args, command);

    // Reporting
    StringBuilder cmdLine = new StringBuilder();
    for (String cmd : args)
        cmdLine.append(cmd).append(' ');
    System.out.println("Command line: [" + cmdLine.toString() + "]");

    return new ProcessBuilder(args.toArray(new String[args.size()]));
}
 
Example #22
Source File: TestPrint.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {

        OutputAnalyzer output = ExecuteHelper.jfr("print");
        output.shouldContain("missing file");

        output = ExecuteHelper.jfr("print", "missing.jfr");
        output.shouldContain("could not find file ");

        Path file = Utils.createTempFile("faked-print-file",  ".jfr");
        FileWriter fw = new FileWriter(file.toFile());
        fw.write('d');
        fw.close();
        output = ExecuteHelper.jfr("print", "--wrongOption", file.toAbsolutePath().toString());
        output.shouldContain("unknown option");
        Files.delete(file);
    }
 
Example #23
Source File: MulExactIRepeatTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void runTest(Verify.BinaryMethod method) {
    Random rnd = Utils.getRandomInstance();
    for (int i = 0; i < 50000; ++i) {
        int x = Integer.MAX_VALUE - 10;
        int y = Integer.MAX_VALUE - 10 + rnd.nextInt(5);

        int c = rnd.nextInt() / 10;
        int d = rnd.nextInt(9);

        int a = catchingExact(x, y, method);

        if (a != 36) {
            throw new RuntimeException("a != 36 : " + a);
        }

        int b = nonExact(c, d, method);
        int n = exact(c, d, method);


        if (n != b) {
            throw new RuntimeException("n != b : " + n + " != " + b);
        }
    }
}
 
Example #24
Source File: ThresholdNotificationsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
protected void runTest() {
    int iterationsCount
            = Integer.getInteger("jdk.test.lib.iterations", 1);
    MemoryPoolMXBean bean = btype.getMemoryPool();
    ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
            addNotificationListener(this, null, null);
    for (int i = 0; i < iterationsCount; i++) {
        CodeCacheUtils.hitUsageThreshold(bean, btype);
    }
    Asserts.assertTrue(
            Utils.waitForCondition(
                    () -> (CodeCacheUtils.isCodeHeapPredictable(btype) ?
                            (counter == iterationsCount) : (counter >= iterationsCount)),
                    WAIT_TIME),
            "Couldn't receive expected notifications count");
    try {
        ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
                removeNotificationListener(this);
    } catch (ListenerNotFoundException ex) {
        throw new AssertionError("Can't remove notification listener", ex);
    }
    System.out.printf("INFO: Scenario finished successfully for %s%n",
            bean.getName());
}
 
Example #25
Source File: TestStressG1Humongous.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void run(int heapSize, int regionSize, int threads, double humongousSize, int timeout)
        throws Exception {
    ArrayList<String> options = new ArrayList<>();
    Collections.addAll(options, Utils.getTestJavaOpts());
    Collections.addAll(options,
            "-Xlog:gc=debug",
            "-Xmx" + heapSize + "m",
            "-XX:+UseG1GC",
            "-XX:G1HeapRegionSize=" + regionSize + "m",
            "-Dtimeout=" + timeout,
            "-Dthreads=" + threads,
            "-Dhumongoussize=" + humongousSize,
            "-Dregionsize=" + regionSize,
            TestStressG1HumongousImpl.class.getName()
    );
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(options.toArray(new String[options.size()]));
    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    output.shouldHaveExitValue(0);
}
 
Example #26
Source File: TestNewRatioFlag.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    LinkedList<String> options = new LinkedList<>(
            Arrays.asList(Utils.getFilteredTestJavaOpts("(-XX:[^ ]*NewSize=[^ ]+)|(-Xm[ns][^ ]+)"))
    );

    testNewRatio(4, options);
    testNewRatio(6, options);
    testNewRatio(10, options);
    testNewRatio(15, options);
    testNewRatio(20, options);
}
 
Example #27
Source File: PLABUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prepares options for testing.
 *
 * @param options - additional options for testing
 * @return List of options
 */
public static List<String> prepareOptions(List<String> options) {
    if (options == null) {
        throw new IllegalArgumentException("Options cannot be null");
    }
    List<String> executionOtions = new ArrayList<>(
            Arrays.asList(Utils.getTestJavaOpts())
    );
    Collections.addAll(executionOtions, WB_DIAGNOSTIC_OPTIONS);
    Collections.addAll(executionOtions, G1_PLAB_LOGGING_OPTIONS);
    Collections.addAll(executionOtions, GC_TUNE_OPTIONS);
    executionOtions.addAll(options);
    return executionOtions;
}
 
Example #28
Source File: Common.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static DockerRunOptions newOpts(String imageNameAndTag, String testClass) {
    DockerRunOptions opts =
        new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", testClass);
    opts.addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/");
    opts.addJavaOpts("-Xlog:os+container=trace", "-cp", "/test-classes/");
    return opts;
}
 
Example #29
Source File: DockerTestUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute a specified command in a process, report diagnostic info.
 *
 * @param command to be executed
 * @return The output from the process
 * @throws Exception
 */
public static OutputAnalyzer execute(String... command) throws Exception {

    ProcessBuilder pb = new ProcessBuilder(command);
    System.out.println("[COMMAND]\n" + Utils.getCommandLine(pb));

    long started = System.currentTimeMillis();
    OutputAnalyzer output = new OutputAnalyzer(pb.start());

    System.out.println("[ELAPSED: " + (System.currentTimeMillis() - started) + " ms]");
    System.out.println("[STDERR]\n" + output.getStderr());
    System.out.println("[STDOUT]\n" + output.getStdout());

    return output;
}
 
Example #30
Source File: Test6603011.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void test_divisor(int divisor,
                                ClassLoader apploader) throws Exception {
  System.setProperty("divisor", "" + divisor);
  ClassLoader loader
              = Utils.getTestClassPathURLClassLoader(apploader.getParent());
  Class c = loader.loadClass(Test6603011.class.getName());
  Runnable r = (Runnable)c.newInstance();
  r.run();
}