jdk.test.lib.Asserts Java Examples

The following examples show how to use jdk.test.lib.Asserts. 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: ResolvePossiblyCachedConstantInPoolTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void validateString(ConstantPool constantPoolCTVM,
                                   ConstantTypes cpType,
                                   DummyClasses dummyClass,
                                   int cpi) {
    TestedCPEntry entry = cpType.getTestedCPEntry(dummyClass, cpi);
    if (entry == null) {
        return;
    }
    int index = cpi;
    String cached = "";
    int cpci = dummyClass.getCPCacheIndex(cpi);
    if (cpci != ConstantPoolTestsHelper.NO_CP_CACHE_PRESENT) {
        index = cpci;
        cached = "cached ";
    }
    Object constantInPool = CompilerToVMHelper.resolvePossiblyCachedConstantInPool(constantPoolCTVM, index);
    String stringToVerify = (String) constantInPool;
    String stringToRefer = entry.name;
    if (stringToRefer.equals("") && cpci != ConstantPoolTestsHelper.NO_CP_CACHE_PRESENT) {
        stringToRefer = null; // tested method returns null for cached empty strings
    }
    String msg = String.format("Wrong string accessed by %sconstant pool index %d", cached, index);
    Asserts.assertEQ(stringToRefer, stringToVerify, msg);
}
 
Example #2
Source File: TestGetLabel.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 {
    EventType type = EventType.getEventType(CustomEvent.class);

    SettingDescriptor plain = Events.getSetting(type, "plain");
    Asserts.assertNull(plain.getLabel());

    SettingDescriptor annotatedType = Events.getSetting(type, "annotatedType");
    Asserts.assertEquals(AnnotatedSetting.LABEL, annotatedType.getLabel());

    SettingDescriptor newName = Events.getSetting(type, "newName");
    Asserts.assertEquals(newName.getLabel(), "Annotated Method");

    SettingDescriptor overridden = Events.getSetting(type, "overridden");
    Asserts.assertNull(overridden.getLabel());

    SettingDescriptor protectedBase = Events.getSetting(type, "protectedBase");
    Asserts.assertEquals(protectedBase.getLabel(), "Protected Base");

    SettingDescriptor publicBase = Events.getSetting(type, "publicBase");
    Asserts.assertEquals(publicBase.getLabel(), AnnotatedSetting.LABEL);

    SettingDescriptor packageProtectedBase = Events.getSetting(type, "packageProtectedBase");
    Asserts.assertNull(packageProtectedBase.getLabel());

    CustomEvent.assertOnDisk((x, y) -> Objects.equals(x.getLabel(), y.getLabel()) ? 0 : 1);
}
 
Example #3
Source File: JcmdHelper.java    From TencentKona-8 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: TestExperimental.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 {
    EventType t = EventType.getEventType(ExperimentalEvent.class);

    // @Experimental on event
    Experimental e = t.getAnnotation(Experimental.class);
    Asserts.assertTrue(e != null, "Expected @Experimental annotation on event");

    // @Experimental on annotation
    AnnotationElement a = Events.getAnnotationByName(t, ExperimentalAnnotation.class.getName());
    e = a.getAnnotation(Experimental.class);
    Asserts.assertTrue(e != null, "Expected @Experimental on annotation");

    // @Experimental on field
    a = Events.getAnnotation(t.getField("experimentalField"), Experimental.class);
    Asserts.assertTrue(e != null, "Expected @Experimental on field");
}
 
Example #5
Source File: TestDumpLongPath.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 r = new Recording();
    final String eventPath = EventNames.OSInformation;
    r.enable(eventPath);
    r.start();
    r.stop();

    Path dir = FileHelper.createLongDir(Paths.get("."));
    Path path = Paths.get(dir.toString(), "my.jfr");
    r.dump(path);
    r.close();

    Asserts.assertTrue(Files.exists(path), "Recording file does not exist: " + path);
    List<RecordedEvent> events = RecordingFile.readAllEvents(path);
    Asserts.assertFalse(events.isEmpty(), "No events found");
    String foundEventPath = events.get(0).getEventType().getName();
    System.out.printf("Found event: %s%n", foundEventPath);
    Asserts.assertEquals(foundEventPath, eventPath, "Wrong event");
}
 
