jdk.test.lib.process.OutputAnalyzer.shouldMatch() - java examples

Here are the examples of the java api jdk.test.lib.process.OutputAnalyzer.shouldMatch() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

44 Examples 7

19 View Complete Implementation : TestDisableDefaultGC.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    // Start VM, disabling all possible default GCs
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:-UseSerialGC", "-XX:-UseParallelGC", "-XX:-UseG1GC", "-XX:-UseConcMarkSweepGC", "-version");
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    output.shouldMatch("Garbage collector not selected");
    output.shouldHaveExitValue(1);
}

19 View Complete Implementation : TestNewSizeFlags.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
/**
 * 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 preplaceded 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 {
    Outputreplacedyzer replacedyzer = startVM(options, newSize, maxNewSize, heapSize, maxHeapSize, expectedNewSize, expectedMaxNewSize);
    if (failureExpected) {
        replacedyzer.shouldHaveExitValue(1);
        replacedyzer.shouldMatch("(Error occurred during initialization of VM)|" + "(Error: Could not create the Java Virtual Machine.)");
    } else {
        replacedyzer.shouldHaveExitValue(0);
    }
}

19 View Complete Implementation : TestSelectDefaultGC.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void replacedertVMOption(Outputreplacedyzer output, String option, boolean value) {
    output.shouldMatch(" " + option + " .*=.* " + value + " ");
}

19 View Complete Implementation : TestUseNUMAInterleaving.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    String[] vmargs = new String[] { "-XX:+UseNUMA", "-XX:+PrintFlagsFinal", "-version" };
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, vmargs);
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    boolean isNUMAEnabled = Boolean.parseBoolean(output.firstMatch(NUMA_FLAG_PATTERN, 1));
    if (isNUMAEnabled) {
        output.shouldMatch("\\bUseNUMAInterleaving\\b.*?=.*?true");
        System.out.println(output.getStdout());
    } else {
        System.out.println(output.firstMatch(NUMA_FLAG_PATTERN));
        System.out.println(output.firstMatch(NUMA_FLAG_PATTERN, 1));
    }
}

19 View Complete Implementation : TestVerifyBeforeAndAfterGCFlags.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
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.clreplaced.getName() });
    ProcessBuilder procBuilder = ProcessTools.createJavaProcessBuilder(vmOpts.toArray(new String[vmOpts.size()]));
    Outputreplacedyzer replacedyzer = new Outputreplacedyzer(procBuilder.start());
    replacedyzer.shouldHaveExitValue(0);
    replacedyzer.shouldNotMatch(VERIFY_BEFORE_GC_CORRUPTED_PATTERN);
    replacedyzer.shouldNotMatch(VERIFY_AFTER_GC_CORRUPTED_PATTERN);
    if (verifyBeforeGC) {
        replacedyzer.shouldMatch(VERIFY_BEFORE_GC_PATTERN);
    } else {
        replacedyzer.shouldNotMatch(VERIFY_BEFORE_GC_PATTERN);
    }
    if (verifyAfterGC) {
        replacedyzer.shouldMatch(VERIFY_AFTER_GC_PATTERN);
    } else {
        replacedyzer.shouldNotMatch(VERIFY_AFTER_GC_PATTERN);
    }
}

19 View Complete Implementation : TestCMSClassUnloadingEnabledHWM.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void testWithoutCMSClreplacedUnloading() throws Exception {
    // -XX:-CMSClreplacedUnloadingEnabled is used, so we expect a full GC instead of a concurrent cycle.
    Outputreplacedyzer out = runWithoutCMSClreplacedUnloading();
    out.shouldMatch(".*Pause Full.*");
    out.shouldNotMatch(".*Pause Initial Mark.*");
}

19 View Complete Implementation : TestCMSClassUnloadingEnabledHWM.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void testWithCMSClreplacedUnloading() throws Exception {
    // -XX:+CMSClreplacedUnloadingEnabled is used, so we expect a concurrent cycle instead of a full GC.
    Outputreplacedyzer out = runWithCMSClreplacedUnloading();
    out.shouldMatch(".*Pause Initial Mark.*");
    out.shouldNotMatch(".*Pause Full.*");
}

19 View Complete Implementation : TestG1ClassUnloadingHWM.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void testWithG1ClreplacedUnloading() throws Exception {
    // -XX:+ClreplacedUnloadingWithConcurrentMark is used, so we expect a concurrent cycle instead of a full GC.
    Outputreplacedyzer out = runWithG1ClreplacedUnloading();
    out.shouldMatch(".*Pause Initial Mark.*");
    out.shouldNotMatch(".*Pause Full.*");
}

19 View Complete Implementation : TestG1ClassUnloadingHWM.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void testWithoutG1ClreplacedUnloading() throws Exception {
    // -XX:-ClreplacedUnloadingWithConcurrentMark is used, so we expect a full GC instead of a concurrent cycle.
    Outputreplacedyzer out = runWithoutG1ClreplacedUnloading();
    out.shouldMatch(".*Pause Full.*");
    out.shouldNotMatch(".*Pause Initial Mark.*");
}

19 View Complete Implementation : TestGCLogMessages.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
void checkMessagesAtLevel(Outputreplacedyzer 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);
        }
    }
}

19 View Complete Implementation : TestStringSymbolTableStats.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", "-XX:+UnlockExperimentalVMOptions", "-Xlog:gc+stringtable=trace", SystemGCTest.clreplaced.getName());
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    System.out.println("Output:\n" + output.getOutput());
    output.shouldMatch("GC\\(\\d+\\) Cleaned string and symbol table");
    output.shouldHaveExitValue(0);
}

19 View Complete Implementation : TestGCId.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
private static void verifyContainsGCIDs(Outputreplacedyzer output) {
    output.shouldMatch("\\[.*\\]\\[.*\\]\\[.*\\] GC\\(0\\) ");
    output.shouldMatch("\\[.*\\]\\[.*\\]\\[.*\\] GC\\(1\\) ");
    output.shouldHaveExitValue(0);
}

19 View Complete Implementation : TestPrintReferences.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder("-Xlog:gc+ref=debug", "-Xmx10M", GCTest.clreplaced.getName());
    Outputreplacedyzer output = new Outputreplacedyzer(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);
}

19 View Complete Implementation : TestVMOptions.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:bogus", "-XX:+IgnoreUnrecognizedVMOptions", "-XX:+PrintFlagsInitial");
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    output.shouldContain("bool UseSerialGC");
    pb = ProcessTools.createJavaProcessBuilder("-XX:-PrintVMOptions", "-version");
    output = new Outputreplacedyzer(pb.start());
    output.shouldMatch("(openjdk|java)\\sversion");
    File dir = new File(System.getProperty("test.src", "."));
    File file = new File(dir, "flagfile.txt");
    String s = file.getAbsolutePath();
    pb = ProcessTools.createJavaProcessBuilder("-XX:Flags=" + s);
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("VM option '-IgnoreUnrecognizedVMOptions'");
}

19 View Complete Implementation : VMDeprecatedOptions.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
static void testDeprecated(String[][] optionInfo) throws Throwable {
    String[] optionNames = new String[optionInfo.length];
    String[] expectedValues = new String[optionInfo.length];
    for (int i = 0; i < optionInfo.length; i++) {
        optionNames[i] = optionInfo[i][0];
        expectedValues[i] = optionInfo[i][1];
    }
    Outputreplacedyzer output = CommandLineOptionTest.startVMWithOptions(optionNames, expectedValues);
    // check for option deprecation messages:
    output.shouldHaveExitValue(0);
    for (String[] deprecated : optionInfo) {
        String match = getDeprecationString(deprecated[0]);
        output.shouldMatch(match);
    }
}

19 View Complete Implementation : SafeFetchInErrorHandlingTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
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");
    Outputreplacedyzer output_detail = new Outputreplacedyzer(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.");
}

19 View Complete Implementation : StartupTimeTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
static void replacedyzeOutputOn(ProcessBuilder pb) throws Exception {
    Outputreplacedyzer output = new Outputreplacedyzer(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);
}

19 View Complete Implementation : StartupTimeTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
static void replacedyzeModulesOutputOn(ProcessBuilder pb) throws Exception {
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    output.shouldMatch("(Phase2 initialization, [0-9]+.[0-9]+ secs)");
    output.shouldHaveExitValue(0);
}

19 View Complete Implementation : ThreadedVirtualAllocTestType.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    Outputreplacedyzer output;
    String pid = Long.toString(ProcessTools.getProcessId());
    ProcessBuilder pb = new ProcessBuilder();
    Thread reserveThread = new Thread() {

        public void run() {
            addr = wb.NMTReserveMemory(reserveSize);
        }
    };
    reserveThread.start();
    reserveThread.join();
    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "detail" });
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=512KB, committed=0KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 512KB for Test");
    Thread commitThread = new Thread() {

        public void run() {
            wb.NMTCommitMemory(addr, commitSize);
        }
    };
    commitThread.start();
    commitThread.join();
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=512KB, committed=128KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + commitSize) + "\\] committed 128KB");
    Thread uncommitThread = new Thread() {

        public void run() {
            wb.NMTUncommitMemory(addr, commitSize);
        }
    };
    uncommitThread.start();
    uncommitThread.join();
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=512KB, committed=0KB)");
    output.shouldNotMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + commitSize) + "\\] committed");
    Thread releaseThread = new Thread() {

        public void run() {
            wb.NMTReleaseMemory(addr, reserveSize);
        }
    };
    releaseThread.start();
    releaseThread.join();
    output = new Outputreplacedyzer(pb.start());
    output.shouldNotContain("Test (reserved=");
    output.shouldNotContain("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved");
}

19 View Complete Implementation : VirtualAllocCommitUncommitRecommit.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    Outputreplacedyzer output;
    // 128KB
    long commitSize = 128 * 1024;
    // 4096KB
    long reserveSize = 4 * 1024 * 1024;
    long addr;
    String pid = Long.toString(ProcessTools.getProcessId());
    ProcessBuilder pb = new ProcessBuilder();
    // reserve
    addr = wb.NMTReserveMemory(reserveSize);
    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "detail" });
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=4096KB, committed=0KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 4096KB for Test");
    long addrA = addr;
    long addrB = addr + commitSize;
    long addrC = addr + (2 * commitSize);
    long addrD = addr + (3 * commitSize);
    long addrE = addr + (4 * commitSize);
    long addrF = addr + (5 * commitSize);
    // commit ABCD
    wb.NMTCommitMemory(addrA, commitSize);
    wb.NMTCommitMemory(addrB, commitSize);
    wb.NMTCommitMemory(addrC, commitSize);
    wb.NMTCommitMemory(addrD, commitSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=4096KB, committed=512KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 4096KB for Test");
    // uncommit BC
    wb.NMTUncommitMemory(addrB, commitSize);
    wb.NMTUncommitMemory(addrC, commitSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=4096KB, committed=256KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 4096KB for Test");
    // commit EF
    wb.NMTCommitMemory(addrE, commitSize);
    wb.NMTCommitMemory(addrF, commitSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=4096KB, committed=512KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 4096KB for Test");
    // uncommit A
    wb.NMTUncommitMemory(addrA, commitSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=4096KB, committed=384KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 4096KB for Test");
    // commit ABC
    wb.NMTCommitMemory(addrA, commitSize);
    wb.NMTCommitMemory(addrB, commitSize);
    wb.NMTCommitMemory(addrC, commitSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=4096KB, committed=768KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 4096KB for Test");
    // uncommit ABCDEF
    wb.NMTUncommitMemory(addrA, commitSize);
    wb.NMTUncommitMemory(addrB, commitSize);
    wb.NMTUncommitMemory(addrC, commitSize);
    wb.NMTUncommitMemory(addrD, commitSize);
    wb.NMTUncommitMemory(addrE, commitSize);
    wb.NMTUncommitMemory(addrF, commitSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=4096KB, committed=0KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 4096KB for Test");
    // release
    wb.NMTReleaseMemory(addr, reserveSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldNotContain("Test (reserved=");
    output.shouldNotMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 4096KB for Test");
}

19 View Complete Implementation : VirtualAllocTestType.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    Outputreplacedyzer output;
    long commitSize = 128 * 1024;
    long reserveSize = 256 * 1024;
    long addr;
    String pid = Long.toString(ProcessTools.getProcessId());
    ProcessBuilder pb = new ProcessBuilder();
    addr = wb.NMTReserveMemory(reserveSize);
    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "detail" });
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=256KB, committed=0KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 256KB for Test");
    wb.NMTCommitMemory(addr, commitSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=256KB, committed=128KB)");
    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + commitSize) + "\\] committed 128KB");
    wb.NMTUncommitMemory(addr, commitSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Test (reserved=256KB, committed=0KB)");
    output.shouldNotMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + commitSize) + "\\] committed");
    wb.NMTReleaseMemory(addr, reserveSize);
    output = new Outputreplacedyzer(pb.start());
    output.shouldNotContain("Test (reserved=");
    output.shouldNotMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved");
}

19 View Complete Implementation : ArchiveDoesNotExist.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    String fileName = "ArchiveDoesNotExist.jsa";
    File cdsFile = new File(fileName);
    if (cdsFile.exists())
        throw new RuntimeException("Test error: cds file already exists");
    // Sharing: on
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./" + fileName, "-Xshare:on", "-version");
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    output.shouldContain("Specified shared archive not found");
    output.shouldHaveExitValue(1);
    // Sharing: auto
    pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./" + fileName, "-Xshare:auto", "-version");
    output = new Outputreplacedyzer(pb.start());
    output.shouldMatch("(java|openjdk) version");
    output.shouldNotContain("sharing");
    output.shouldHaveExitValue(0);
}

19 View Complete Implementation : BootAppendTests.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
// Test #4: If a clreplaced on -Xbootclreplacedpath/a has the same fully qualified
// name as a clreplaced defined in boot modules, the clreplaced is loaded
// from -Xbootclreplacedpath/a when the boot module is excluded using
// --limit-modules. Verify the behavior is the same at runtime
// when CDS is enabled.
// 
// The org.omg.CORBA.Context is a boot module clreplaced. The clreplaced
// on -Xbootclreplacedpath/a that has the same fully-qualified name
// as org.omg.CORBA.Context can be loaded at runtime when
// java.corba is excluded.
public static void testBootAppendDuplicateExcludedModuleClreplaced() throws Exception {
    for (String mode : modes) {
        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./BootAppendTests.jsa", "-XX:+TraceClreplacedLoading", "-cp", appJar, "-Xbootclreplacedpath/a:" + bootAppendJar, "--limit-modules=java.base", "-Xshare:" + mode, APP_CLreplaced, BOOT_APPEND_DUPLICATE_MODULE_CLreplaced_NAME);
        Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
        output.shouldContain("[clreplaced,load] org.omg.CORBA.Context");
        output.shouldMatch(".*\\[clreplaced,load\\] org.omg.CORBA.Context source:.*bootAppend.jar");
    }
}

19 View Complete Implementation : RangeCheck.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    if (!Platform.isDebugBuild()) {
        System.out.println("Testing replacedert which requires a debug build. Preplaceding silently.");
        return;
    }
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, "-Xmx32m", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", "-XX:-TransmitErrorReport", "-XX:-CreateCoredumpOnCrash", // The compiler intrinsics doesn't have the replacedert
    "-XX:-InlineUnsafeOps", DummyClreplacedWithMainRangeCheck.clreplaced.getName());
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    output.shouldMatch("replacedert\\(byte_offset < p_size\\) failed: Unsafe access: offset \\d+ > object's size \\d+");
}

19 View Complete Implementation : VMVersionTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public void run(CommandExecutor executor) {
    Outputreplacedyzer output = executor.execute("VM.version");
    output.shouldMatch(".*(?:HotSpot|OpenJDK).*VM.*");
}

19 View Complete Implementation : ClassHistogramTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public void run(CommandExecutor executor) {
    Outputreplacedyzer output = executor.execute("GC.clreplaced_histogram " + clreplacedHistogramArgs);
    /*
         * example output:
         *  num     #instances         #bytes  clreplaced name (module)
         * -------------------------------------------------------
         *    1:          7991         757792  [B (java.base@9-internal)
         *    2:          1811         217872  java.lang.Clreplaced (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.Clreplaced */
    output.shouldMatch("^\\s+\\d+:\\s+\\d+\\s+\\d+\\s+java.lang.Clreplaced \\(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 TestClreplaced[] */
    output.shouldMatch("^\\s+\\d+:\\s+1\\s+\\d+\\s+" + Pattern.quote(TestClreplaced[].clreplaced.getName()) + "\\s*$");
    /* Require at exactly 1024 TestClreplaced */
    output.shouldMatch("^\\s+\\d+:\\s+1024\\s+\\d+\\s+" + Pattern.quote(TestClreplaced.clreplaced.getName()) + "\\s*$");
}

