Java Code Examples for jdk.test.lib.process.OutputAnalyzer#shouldMatch()

The following examples show how to use jdk.test.lib.process.OutputAnalyzer#shouldMatch() . 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: RangeCheck.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 {
    if (!Platform.isDebugBuild()) {
        System.out.println("Testing assert which requires a debug build. Passing silently.");
        return;
    }

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
            true,
            "-Xmx32m",
            "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
            "-XX:-TransmitErrorReport",
            "-XX:-CreateCoredumpOnCrash",
            "-XX:-InlineUnsafeOps", // The compiler intrinsics doesn't have the assert
            DummyClassWithMainRangeCheck.class.getName());

    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    output.shouldMatch("assert\\(byte_offset < p_size\\) failed: Unsafe access: offset \\d+ > object's size \\d+");
}
 
Example 2
Source File: TestPrintReferences.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 {
  ProcessBuilder pb_enabled =
    ProcessTools.createJavaProcessBuilder("-Xlog:gc+ref=debug", "-Xmx10M", GCTest.class.getName());
  OutputAnalyzer output = new OutputAnalyzer(pb_enabled.start());

  String countRegex = "[0-9]+ refs";
  String timeRegex = "[0-9]+[.,][0-9]+ms";

  output.shouldMatch(".* GC\\([0-9]+\\) SoftReference " + timeRegex + "\n" +
                     ".* GC\\([0-9]+\\) WeakReference " + timeRegex + "\n" +
                     ".* GC\\([0-9]+\\) FinalReference " + timeRegex + "\n" +
                     ".* GC\\([0-9]+\\) PhantomReference " + timeRegex + "\n" +
                     ".* GC\\([0-9]+\\) JNI Weak Reference " + timeRegex + "\n" +
                     ".* GC\\([0-9]+\\) Ref Counts: Soft: [0-9]+ Weak: [0-9]+ Final: [0-9]+ Phantom: [0-9]+\n");

  output.shouldHaveExitValue(0);
}
 
Example 3
Source File: JcmdHelper.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void waitUntilRunning(String name) throws Exception {
    long timeoutAt = System.currentTimeMillis() + 10000;
    while (true) {
        OutputAnalyzer output = jcmdCheck(name, false);
        try {
            // The expected output can look like this:
            // Recording 1: name=1 (running)
            output.shouldMatch("^Recording \\d+: name=" + name
                    + " .*\\W{1}running\\W{1}");
            return;
        } catch (RuntimeException e) {
            if (System.currentTimeMillis() > timeoutAt) {
                Asserts.fail("Recording not started: " + name);
            }
            Thread.sleep(100);
        }
    }
}
 
Example 4
Source File: CommandLineOptionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Verifies that value of specified JVM option is the same as
 * expected value.
 *
 * @param optionName a name of tested option.
 * @param expectedValue expected value of tested option.
 * @param optionErrorString message will be shown if option value is not
 *                          as expected.
 * @param outputAnalyzer OutputAnalyzer instance
 * @throws AssertionError if verification fails
 */
public static void verifyOptionValue(String optionName,
        String expectedValue, String optionErrorString,
        OutputAnalyzer outputAnalyzer) {
    try {
        outputAnalyzer.shouldMatch(String.format(
                CommandLineOptionTest.PRINT_FLAGS_FINAL_FORMAT,
                optionName, expectedValue));
    } catch (RuntimeException e) {
        String errorMessage = String.format(
                "Option '%s' is expected to have '%s' value%n%s",
                optionName, expectedValue,
                optionErrorString);
        throw new AssertionError(errorMessage, e);
    }
}
 
Example 5
Source File: TestVerifyBeforeAndAfterGCFlags.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void testVerifyFlags(boolean verifyBeforeGC,
                                   boolean verifyAfterGC,
                                   String[] opts) throws Exception {
    ArrayList<String> vmOpts = new ArrayList<>();
    if (opts != null && (opts.length > 0)) {
        Collections.addAll(vmOpts, opts);
    }

    Collections.addAll(vmOpts, new String[] {
                                   "-Xlog:gc+verify=debug",
                                   "-Xmx5m",
                                   "-Xms5m",
                                   "-Xmn3m",
                                   "-XX:+UnlockDiagnosticVMOptions",
                                   (verifyBeforeGC ? "-XX:+VerifyBeforeGC"
                                                   : "-XX:-VerifyBeforeGC"),
                                   (verifyAfterGC ? "-XX:+VerifyAfterGC"
                                                  : "-XX:-VerifyAfterGC"),
                                   GarbageProducer.class.getName() });
    ProcessBuilder procBuilder =
        ProcessTools.createJavaProcessBuilder(vmOpts.toArray(
                                               new String[vmOpts.size()]));
    OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start());

    analyzer.shouldHaveExitValue(0);
    analyzer.shouldNotMatch(VERIFY_BEFORE_GC_CORRUPTED_PATTERN);
    analyzer.shouldNotMatch(VERIFY_AFTER_GC_CORRUPTED_PATTERN);

    if (verifyBeforeGC) {
        analyzer.shouldMatch(VERIFY_BEFORE_GC_PATTERN);
    } else {
        analyzer.shouldNotMatch(VERIFY_BEFORE_GC_PATTERN);
    }

    if (verifyAfterGC) {
        analyzer.shouldMatch(VERIFY_AFTER_GC_PATTERN);
    } else {
        analyzer.shouldNotMatch(VERIFY_AFTER_GC_PATTERN);
    }
}
 