Example #6
Source File: TestEnoughPermission.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static long testRecording(FlightRecorderMXBean bean) throws Exception {
    System.out.println("A");
    long recId = bean.newRecording();
    System.out.println("B");
    bean.setPredefinedConfiguration(recId, "profile");
    System.out.println("C");
    bean.startRecording(recId);
    System.out.println("D");
    Asserts.assertTrue(bean.getRecordings().stream().anyMatch(r -> { return r.getId() == recId; }), "recId not found");
    System.out.println("E");
    bean.stopRecording(recId);

    final Path path = Paths.get(".", "rec" + recId + ".jfr");
    bean.copyTo(recId, path.toString());
    //EventSet events = EventSet.fromFile(path);
    return recId;
}
 
Example #7
Source File: TestConstructor.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    ValueDescriptor vdSimple = new ValueDescriptor(String.class, "message");
    Asserts.assertNull(vdSimple.getAnnotation(Label.class), "Expected getAnnotation()==null");
    Asserts.assertEquals(0, vdSimple.getAnnotationElements().size(), "Expected getAnnotations().size() == 0");

    // Add labelA and verify we can read it back
    List<AnnotationElement> annos = new ArrayList<>();
    AnnotationElement labelA = new AnnotationElement(Label.class, "labelA");
    annos.add(labelA);
    System.out.println("labelA.getClass()" + labelA.getClass());
    ValueDescriptor vdComplex = new ValueDescriptor(String.class, "message", annos);

    final Label outLabel = vdComplex.getAnnotation(Label.class);
    Asserts.assertFalse(outLabel == null, "getLabel(Label.class) was null");
    System.out.println("outLabel.value() = " + outLabel.value());

    // Get labelA from getAnnotations() list
    Asserts.assertEquals(1, vdComplex.getAnnotationElements().size(), "Expected getAnnotations().size() == 1");
    final AnnotationElement outAnnotation = vdComplex.getAnnotationElements().get(0);
    Asserts.assertNotNull(outAnnotation, "outAnnotation was null");
    System.out.printf("Annotation: %s = %s%n", outAnnotation.getTypeName(), outAnnotation.getValue("value"));
    Asserts.assertEquals(outAnnotation, labelA, "Expected firstAnnotation == labelA");

}
 
Example #8
Source File: GCEventAll.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void verifyPhaseEvents(List<GCHelper.GcBatch> batches) {
    for (GCHelper.GcBatch batch : batches) {
        for(RecordedEvent event : batch.getEvents()) {
            if (event.getEventType().getName().contains(GCHelper.pauseLevelEvent)) {
                Instant batchStartTime = batch.getEndEvent().getStartTime();
                Asserts.assertGreaterThanOrEqual(
                    event.getStartTime(), batchStartTime, "Phase startTime >= batch startTime. Event:" + event);

                // Duration for event "vm/gc/phases/pause" must be >= 1. Other phase event durations must be >= 0.
                Duration minDuration = Duration.ofNanos(GCHelper.event_phases_pause.equals(event.getEventType().getName()) ? 1 : 0);
                Duration duration = event.getDuration();
                Asserts.assertGreaterThanOrEqual(duration, minDuration, "Wrong duration. Event:" + event);
            }
        }
    }
}
 