19 View Complete Implementation : PrintTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public void run(CommandExecutor executor) {
    MonitorThread mThread = new MonitorThread();
    mThread.start();
    LockThread lThread = new LockThread();
    lThread.start();
    /* Wait for threads to get ready */
    waitForBarrier(readyBarrier);
    /* Execute */
    Outputreplacedyzer output = executor.execute("Thread.print" + (jucLocks ? " -l=true" : ""));
    /* Signal that we've got the thread dump */
    waitForBarrier(doneBarrier);
    /*
         * Example output (trimmed) with arrows indicating the rows we are looking for:
         *
         *     ...
         *     "Thread-2" #24 prio=5 os_prio=0 tid=0x00007f913411f800 nid=0x4fc9 waiting on condition [0x00007f91fbffe000]
         *        java.lang.Thread.State: WAITING (parking)
         *       at sun.misc.Unsafe.park(Native Method)
         *       - parking to wait for  <0x000000071a0868a8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         *       at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
         *       at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
         *       at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:234)
         *       at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:362)
         *       at Print.waitForBarrier(Print.java:26)
         *       at Print.access$000(Print.java:18)
         *       at Print$LockThread.run(Print.java:58)
         *
         * -->    Locked ownable synchronizers:
         * -->    - <0x000000071a294930> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
         *
         *     "Thread-1" #23 prio=5 os_prio=0 tid=0x00007f913411e800 nid=0x4fc8 waiting on condition [0x00007f9200113000]
         *        java.lang.Thread.State: WAITING (parking)
         *       at sun.misc.Unsafe.park(Native Method)
         *       - parking to wait for  <0x000000071a0868a8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         *       at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
         *       at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
         *       at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:234)
         *       at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:362)
         *       at Print.waitForBarrier(Print.java:26)
         *       at Print.access$000(Print.java:18)
         *       at Print$MonitorThread.run(Print.java:42)
         * -->   - locked <0x000000071a294390> (a java.lang.Object)
         *
         *        Locked ownable synchronizers:
         *       - None
         *
         *     "MainThread" #22 prio=5 os_prio=0 tid=0x00007f923015b000 nid=0x4fc7 in Object.wait() [0x00007f9200840000]
         *        java.lang.Thread.State: WAITING (on object monitor)
         *       at java.lang.Object.wait(Native Method)
         *       - waiting on <0x000000071a70ad98> (a java.lang.UNIXProcess)
         *       at java.lang.Object.wait(Object.java:502)
         *        at java.lang.UNIXProcess.waitFor(UNIXProcess.java:397)
         *        - locked <0x000000071a70ad98> (a java.lang.UNIXProcess)
         *        at jdk.test.lib.dcmd.JcmdExecutor.executeImpl(JcmdExecutor.java:32)
         *       at jdk.test.lib.dcmd.CommandExecutor.execute(CommandExecutor.java:24)
         * -->   at Print.run(Print.java:74)
         *       at Print.file(Print.java:112)
         *     ...

         */
    output.shouldMatch(".*at " + Pattern.quote(PrintTest.clreplaced.getName()) + "\\.run.*");
    output.shouldMatch(".*- locked <0x\\p{XDigit}+> \\(a " + Pattern.quote(mThread.lock.getClreplaced().getName()) + "\\).*");
    String jucLockPattern1 = ".*Locked ownable synchronizers:.*";
    String jucLockPattern2 = ".*- <0x\\p{XDigit}+> \\(a " + Pattern.quote(lThread.lock.getClreplaced().getName()) + ".*";
    if (jucLocks) {
        output.shouldMatch(jucLockPattern1);
        output.shouldMatch(jucLockPattern2);
    } else {
        output.shouldNotMatch(jucLockPattern1);
        output.shouldNotMatch(jucLockPattern2);
    }
}