Example 6
Source File: TestGCLogMessages.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void checkMessagesAtLevel(OutputAnalyzer output, LogMessageWithLevel messages[], Level level) throws Exception {
    for (LogMessageWithLevel l : messages) {
        if (level.lessThan(l.level)) {
            output.shouldNotContain(l.message);
        } else {
            output.shouldMatch("\\[" + l.level + ".*" + l.message);
        }
    }
}
 
Example 7
Source File: TestStringSymbolTableStats.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 {

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC",
                                                              "-XX:+UnlockExperimentalVMOptions",
                                                              "-Xlog:gc+stringtable=trace",
                                                              SystemGCTest.class.getName());

    OutputAnalyzer output = new OutputAnalyzer(pb.start());

    System.out.println("Output:\n" + output.getOutput());

    output.shouldMatch("GC\\(\\d+\\) Cleaned string and symbol table");
    output.shouldHaveExitValue(0);
  }
 
Example 8
Source File: TestG1ClassUnloadingHWM.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void testWithG1ClassUnloading() throws Exception {
  // -XX:+ClassUnloadingWithConcurrentMark is used, so we expect a concurrent cycle instead of a full GC.
  OutputAnalyzer out = runWithG1ClassUnloading();

  out.shouldMatch(".*Pause Initial Mark.*");
  out.shouldNotMatch(".*Pause Full.*");
}
 
Example 9
Source File: ClassHistogramTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void run(CommandExecutor executor) {
    OutputAnalyzer output = executor.execute("GC.class_histogram " + classHistogramArgs);

    /*
     * example output:
     *  num     #instances         #bytes  class name (module)
     * -------------------------------------------------------
     *    1:          7991         757792  [B (java.base@9-internal)
     *    2:          1811         217872  java.lang.Class (java.base@9-internal)
     *    3:          6724         215168  java.util.HashMap$Node (java.base@9-internal)
     *    4:          7852         188448  java.lang.String (java.base@9-internal)
     *    5:          1378         105040  [Ljava.util.HashMap$Node; (java.base@9-internal)
     *    6:          1863          95096  [Ljava.lang.Object; (java.base@9-internal)

     * ...
     */

    /* Require at least one java.lang.Class */
    output.shouldMatch("^\\s+\\d+:\\s+\\d+\\s+\\d+\\s+java.lang.Class \\(java.base@\\S*\\)\\s*$");

    /* Require at least one java.lang.String */
    output.shouldMatch("^\\s+\\d+:\\s+\\d+\\s+\\d+\\s+java.lang.String \\(java.base@\\S*\\)\\s*$");

    /* Require at least one java.lang.Object */
    output.shouldMatch("^\\s+\\d+:\\s+\\d+\\s+\\d+\\s+java.lang.Object \\(java.base@\\S*\\)\\s*$");

    /* Require at exactly one TestClass[] */
    output.shouldMatch("^\\s+\\d+:\\s+1\\s+\\d+\\s+" +
        Pattern.quote(TestClass[].class.getName()) + "\\s*$");

    /* Require at exactly 1024 TestClass */
    output.shouldMatch("^\\s+\\d+:\\s+1024\\s+\\d+\\s+" +
        Pattern.quote(TestClass.class.getName()) + "\\s*$");
}
 
Example 10
Source File: CommandLineOptionTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies from the output that values of specified JVM options were the same as
 * expected values.
 *
 * @param outputAnalyzer search output for expect options and values.
 * @param optionNames names of tested options.
 * @param expectedValues expected values of tested options.
 * @throws Throwable if verification fails or some other issues occur.
 */
public static void verifyOptionValuesFromOutput(OutputAnalyzer outputAnalyzer,
        String[] optionNames,
        String[] expectedValues) throws Throwable {
    outputAnalyzer.shouldHaveExitValue(0);
    for (int i = 0; i < optionNames.length; i++) {
      outputAnalyzer.shouldMatch(String.format(
            CommandLineOptionTest.PRINT_FLAGS_FINAL_FORMAT,
            optionNames[i], expectedValues[i]));
    }
}
 
Example 11
Source File: StartupTimeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void analyzeOutputOn(ProcessBuilder pb) throws Exception {
    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    output.shouldMatch("(Genesis, [0-9]+.[0-9]+ secs)");
    output.shouldMatch("(Start VMThread, [0-9]+.[0-9]+ secs)");
    output.shouldMatch("(Create VM, [0-9]+.[0-9]+ secs)");
    output.shouldHaveExitValue(0);
}
 