Example #9
Source File: TestLabel.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 {
    // Event
    EventType t = EventType.getEventType(LabelEvent.class);
    Asserts.assertEquals(t.getLabel(), "Event Label", "Incorrect label for event");

    // Field
    ValueDescriptor field = t.getField("labledField");
    Asserts.assertEquals(field.getLabel(), "Field Label", "Incorrect label for field");

    // Annotation
    AnnotationElement awl = Events.getAnnotationByName(t, AnnotionWithLabel.class.getName());
    Label label = awl.getAnnotation(Label.class);
    Asserts.assertEquals(label.value(), "Annotation Label", "Incorrect label for annotation");

    // Setting
    for (SettingDescriptor v: t.getSettingDescriptors()) {
        if (v.getName().equals("dummy")) {
            Label settingLabel = v.getAnnotation(Label.class);
            Asserts.assertEquals(settingLabel.value(), "Setting Label", "Incorrect label for setting");
        }
    }
}
 
Example #10
Source File: TestGetDescription.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 {
    EventType type = EventType.getEventType(CustomEvent.class);

    SettingDescriptor plain = Events.getSetting(type, "plain");
    Asserts.assertNull(plain.getDescription());

    SettingDescriptor annotatedType = Events.getSetting(type, "annotatedType");
    Asserts.assertEquals(annotatedType.getDescription(), AnnotatedSetting.DESCRIPTION);

    SettingDescriptor newName = Events.getSetting(type, "newName");
    Asserts.assertEquals(newName.getDescription(), CustomEvent.DESCRIPTION_OF_AN_ANNOTATED_METHOD);

    SettingDescriptor overridden = Events.getSetting(type, "overridden");
    Asserts.assertNull(overridden.getDescription());

    SettingDescriptor protectedBase = Events.getSetting(type, "protectedBase");
    Asserts.assertEquals(protectedBase.getDescription(), "Description of protected base");

    SettingDescriptor publicBase = Events.getSetting(type, "publicBase");
    Asserts.assertEquals(publicBase.getDescription(), AnnotatedSetting.DESCRIPTION);

    SettingDescriptor packageProtectedBase = Events.getSetting(type, "packageProtectedBase");
    Asserts.assertNull(packageProtectedBase.getDescription());

    CustomEvent.assertOnDisk((x, y) -> Objects.equals(x.getDescription(), y.getDescription()) ? 0 : 1);
}
 
Example #11
Source File: TestGetId.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Map<Long, Recording> recordings = new HashMap<>();

    final int iterations = 100;
    for (int i = 0; i < iterations; ++i) {
        Recording newRecording = new Recording();
        System.out.println("created: " + newRecording.getId());
        Recording oldRecording = recordings.get(newRecording.getId());
        Asserts.assertNull(oldRecording, "Duplicate recording ID: " + newRecording.getId());
        recordings.put(newRecording.getId(), newRecording);

        if (i % 3 == 0) {
            Recording closeRecording = recordings.remove(recordings.keySet().iterator().next());
            Asserts.assertNotNull(closeRecording, "Could not find recording in map. Test error.");
            closeRecording.close();
            System.out.println("closed: " + closeRecording.getId());
        }
    }

    for (Recording r : recordings.values()) {
        r.close();
    }
}
 
Example #12
Source File: RefStatEvent.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void verifyRefStatEvents(List<RecordedEvent> events, int gcId) {
    List<String> expectedTypes = Arrays.asList("Soft reference", "Weak reference", "Final reference", "Phantom reference");
    List<String> actualTypes = new ArrayList<>();
    try {
        for (RecordedEvent event : events) {
            if (!Events.isEventType(event, refStatsEventPath)) {
                continue;
            }
            Events.assertField(event, "count").atLeast(0L);
            if (Events.assertField(event, "gcId").isEqual(gcId)) {
                actualTypes.add(Events.assertField(event, "type").notEmpty().getValue());
            }
        }

        Asserts.assertEquals(actualTypes.size(), expectedTypes.size(), "Wrong number of refStat events");
        Asserts.assertTrue(expectedTypes.containsAll(actualTypes), "Found unknown refStat types");
        Asserts.assertTrue(actualTypes.containsAll(expectedTypes), "Missning refStat types");
    } catch (Exception e) {
        System.out.println("Expected refStatTypes: " + expectedTypes.stream().collect(Collectors.joining(", ")));
        System.out.println("Got refStatTypes: " + actualTypes.stream().collect(Collectors.joining(", ")));
        throw e;
    }
}
 