19 View Complete Implementation : TestBasicLogOutput.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:all=trace", "-version");
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    // expected tag(s)
    output.shouldMatch("\\[logging *\\]");
    // expected message
    output.shouldContain("Log configuration fully initialized.");
    output.shouldHaveExitValue(0);
}

19 View Complete Implementation : TestMultipleXlogArgs.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:logging=debug", "-Xlog:logging=trace", "-Xlog:defaultmethods=trace", "-Xlog:defaultmethods=off", "-Xlog:safepoint=info", "-Xlog:safepoint=info", "-version");
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    // -Xlog:logging=trace means that the log configuration will be printed.
    String stdoutConfigLine = "\\[logging *\\] #0: stdout .*";
    // Ensure logging=trace has overwritten logging=debug
    output.shouldMatch(stdoutConfigLine + "logging=trace").shouldNotMatch(stdoutConfigLine + "logging=debug");
    // Make sure safepoint=info is printed exactly once even though we're setting it twice
    output.shouldMatch(stdoutConfigLine + "safepoint=info").shouldNotMatch(stdoutConfigLine + "safepoint=info.*safepoint=info");
    // Shouldn't see defaultmethods at all, because disabled tags are not listed
    output.shouldNotMatch(stdoutConfigLine + "defaultmethods");
    output.shouldHaveExitValue(0);
}