Example 12
Source File: TestNewSizeFlags.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verify that NewSize and MaxNewSize flags affect young gen size.
 *
 * @param newSize value of NewSize option, omitted if negative
 * @param maxNewSize value of MaxNewSize option, omitted if negative
 * @param heapSize value of HeapSize option
 * @param maxHeapSize value of MaxHeapSize option
 * @param expectedNewSize expected initial young gen size
 * @param expectedMaxNewSize expected max young gen size
 * @param options additional options for JVM
 * @param failureExpected true if JVM should fail with passed heap size options
 */
public static void testVMOptions(long newSize, long maxNewSize,
        long heapSize, long maxHeapSize,
        long expectedNewSize, long expectedMaxNewSize,
        LinkedList<String> options, boolean failureExpected) throws Exception {
    OutputAnalyzer analyzer = startVM(options, newSize, maxNewSize, heapSize, maxHeapSize, expectedNewSize, expectedMaxNewSize);

    if (failureExpected) {
        analyzer.shouldHaveExitValue(1);
        analyzer.shouldMatch("(Error occurred during initialization of VM)|"
                + "(Error: Could not create the Java Virtual Machine.)");
    } else {
        analyzer.shouldHaveExitValue(0);
    }
}
 
Example 13
Source File: TestCMSClassUnloadingEnabledHWM.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void testWithCMSClassUnloading() throws Exception {
  // -XX:+CMSClassUnloadingEnabled is used, so we expect a concurrent cycle instead of a full GC.
  OutputAnalyzer out = runWithCMSClassUnloading();

  out.shouldMatch(".*Pause Initial Mark.*");
  out.shouldNotMatch(".*Pause Full.*");
}
 
Example 14
Source File: JcmdAsserts.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void assertJfrUsed(OutputAnalyzer output) {
    output.shouldMatch("Flight Recorder has been used");
}
 
Example 15
Source File: StartupTimeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
static void analyzeModulesOutputOn(ProcessBuilder pb) throws Exception {
    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    output.shouldMatch("(Phase2 initialization, [0-9]+.[0-9]+ secs)");
    output.shouldHaveExitValue(0);
}
 
Example 16
Source File: JcmdAsserts.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void assertRecordingIsRunning(OutputAnalyzer output, String name) {
    output.shouldMatch(".*" + name + ".*running");
}
 
Example 17
Source File: VMVersionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void run(CommandExecutor executor) {
    OutputAnalyzer output = executor.execute("VM.version");
    output.shouldMatch(".*(?:HotSpot|OpenJDK).*VM.*");
}
 
Example 18
Source File: SafeFetchInErrorHandlingTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

    if (!Platform.isDebugBuild() || Platform.isZero()) {
      return;
    }

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
        "-XX:+UnlockDiagnosticVMOptions",
        "-Xmx100M",
        "-XX:ErrorHandlerTest=14",
        "-XX:+TestSafeFetchInErrorHandler",
        "-XX:-CreateCoredumpOnCrash",
        "-version");

    OutputAnalyzer output_detail = new OutputAnalyzer(pb.start());

    // we should have crashed with a SIGSEGV
    output_detail.shouldMatch("# A fatal error has been detected by the Java Runtime Environment:.*");
    output_detail.shouldMatch("# +(?:SIGSEGV|EXCEPTION_ACCESS_VIOLATION).*");

    // extract hs-err file
    String hs_err_file = output_detail.firstMatch("# *(\\S*hs_err_pid\\d+\\.log)", 1);
    if (hs_err_file == null) {
      throw new RuntimeException("Did not find hs-err file in output.\n");
    }

    File f = new File(hs_err_file);
    if (!f.exists()) {
      throw new RuntimeException("hs-err file missing at "
          + f.getAbsolutePath() + ".\n");
    }

    System.out.println("Found hs_err file. Scanning...");

    FileInputStream fis = new FileInputStream(f);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String line = null;

    Pattern [] pattern = new Pattern[] {
        Pattern.compile("Will test SafeFetch..."),
        Pattern.compile("SafeFetch OK."),
    };
    int currentPattern = 0;

    String lastLine = null;
    while ((line = br.readLine()) != null) {
      if (currentPattern < pattern.length) {
        if (pattern[currentPattern].matcher(line).matches()) {
          System.out.println("Found: " + line + ".");
          currentPattern ++;
        }
      }
      lastLine = line;
    }
    br.close();

    if (currentPattern < pattern.length) {
      throw new RuntimeException("hs-err file incomplete (first missing pattern: " +  currentPattern + ")");
    }

    if (!lastLine.equals("END.")) {
      throw new RuntimeException("hs-err file incomplete (missing END marker.)");
    } else {
      System.out.println("End marker found.");
    }

    System.out.println("OK.");

  }
 
Example 19
Source File: JcmdAsserts.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void assertFileNotFoundException(OutputAnalyzer output, String name) {
    output.shouldMatch("Could not write recording \"" + name + "\" to file.*");
}
 
Example 20
Source File: JcmdAsserts.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void assertJfrUsed(OutputAnalyzer output) {
    output.shouldMatch("Flight Recorder has been used");
}