Example #13
Source File: TestRecordedEventGetThread.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Thread currentThread = Thread.currentThread();
    currentThread.setName(MY_THREAD_NAME);
    long expectedThreadId = currentThread.getId();

    Recording r = new Recording();
    r.start();
    SimpleEvent t = new SimpleEvent();
    t.commit();
    r.stop();
    List<RecordedEvent> events = Events.fromRecording(r);
    r.close();
    Events.hasEvents(events);
    RecordedEvent event = events.get(0);
    RecordedThread recordedThread = event.getThread();

    Asserts.assertNotNull(recordedThread);
    Asserts.assertEquals(recordedThread.getJavaName(), MY_THREAD_NAME);
    Asserts.assertEquals(recordedThread.getJavaThreadId(), expectedThreadId);
    Asserts.assertNotNull(recordedThread.getOSThreadId());
    Asserts.assertNotNull(recordedThread.getId());
    Asserts.assertEquals(recordedThread.getOSName(), MY_THREAD_NAME);
}
 
Example #14
Source File: TestCMSConcurrentModeFailureEvent.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 {
    String[] vmFlags = {"-Xmx128m", "-XX:MaxTenuringThreshold=0", "-Xloggc:testCMSGC.log", "-verbose:gc",
        "-XX:+UseConcMarkSweepGC", "-XX:+UnlockExperimentalVMOptions", "-XX:-UseFastUnorderedTimeStamps"};

    if (!ExecuteOOMApp.execute(EVENT_SETTINGS_FILE, JFR_FILE, vmFlags, BYTES_TO_ALLOCATE)) {
        System.out.println("OOM happened in the other thread(not test thread). Skip test.");
        // Skip test, process terminates due to the OOME error in the different thread
        return;
    }

    Optional<RecordedEvent> event = RecordingFile.readAllEvents(Paths.get(JFR_FILE)).stream().findFirst();
    if (event.isPresent()) {
        Asserts.assertEquals(EVENT_NAME, event.get().getEventType().getName(), "Wrong event type");
    } else {
        // No event received. Check if test did trigger the event.
        boolean isEventTriggered = fileContainsString("testCMSGC.log", "concurrent mode failure");
        System.out.println("isEventTriggered=" +isEventTriggered);
        Asserts.assertFalse(isEventTriggered, "Event found in log, but not in JFR");
    }
}
 
Example #15
Source File: TestExceptionEvents.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void checkThrowableEvents(List<RecordedEvent> events, String eventName,
    int excpectedEvents, Class<?> expectedClass, String expectedMessage) throws Exception {
    int count = 0;
    for(RecordedEvent event : events) {
        if (Events.isEventType(event, eventName)) {
            String message = Events.assertField(event, "message").getValue();
            if (expectedMessage.equals(message)) {
                RecordedThread t = event.getThread();
                String threadName = t.getJavaName();
                if (threadName != null && threadName.equals(Thread.currentThread().getName())) {
                    RecordedClass jc = event.getValue("thrownClass");
                    if (jc.getName().equals(expectedClass.getName())) {
                        count++;
                    }
                }
            }
        }
    }
    Asserts.assertEquals(count, excpectedEvents, "Wrong event count for type " + eventName);
}
 