19 View Complete Implementation : TestQuotedLogOutputs.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    // Ensure log files can be specified with full path.
    // On windows, this means that the file name will contain
    // a colon ('C:\log.txt' for example), which is used to
    // separate -Xlog: options (-Xlog:tags:filename:decorators).
    // Try to log to a file in our current directory, using its absolute path.
    String baseName = "test file.log";
    Path filePath = Paths.get(baseName).toAbsolutePath();
    String fileName = filePath.toString();
    File file = filePath.toFile();
    // In case the file already exists, attempt to delete it before running the test
    file.delete();
    // Depending on if we're on Windows or not the quotation marks must be escaped,
    // otherwise they will be stripped from the command line arguments.
    String quote;
    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        // quote should be \" (escaped quote)
        quote = "\\\"";
    } else {
        // quote should be " (no escape needed)
        quote = "\"";
    }
    // Test a few variations with valid log output specifiers
    String[] validOutputs = new String[] { quote + fileName + quote, "file=" + quote + fileName + quote, quote + fileName + quote + ":", quote + fileName + quote + "::" };
    for (String logOutput : validOutputs) {
        // Run with logging=trace on stdout so that we can verify the log configuration afterwards.
        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:logging=trace", "-Xlog:all=trace:" + logOutput, "-version");
        Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
        output.shouldHaveExitValue(0);
        replacederts.replacedertTrue(file.exists());
        // Clean up after test
        file.deleteOnExit();
        // Expect to see the log output listed
        output.shouldMatch("\\[logging *\\].*" + baseName);
    }
    // Test a bunch of invalid output specifications and ensure the VM fails with these
    String[] invalidOutputs = new String[] { quote, // should fail because the VM will try to create a file without a name
    quote + quote, quote + quote + quote, quote + quote + quote + quote, quote + quote + quote + quote + quote, "prefix" + quote + quote + "suffix", "prefix" + quote + quote, quote + quote + "suffix", quote + "A" + quote + quote + "B" + quote, quote + "A" + quote + "B" + quote + "C" + quote, "A" + quote + quote + "B" };
    for (String logOutput : invalidOutputs) {
        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:logging=trace", "-Xlog:all=trace:" + logOutput, "-version");
        Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
        output.shouldHaveExitValue(1);
        // Ensure error message was logged
        output.shouldMatch("([Mm]issing terminating quote)" + "|(Error opening log file '')" + "|(Output name can not be partially quoted)");
    }
}