Example #16
Source File: TestEventMetadata.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void verifyEventType(EventType eventType) {
    System.out.println("Verifying event: " + eventType.getName());
    verifyDescription(eventType.getDescription());
    verifyLabel(eventType.getLabel());
    Asserts.assertNotEquals(eventType.getName(), null, "Name not allowed to be null");
    Asserts.assertTrue(eventType.getName().startsWith(EventNames.PREFIX), "OpenJDK events must start with " + EventNames.PREFIX);
    String name = eventType.getName().substring(EventNames.PREFIX.length());
    Asserts.assertFalse(isReservedKeyword(name),"Name must not be reserved keyword in the Java language (" + name + ")");
    checkCommonAbbreviations(name);
      char firstChar = name.charAt(0);
    Asserts.assertFalse(name.contains("ID"), "'ID' should not be used in name, consider using 'Id'");
    Asserts.assertTrue(Character.isAlphabetic(firstChar), "Name " + name + " must start with a character");
    Asserts.assertTrue(Character.isUpperCase(firstChar), "Name " + name + " must start with upper case letter");
    for (int i = 0; i < name.length(); i++) {
        char c = name.charAt(i);
        Asserts.assertTrue(Character.isAlphabetic(c) || Character.isDigit(c), "Name " + name + " must consists of characters or numbers, found '" + name.charAt(i) + "'");
    }
}
 
Example #17
Source File: TestSmallHeap.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void verifySmallHeapSize(String gc, long expectedMaxHeap) throws Exception {
    long minMaxHeap = 4 * 1024 * 1024;
    LinkedList<String> vmOptions = new LinkedList<>();
    vmOptions.add(gc);
    vmOptions.add("-Xmx" + minMaxHeap);
    vmOptions.add("-XX:+PrintFlagsFinal");
    vmOptions.add(VerifyHeapSize.class.getName());

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(vmOptions.toArray(new String[0]));
    OutputAnalyzer analyzer = new OutputAnalyzer(pb.start());
    analyzer.shouldHaveExitValue(0);

    expectedMaxHeap = Math.max(expectedMaxHeap, minMaxHeap);
    long maxHeapSize = Long.parseLong(analyzer.firstMatch("MaxHeapSize.+=\\s+(\\d+)",1));
    long actualHeapSize = Long.parseLong(analyzer.firstMatch(VerifyHeapSize.actualMsg + "(\\d+)",1));
    Asserts.assertEQ(maxHeapSize, expectedMaxHeap);
    Asserts.assertLessThanOrEqual(actualHeapSize, maxHeapSize);
}
 
Example #18
Source File: TestRandomAccessFileThread.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void verifyTimes(List<RecordedEvent> events) {
    RecordedEvent prev = null;
    for (RecordedEvent curr : events) {
        if (prev != null) {
            try {
                Asserts.assertGreaterThanOrEqual(curr.getStartTime(), prev.getStartTime(), "Wrong startTime");
                Asserts.assertGreaterThanOrEqual(curr.getEndTime(), prev.getEndTime(), "Wrong endTime");
                long commitPrev = Events.assertField(prev, "startTime").getValue();
                long commitCurr = Events.assertField(curr, "startTime").getValue();
                Asserts.assertGreaterThanOrEqual(commitCurr, commitPrev, "Wrong commitTime");
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
                System.out.println("Prev Event: " + prev);
                System.out.println("Curr Event: " + curr);
                throw e;
            }
        }
        prev = curr;
    }
}
 
Example #19
Source File: TestFieldInformation.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 {
    WhiteBox.setWriteAllObjectSamples(true);

    try (Recording recording = new Recording()) {
        recording.enable(EventNames.OldObjectSample).withoutStackTrace().with("cutoff", "infinity");
        recording.start();

        addToTestField();

        recording.stop();

        List<RecordedEvent> events = Events.fromRecording(recording);
        Events.hasEvents(events);
        for (RecordedEvent e : events) {
            if (hasValidField(e)) {
                return;
            }
        }
        System.out.println(events);
        Asserts.fail("Could not find old object with field 'testField'");
    }
}
 
Example #20
Source File: TestEvacuationFailedEvent.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 {
    String[] vmFlags = {"-XX:+UnlockExperimentalVMOptions", "-XX:-UseFastUnorderedTimeStamps",
        "-Xmx64m", "-Xmn60m", "-XX:-UseDynamicNumberOfGCThreads", "-XX:ParallelGCThreads=3",
        "-XX:MaxTenuringThreshold=0", "-verbose:gc", "-XX:+UseG1GC"};

    if (!ExecuteOOMApp.execute(EVENT_SETTINGS_FILE, JFR_FILE, vmFlags, BYTES_TO_ALLOCATE)) {
        System.out.println("OOM happened in the other thread(not test thread). Skip test.");
        // Skip test, process terminates due to the OOME error in the different thread
        return;
    }

    List<RecordedEvent> events = RecordingFile.readAllEvents(Paths.get(JFR_FILE));

    Events.hasEvents(events);
    for (RecordedEvent event : events) {
        long objectCount = Events.assertField(event, "evacuationFailed.objectCount").atLeast(1L).getValue();
        long smallestSize = Events.assertField(event, "evacuationFailed.smallestSize").atLeast(1L).getValue();
        long firstSize = Events.assertField(event, "evacuationFailed.firstSize").atLeast(smallestSize).getValue();
        long totalSize = Events.assertField(event, "evacuationFailed.totalSize").atLeast(firstSize).getValue();
        Asserts.assertLessThanOrEqual(smallestSize * objectCount, totalSize, "smallestSize * objectCount <= totalSize");
    }
}
 
Example #21
Source File: TestGetStackTrace.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void assertFrame(RecordedFrame frame) {
    int bci = frame.getBytecodeIndex();
    int line = frame.getLineNumber();
    boolean javaFrame = frame.isJavaFrame();
    RecordedMethod method = frame.getMethod();
    String type = frame.getType();
    System.out.println("*** Frame Info ***");
    System.out.println("bci=" + bci);
    System.out.println("line=" + line);
    System.out.println("type=" + type);
    System.out.println("method=" + method);
    System.out.println("***");
    Asserts.assertTrue(javaFrame, "Only Java frame are currently supported");
    Asserts.assertGreaterThanOrEqual(bci, -1);
    Asserts.assertNotNull(method, "Method should not be null");
}
 
Example #22
Source File: TestEventTypes.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void assertSame(List<EventTypeInfo> infos, List<EventType> types) {
    List<Long> ids = new ArrayList<>();
    for (EventTypeInfo info : infos) {
        long id = info.getId();
        Asserts.assertFalse(ids.contains(id), "EventTypeInfo.id not unique:" + id);
        ids.add(id);
        boolean isFound = false;
        for (EventType type : types) {
            if (type.getId() == id) {
                assertSame(info, type);
                isFound = true;
                break;
            }
        }
        if (!isFound) {
            String msg = "No EventType for EventTypeInfo";
            System.out.println(msg + ": " + info);
            Asserts.fail(msg);
        }
    }
    Asserts.assertEquals(infos.size(), types.size(), "Number of EventTypeInfos != EventTypes");
}
 
Example #23
Source File: TestGetStackTrace.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void assertFrame(RecordedFrame frame) {
    int bci = frame.getBytecodeIndex();
    int line = frame.getLineNumber();
    boolean javaFrame = frame.isJavaFrame();
    RecordedMethod method = frame.getMethod();
    String type = frame.getType();
    System.out.println("*** Frame Info ***");
    System.out.println("bci=" + bci);
    System.out.println("line=" + line);
    System.out.println("type=" + type);
    System.out.println("method=" + method);
    System.out.println("***");
    Asserts.assertTrue(javaFrame, "Only Java frame are currently supported");
    Asserts.assertGreaterThanOrEqual(bci, -1);
    Asserts.assertNotNull(method, "Method should not be null");
}
 