19 View Complete Implementation : OutputAnalyzerReportingTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    // Create the output replacedyzer under test
    String stdout = "aaaaaa";
    String stderr = "bbbbbb";
    Outputreplacedyzer output = new Outputreplacedyzer(stdout, stderr);
    // Expected summary values should be the same for all cases,
    // since the outputreplacedyzer object is the same
    String expectedExitValue = "-1";
    String expectedSummary = " stdout: [" + stdout + "];\n" + " stderr: [" + stderr + "]\n" + " exitValue = " + expectedExitValue + "\n";
    DiagnosticSummaryTestRunner testRunner = new DiagnosticSummaryTestRunner();
    // should have exit value
    testRunner.init(expectedSummary);
    int unexpectedExitValue = 2;
    try {
        output.shouldHaveExitValue(unexpectedExitValue);
    } catch (RuntimeException e) {
    }
    testRunner.closeAndCheckResults();
    // should not contain
    testRunner.init(expectedSummary);
    try {
        output.shouldNotContain(stdout);
    } catch (RuntimeException e) {
    }
    testRunner.closeAndCheckResults();
    // should contain
    testRunner.init(expectedSummary);
    try {
        output.shouldContain("unexpected-stuff");
    } catch (RuntimeException e) {
    }
    testRunner.closeAndCheckResults();
    // should not match
    testRunner.init(expectedSummary);
    try {
        output.shouldNotMatch("[a]");
    } catch (RuntimeException e) {
    }
    testRunner.closeAndCheckResults();
    // should match
    testRunner.init(expectedSummary);
    try {
        output.shouldMatch("[qwerty]");
    } catch (RuntimeException e) {
    }
    testRunner.closeAndCheckResults();
}