Example #24
Source File: TestDefaultValue.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 {
    EventType type = EventType.getEventType(CustomEvent.class);

    SettingDescriptor plain = Events.getSetting(type, "plain");
    Asserts.assertEquals(plain.getDefaultValue(), "plain");

    SettingDescriptor annotatedType = Events.getSetting(type, "annotatedType");
    Asserts.assertEquals(annotatedType.getDefaultValue(), AnnotatedSetting.DEFAULT_VALUE);

    SettingDescriptor newName = Events.getSetting(type, "newName");
    Asserts.assertEquals(newName.getDefaultValue(), AnnotatedSetting.DEFAULT_VALUE);

    SettingDescriptor overridden = Events.getSetting(type, "overridden");
    Asserts.assertEquals(overridden.getDefaultValue(), PlainSetting.DEFAULT_VALUE);

    CustomEvent.assertOnDisk((x, y) -> x.getName().compareTo(y.getName()));
}
 
Example #25
Source File: TestGetDuration.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void verifyNativeEvents() throws Exception {
    Recording r = new Recording();
    r.enable(EventNames.JVMInformation);
    r.enable(EventNames.ThreadSleep);
    r.start();
    // Should trigger a sleep event even if we
    // have a low resolution clock
    Thread.sleep(200);
    r.stop();
    List<RecordedEvent> recordedEvents = Events.fromRecording(r);
    Events.hasEvents(recordedEvents);
    for (RecordedEvent re : recordedEvents) {
        Asserts.assertEquals(re.getDuration(), Duration.between(re.getStartTime(), re.getEndTime()));
        switch (re.getEventType().getName()) {
            case EventNames.JVMInformation:
                Asserts.assertTrue(re.getDuration().isZero());
                break;
            case EventNames.ThreadSleep:
                Asserts.assertTrue(!re.getDuration().isNegative() && !re.getDuration().isZero());
                break;
            default:
                Asserts.fail("Unexpected event: " + re);
                break;
        }
    }
}
 
Example #26
Source File: TestRecordedThreadGroupParent.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void assetrThreadGroupParents(ThreadGroup realGroup, RecordedThreadGroup recordedGroup) {
    if (recordedGroup == null && realGroup == null) {
        return; // root
    }
    Asserts.assertNotNull(recordedGroup, "Parent thread group should not be null");
    Asserts.assertEquals(realGroup.getName(), recordedGroup.getName(), "Parent thread group names don't match");
    assetrThreadGroupParents(realGroup.getParent(), recordedGroup.getParent());
}
 
Example #27
Source File: TestFullStackTrace.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static boolean hasValidStackTraces(Recording recording, RecurseThread[] threads) throws Throwable {
    boolean[] isEventFound = new boolean[threads.length];

    for (RecordedEvent event : Events.fromRecording(recording)) {
        //System.out.println("Event: " + event);
        String threadName = Events.assertField(event, "sampledThread.javaName").getValue();
        long threadId = Events.assertField(event, "sampledThread.javaThreadId").getValue();

        for (int threadIndex = 0; threadIndex < threads.length; ++threadIndex) {
            RecurseThread currThread = threads[threadIndex];
            if (threadId == currThread.getId()) {
                System.out.println("ThreadName=" + currThread.getName() + ", depth=" + currThread.totalDepth);
                Asserts.assertEquals(threadName, currThread.getName(), "Wrong thread name");
                if ("recurseEnd".equals(getTopMethodName(event))) {
                    isEventFound[threadIndex] = true;
                    checkEvent(event, currThread.totalDepth);
                    break;
                }
            }
        }
    }

    for (int i = 0; i < threads.length; ++i) {
        String msg = "threadIndex=%d, recurseDepth=%d, isEventFound=%b%n";
        System.out.printf(msg, i, threads[i].totalDepth, isEventFound[i]);
    }
    for (int i = 0; i < threads.length; ++i) {
        if(!isEventFound[i]) {
           // no assertion, let's retry.
           // Could be race condition, i.e safe point during Thread.sleep
           System.out.println("Falied to validate all threads, will retry.");
           return false;
        }
    }
    return true;
}
 
Example #28
Source File: TestRecordingSettingsInvalid.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Map<String, String> settings = new HashMap<>();
    settings.put(null, "true");
    settings.put("java.exception_throw#stackTrace", null);
    settings.put("java.exception_throw#threshold", "not-a-number");
    settings.put("os.information#period", "4 x");

    // TODO: No exception for these settings. Not sure how much validation can be done on settings.
    //settings.put("java.exception_throw#enabled", "maybe");
    //settings.put("os.information#period", "-4 s");
    //settings.put("java.exception_throw#thread", "");
    //settings.put("", "true");
    //settings.put("os.information#what", "4 ms");
    //settings.put("#", "4 what");
    //settings.put("java.exception_throw#", "true");
    //settings.put("java.exception_throwenabled", "false");

    FlightRecorderMXBean bean = JmxHelper.getFlighteRecorderMXBean();

    for (String key : settings.keySet()) {
        System.out.printf("settings: %s=%s%n", key, settings.get(key));
        Map<String, String> temp = new HashMap<String, String>();
        temp.put(key, settings.get(key));
        long recId = -1;
        try {
            recId = bean.newRecording();
            bean.setRecordingSettings(recId, temp);
            bean.startRecording(recId);
            bean.stopRecording(recId);
            Asserts.fail("Missing exception");
        } catch (Exception e) {
            System.out.println("Got expected exception: " + e.getMessage());
        } finally {
            bean.closeRecording(recId);
        }
    }
}
 
Example #29
Source File: InitialAndMaxUsageTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected void runTest() {
    long headerSize = CodeCacheUtils.getHeaderSize(btype);
    MemoryPoolMXBean bean = btype.getMemoryPool();
    long initialUsage = btype.getMemoryPool().getUsage().getUsed();
    System.out.printf("INFO: trying to test %s of max size %d and initial"
            + " usage %d%n", bean.getName(), maxSize, initialUsage);
    Asserts.assertLT(initialUsage + headerSize + 1L, maxSize,
            "Initial usage is close to total size for " + bean.getName());
    if (lowerBoundIsZero) {
        Asserts.assertEQ(initialUsage, 0L, "Unexpected initial usage");
    }
    ArrayList<Long> blobs = new ArrayList<>();
    long minAllocationUnit = Math.max(1, CodeCacheUtils.MIN_ALLOCATION - headerSize);
    /* now filling code cache with large-sized allocation first, since
     lots of small allocations takes too much time, so, just a small
     optimization */
    try {
        for (int coef = 1000000; coef > 0; coef /= 10) {
            fillWithSize(coef * minAllocationUnit, blobs, bean);
        }
        Asserts.assertGT((double) bean.getUsage().getUsed(),
                CACHE_USAGE_COEF * maxSize, String.format("Unable to fill "
                        + "more than %f of %s. Reported usage is %d ",
                        CACHE_USAGE_COEF, bean.getName(),
                        bean.getUsage().getUsed()));
    } finally {
        for (long entry : blobs) {
            CodeCacheUtils.WB.freeCodeBlob(entry);
        }
    }
    System.out.printf("INFO: Scenario finished successfully for %s%n",
            bean.getName());
}
 
Example #30
Source File: DirectiveParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void emptyObjectTest() {
    String fileName = "emptyObject.json";
    try (JSONFile file = new JSONFile(fileName)) {
        file.write(JSONFile.Element.OBJECT);
        file.end();
    }
    OutputAnalyzer output = HugeDirectiveUtil.execute(fileName);
    Asserts.assertNE(output.getExitValue(), 0, ERROR_MSG + "empty object "
            + "without any match");
    output.shouldContain(EXPECTED_ERROR_STRING);
}