19 View Complete Implementation : OutputAnalyzerTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    String stdout = "aaaaaa";
    String stderr = "bbbbbb";
    // Regexps used for testing pattern matching of the test input
    String stdoutPattern = "[a]";
    String stderrPattern = "[b]";
    String nonExistingPattern = "[c]";
    Outputreplacedyzer output = new Outputreplacedyzer(stdout, stderr);
    if (!stdout.equals(output.getStdout())) {
        throw new Exception("getStdout() returned '" + output.getStdout() + "', expected '" + stdout + "'");
    }
    if (!stderr.equals(output.getStderr())) {
        throw new Exception("getStderr() returned '" + output.getStderr() + "', expected '" + stderr + "'");
    }
    try {
        output.shouldContain(stdout);
        output.stdoutShouldContain(stdout);
        output.shouldContain(stderr);
        output.stderrShouldContain(stderr);
    } catch (RuntimeException e) {
        throw new Exception("shouldContain() failed", e);
    }
    try {
        output.shouldContain("cccc");
        throw new Exception("shouldContain() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    try {
        output.stdoutShouldContain(stderr);
        throw new Exception("stdoutShouldContain() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    try {
        output.stderrShouldContain(stdout);
        throw new Exception("stdoutShouldContain() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    try {
        output.shouldNotContain("cccc");
        output.stdoutShouldNotContain("cccc");
        output.stderrShouldNotContain("cccc");
    } catch (RuntimeException e) {
        throw new Exception("shouldNotContain() failed", e);
    }
    try {
        output.shouldNotContain(stdout);
        throw new Exception("shouldContain() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    try {
        output.stdoutShouldNotContain(stdout);
        throw new Exception("shouldContain() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    try {
        output.stderrShouldNotContain(stderr);
        throw new Exception("shouldContain() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    // Should match
    try {
        output.shouldMatch(stdoutPattern);
        output.stdoutShouldMatch(stdoutPattern);
        output.shouldMatch(stderrPattern);
        output.stderrShouldMatch(stderrPattern);
    } catch (RuntimeException e) {
        throw new Exception("shouldMatch() failed", e);
    }
    try {
        output.shouldMatch(nonExistingPattern);
        throw new Exception("shouldMatch() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    try {
        output.stdoutShouldMatch(stderrPattern);
        throw new Exception("stdoutShouldMatch() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    try {
        output.stderrShouldMatch(stdoutPattern);
        throw new Exception("stderrShouldMatch() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    // Should not match
    try {
        output.shouldNotMatch(nonExistingPattern);
        output.stdoutShouldNotMatch(nonExistingPattern);
        output.stderrShouldNotMatch(nonExistingPattern);
    } catch (RuntimeException e) {
        throw new Exception("shouldNotMatch() failed", e);
    }
    try {
        output.shouldNotMatch(stdoutPattern);
        throw new Exception("shouldNotMatch() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    try {
        output.stdoutShouldNotMatch(stdoutPattern);
        throw new Exception("shouldNotMatch() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    try {
        output.stderrShouldNotMatch(stderrPattern);
        throw new Exception("shouldNotMatch() failed to throw exception");
    } catch (RuntimeException e) {
    // expected
    }
    {
        String aaaa = "aaaa";
        String result = output.firstMatch(aaaa);
        if (!aaaa.equals(result)) {
            throw new Exception("firstMatch(String) faild to match. Expected: " + aaaa + " got: " + result);
        }
    }
    {
        String aa = "aa";
        String aa_grouped_aa = aa + "(" + aa + ")";
        String result = output.firstMatch(aa_grouped_aa, 1);
        if (!aa.equals(result)) {
            throw new Exception("firstMatch(String, int) failed to match. Expected: " + aa + " got: " + result);
        }
    }
}

19 View Complete Implementation : CommandLineOptionTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
/**
 * Verifies that JVM startup behavior matches our expectations.
 *
 * @param expectedMessages an array of patterns that should occur in JVM
 *                         output. If {@code null} then
 *                         JVM output could be empty.
 * @param unexpectedMessages an array of patterns that should not occur
 *                           in JVM output. If {@code null} then
 *                           JVM output could be empty.
 * @param wrongWarningMessage message that will be shown if messages are
 *                            not as expected.
 * @param outputreplacedyzer Outputreplacedyzer instance
 * @throws replacedertionError if verification fails.
 */
public static void verifyOutput(String[] expectedMessages, String[] unexpectedMessages, String wrongWarningMessage, Outputreplacedyzer outputreplacedyzer) {
    if (expectedMessages != null) {
        for (String expectedMessage : expectedMessages) {
            try {
                outputreplacedyzer.shouldMatch(expectedMessage);
            } catch (RuntimeException e) {
                String errorMessage = String.format("Expected message not found: '%s'.%n%s", expectedMessage, wrongWarningMessage);
                throw new replacedertionError(errorMessage, e);
            }
        }
    }
    if (unexpectedMessages != null) {
        for (String unexpectedMessage : unexpectedMessages) {
            try {
                outputreplacedyzer.shouldNotMatch(unexpectedMessage);
            } catch (RuntimeException e) {
                String errorMessage = String.format("Unexpected message found: '%s'.%n%s", unexpectedMessage, wrongWarningMessage);
                throw new replacedertionError(errorMessage, e);
            }
        }
    }
}

19 View Complete Implementation : CommandLineOptionTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
/**
 * Verifies from the output that values of specified JVM options were the same as
 * expected values.
 *
 * @param outputreplacedyzer 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(Outputreplacedyzer outputreplacedyzer, String[] optionNames, String[] expectedValues) throws Throwable {
    outputreplacedyzer.shouldHaveExitValue(0);
    for (int i = 0; i < optionNames.length; i++) {
        outputreplacedyzer.shouldMatch(String.format(CommandLineOptionTest.PRINT_FLAGS_FINAL_FORMAT, optionNames[i], expectedValues[i]));
    }
}

19 View Complete Implementation : CommandLineOptionTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
/**
 * 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 outputreplacedyzer Outputreplacedyzer instance
 * @throws replacedertionError if verification fails
 */
public static void verifyOptionValue(String optionName, String expectedValue, String optionErrorString, Outputreplacedyzer outputreplacedyzer) {
    try {
        outputreplacedyzer.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 replacedertionError(errorMessage, e);
    }
}

19 View Complete Implementation : TestGCLogMessages.java
Copyright GNU General Public License v2.0
Author : hzio
void checkMessagesAtLevel(Outputreplacedyzer output, LogMessageWithLevel[] messages, Level level) throws Exception {
    for (LogMessageWithLevel l : messages) {
        if (level.lessThan(l.level) || !l.isAvailable()) {
            output.shouldNotContain(l.message);
        } else {
            output.shouldMatch("\\[" + l.level + ".*" + l.message);
        }
    }
}

19 View Complete Implementation : TestPrintReferences.java
Copyright GNU General Public License v2.0
Author : hzio
public static void main(String[] args) throws Exception {
    ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder("-Xlog:gc+phases+ref=debug", "-XX:+UseG1GC", "-Xmx10M", // Explicit thread setting is required to avoid using only 1 thread
    "-XX:ParallelGCThreads=2", GCTest.clreplaced.getName());
    Outputreplacedyzer output = new Outputreplacedyzer(pb_enabled.start());
    String indent_4 = "    ";
    String indent_6 = "      ";
    String indent_8 = "        ";
    String gcLogTimeRegex = ".* GC\\([0-9]+\\) ";
    String countRegex = "[0-9]+";
    String timeRegex = "[0-9]+[.,][0-9]+ms";
    String totalRegex = gcLogTimeRegex + indent_4 + "Reference Processing: " + timeRegex + "\n";
    String balanceRegex = gcLogTimeRegex + indent_8 + "Balance queues: " + timeRegex + "\n";
    String softRefRegex = gcLogTimeRegex + indent_6 + "SoftReference: " + timeRegex + "\n";
    String weakRefRegex = gcLogTimeRegex + indent_6 + "WeakReference: " + timeRegex + "\n";
    String finalRefRegex = gcLogTimeRegex + indent_6 + "FinalReference: " + timeRegex + "\n";
    String phantomRefRegex = gcLogTimeRegex + indent_6 + "PhantomReference: " + timeRegex + "\n";
    String refDetailRegex = gcLogTimeRegex + indent_8 + "Phase2: " + timeRegex + "\n" + gcLogTimeRegex + indent_8 + "Phase3: " + timeRegex + "\n" + gcLogTimeRegex + indent_8 + "Discovered: " + countRegex + "\n" + gcLogTimeRegex + indent_8 + "Cleared: " + countRegex + "\n";
    String softRefDetailRegex = gcLogTimeRegex + indent_8 + "Phase1: " + timeRegex + "\n" + refDetailRegex;
    String enqueueRegex = gcLogTimeRegex + indent_4 + "Reference Enqueuing: " + timeRegex + "\n";
    String enqueueDetailRegex = gcLogTimeRegex + indent_6 + "Reference Counts:  Soft: " + countRegex + "  Weak: " + countRegex + "  Final: " + countRegex + "  Phantom: " + countRegex + "\n";
    output.shouldMatch(/* Total Reference processing time */
    totalRegex + /* SoftReference processing */
    softRefRegex + balanceRegex + softRefDetailRegex + /* WeakReference processing */
    weakRefRegex + balanceRegex + refDetailRegex + /* FinalReference processing */
    finalRefRegex + balanceRegex + refDetailRegex + /* PhantomReference processing */
    phantomRefRegex + balanceRegex + refDetailRegex + /* Total Enqueuing time */
    enqueueRegex + /* Enqueued Stats */
    enqueueDetailRegex);
    output.shouldHaveExitValue(0);
}

19 View Complete Implementation : TimeoutInErrorHandlingTest.java
Copyright GNU General Public License v2.0
Author : hzio
public static void main(String[] args) throws Exception {
    /* Start the VM and let it crash. Specify TestUnresponsiveErrorHandler which will
         * let five subsequent error reporting steps hang. The Timeout handling triggered
         * by the WatcherThread should kick in and interrupt those steps. In theory, the
         * text "timeout occurred during error reporting in step .." (the little timeouts)
         * should occur in the error log up to four times, followed by the final big timeout
         * "------ Timeout during error reporting after xx s. ------"
         *
         * Note that there are a number of uncertainties which make writing a 100% foolproof
         * test challenging. The time the error reporting thread takes to react to the
         * timeout triggers is unknown. So it is difficult to predict how many little timeouts
         * will be visible before the big timeout kicks in. Also, once the big timeout hits,
         * error reporting thread and Watcherthread will race. The former writes his last
         * message to the error logs and flushes, the latter waits 200ms and then exits the
         * process without further synchronization with the error reporting thread.
         *
         * Because of all this and the desire to write a bullet proof test which does
         * not fail sporadically, we will not test for the final timeout message nor for all
         * of the optimally expected little timeout messages. We just test for two of the
         * little timeout messages to see that repeated timeout handling is basically working.
         */
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-Xmx100M", "-XX:ErrorHandlerTest=14", "-XX:+TestUnresponsiveErrorHandler", // 16 seconds big timeout = 4 seconds per little timeout
    "-XX:ErrorLogTimeout=16", "-XX:-CreateCoredumpOnCrash", "-version");
    Outputreplacedyzer output_detail = new Outputreplacedyzer(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).*");
    // VM should have been aborted by WatcherThread
    output_detail.shouldMatch(".*timer expired, abort.*");
    // 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(".*timeout occurred during error reporting in step.*"), Pattern.compile(".*timeout occurred during error reporting in step.*") };
    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 + ")");
    }
    System.out.println("OK.");
}

19 View Complete Implementation : StartupTimeTest.java
Copyright GNU General Public License v2.0
Author : hzio
static void replacedyzeOutputOn(ProcessBuilder pb) throws Exception {
    Outputreplacedyzer output = new Outputreplacedyzer(pb.start());
    output.shouldMatch("(Genesis, [0-9]+.[0-9]+ secs)");
    output.shouldMatch("(Start VMThread, [0-9]+.[0-9]+ secs)");
    output.shouldMatch("(Initialize module system, [0-9]+.[0-9]+ secs)");
    output.shouldMatch("(Create VM, [0-9]+.[0-9]+ secs)");
    output.shouldHaveExitValue(0);
}

19 View Complete Implementation : ArchiveDoesNotExist.java
Copyright GNU General Public License v2.0
Author : hzio
public static void main(String[] args) throws Exception {
    String fileName = "ArchiveDoesNotExist.jsa";
    File cdsFile = new File(fileName);
    if (cdsFile.exists())
        throw new RuntimeException("Test error: cds file already exists");
    CDSOptions opts = (new CDSOptions()).setArchiveName(fileName);
    // -Xshare=on
    Outputreplacedyzer out = CDSTestUtils.runWithArchive(opts);
    if (!CDSTestUtils.isUnableToMap(out)) {
        out.shouldContain("Specified shared archive not found").shouldHaveExitValue(1);
    }
    // -Xshare=auto
    opts.setXShareMode("auto");
    out = CDSTestUtils.runWithArchive(opts);
    if (!CDSTestUtils.isUnableToMap(out)) {
        out.shouldMatch("(java|openjdk) version").shouldNotContain("sharing").shouldHaveExitValue(0);
    }
}

19 View Complete Implementation : BootAppendTests.java
Copyright GNU General Public License v2.0
Author : hzio
// Test #4: If a clreplaced on -Xbootclreplacedpath/a has the same fully qualified
// name as a clreplaced defined in boot modules, the clreplaced is loaded
// from -Xbootclreplacedpath/a when the boot module is excluded using
// --limit-modules. Verify the behavior is the same at runtime
// when CDS is enabled.
// 
// The org.omg.CORBA.Context is a boot module clreplaced. The clreplaced
// on -Xbootclreplacedpath/a that has the same fully-qualified name
// as org.omg.CORBA.Context can be loaded at runtime when
// java.corba is excluded.
public static void testBootAppendDuplicateExcludedModuleClreplaced() throws Exception {
    for (String mode : modes) {
        CDSOptions opts = (new CDSOptions()).setXShareMode(mode).setUseVersion(false).addPrefix("-Xbootclreplacedpath/a:" + bootAppendJar, "-showversion", "--limit-modules=java.base", "-cp", appJar).addSuffix("-Xlog:clreplaced+load=info", APP_CLreplaced, BOOT_APPEND_DUPLICATE_MODULE_CLreplaced_NAME);
        Outputreplacedyzer out = CDSTestUtils.runWithArchive(opts);
        CDSTestUtils.checkExec(out, opts, "[clreplaced,load] org.omg.CORBA.Context");
        if (!CDSTestUtils.isUnableToMap(out)) {
            if (mode.equals("off")) {
                out.shouldMatch(".*\\[clreplaced,load\\] org.omg.CORBA.Context source:.*bootAppend.jar");
            } else {
                CDSTestUtils.checkExec(out, opts, "[clreplaced,load] org.omg.CORBA.Context source: shared objects file");
            }
        }
    }
}

19 View Complete Implementation : CdsDifferentCompactStrings.java
Copyright GNU General Public License v2.0
Author : hzio
private static void createAndLoadSharedArchive(String create, String load) throws Exception {
    String createCompactStringsArgument = "-XX:" + create + "CompactStrings";
    String loadCompactStringsArgument = "-XX:" + load + "CompactStrings";
    Outputreplacedyzer out = CDSTestUtils.createArchive(createCompactStringsArgument);
    CDSTestUtils.checkDump(out);
    out = CDSTestUtils.runWithArchive(loadCompactStringsArgument);
    if (!CDSTestUtils.isUnableToMap(out)) {
        out.shouldMatch("The shared archive file's CompactStrings " + "setting .* does not equal the current CompactStrings setting").shouldHaveExitValue(1);
    }
}

18 View Complete Implementation : SecondaryErrorTest.java
Copyright GNU General Public License v2.0
Author : AdoptOpenJDK
public static void main(String[] args) throws Exception {
    // Do not execute for windows, nor for non-debug builds
    if (Platform.isWindows()) {
        return;
    }
    if (!Platform.isDebugBuild()) {
        return;
    }
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-Xmx100M", "-XX:-CreateCoredumpOnCrash", "-XX:ErrorHandlerTest=15", "-XX:TestCrashInErrorHandler=14", "-version");
    Outputreplacedyzer output_detail = new Outputreplacedyzer(pb.start());
    // we should have crashed with a SIGFPE
    output_detail.shouldMatch("# A fatal error has been detected by the Java Runtime Environment:.*");
    output_detail.shouldMatch("# +SIGFPE.*");
    // 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");
    }
    // scan hs-err file: File should contain the "[error occurred during error reporting..]"
    // markers which show that the secondary error handling kicked in and handled the
    // error successfully. As an added test, we check that the last line contains "END.",
    // which is an end marker written in the last step and proves that hs-err file was
    // completely written.
    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 crash now \\(TestCrashInErrorHandler=14\\)..."), Pattern.compile("\\[error occurred during error reporting \\(test secondary crash 1\\).*\\]"), Pattern.compile("Will crash now \\(TestCrashInErrorHandler=14\\)..."), Pattern.compile("\\[error occurred during error reporting \\(test secondary crash 2\\).*\\]") };
    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.");
}

18 View Complete Implementation : JhsdbThreadInfoTest.java
Copyright GNU General Public License v2.0
Author : hzio
public static void main(String[] args) throws Exception {
    if (!Platform.shouldSAAttach()) {
        System.out.println("SA attach not expected to work - test skipped.");
        return;
    }
    LingeredApp app = null;
    try {
        app = LingeredApp.startApp(Utils.getVmOptions());
        System.out.println("Started LingeredApp with pid " + app.getPid());
        JDKToolLauncher jhsdbLauncher = JDKToolLauncher.createUsingTestJDK("jhsdb");
        jhsdbLauncher.addToolArg("jstack");
        jhsdbLauncher.addToolArg("--pid");
        jhsdbLauncher.addToolArg(Long.toString(app.getPid()));
        ProcessBuilder pb = new ProcessBuilder();
        pb.command(jhsdbLauncher.getCommand());
        Process jhsdb = pb.start();
        jhsdb.waitFor();
        Outputreplacedyzer out = new Outputreplacedyzer(jhsdb);
        System.out.println(out.getStdout());
        System.err.println(out.getStderr());
        out.shouldMatch("\".+\" #\\d+ daemon prio=\\d+ tid=0x[0-9a-f]+ nid=0x[0-9a-f]+ .+ \\[0x[0-9a-f]+]");
        out.shouldMatch("\"main\" #\\d+ prio=\\d+ tid=0x[0-9a-f]+ nid=0x[0-9a-f]+ .+ \\[0x[0-9a-f]+]");
        out.shouldMatch("   java.lang.Thread.State: .+");
        out.shouldMatch("   JavaThread state: _thread_.+");
        out.shouldNotContain("   java.lang.Thread.State: UNKNOWN");
        out.stderrShouldBeEmpty();
        System.out.println("Test Completed");
    } catch (InterruptedException ie) {
        throw new Error("Problem awaiting the child process: " + ie, ie);
    } catch (Exception attachE) {
        throw new Error("Couldn't start jhsdb, attach to LingeredApp or match ThreadName: " + attachE);
    } finally {
        LingeredApp.stopApp(app);
    }
}