jdk.testlibrary.Asserts Java Examples

The following examples show how to use jdk.testlibrary.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: TestName.java    From dragonwell8_jdk 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(NamedEvent.class);
    ValueDescriptor testField = t.getField("testField");
    SettingDescriptor setting = getSetting(t, "name");
    AnnotationElement a = Events.getAnnotationByName(t, "com.oracle.TestAnnotation");

    // Check that names are overridden
    Asserts.assertNotNull(testField, "Can't find expected field testField");
    Asserts.assertEquals(t.getName(), "com.oracle.TestEvent", "Incorrect name for event");
    Asserts.assertEquals(a.getTypeName(), "com.oracle.TestAnnotation", "Incorrect name for annotation");
    Asserts.assertEquals(a.getTypeName(), "com.oracle.TestAnnotation", "Incorrect name for annotation");
    Asserts.assertEquals(setting.getName(), "name", "Incorrect name for setting");

    // Check that @Name is persisted
    assertAnnotation(t.getAnnotation(Name.class), "@Name should be persisted on event");
    assertAnnotation(testField.getAnnotation(Name.class), "@Name should be persisted on field");
    assertAnnotation(a.getAnnotation(Name.class), "@Name should be persisted on annotations");
    assertAnnotation(setting.getAnnotation(Name.class), "@Name should be persisted on setting");
}
 
Example #2
Source File: JpsHelper.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generate all possible combinations of {@link JpsArg}
 * (31 argument combinations and no arguments case)
 */
public static List<List<JpsArg>> generateCombinations() {
    final int argCount = JpsArg.values().length;
    // If there are more than 30 args this algorithm will overflow.
    Asserts.assertLessThan(argCount, 31, "Too many args");

    List<List<JpsArg>> combinations = new ArrayList<>();
    int combinationCount = (int) Math.pow(2, argCount);
    for (int currCombo = 0; currCombo < combinationCount; ++currCombo) {
        List<JpsArg> combination = new ArrayList<>();
        for (int position = 0; position < argCount; ++position) {
            int bit = 1 << position;
            if ((bit & currCombo) != 0) {
                combination.add(JpsArg.values()[position]);
            }
        }
        combinations.add(combination);
    }
    return combinations;
}
 
Example #3
Source File: HeapSummaryEventAllGcs.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void checkMetaspaceEventContent(RecordedEvent event) {
    long totalUsed = Events.assertField(event, "metaspace.used").atLeast(0L).getValue();
    long totalCommitted = Events.assertField(event, "metaspace.committed").atLeast(totalUsed).getValue();
    long totalReserved = Events.assertField(event, "metaspace.reserved").atLeast(totalCommitted).getValue();

    long dataUsed = Events.assertField(event, "dataSpace.used").atLeast(0L).getValue();
    long dataCommitted = Events.assertField(event, "dataSpace.committed").atLeast(dataUsed).getValue();
    long dataReserved = Events.assertField(event, "dataSpace.reserved").atLeast(dataCommitted).getValue();

    long classUsed = Events.assertField(event, "classSpace.used").atLeast(0L).getValue();
    long classCommitted = Events.assertField(event, "classSpace.committed").atLeast(classUsed).getValue();
    long classReserved = Events.assertField(event, "classSpace.reserved").atLeast(classCommitted).getValue();

    Asserts.assertEquals(dataCommitted + classCommitted, totalCommitted, "Wrong committed memory");
    Asserts.assertEquals(dataUsed + classUsed, totalUsed, "Wrong used memory");
    Asserts.assertEquals(dataReserved + classReserved, totalReserved, "Wrong reserved memory");
}
 
Example #4
Source File: TestGetConfigurations.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    List<Configuration> predefinedConfigs = Configuration.getConfigurations();
    Asserts.assertNotNull(predefinedConfigs, "List of predefined configs is null");
    Asserts.assertEquals(predefinedConfigs.size(), 2, "Expected exactly two predefined configurations");

    Configuration defaultConfig = findConfigByName(predefinedConfigs, DEFAULT_CONFIG_NAME);
    Asserts.assertNotNull(defaultConfig, "Config '" + DEFAULT_CONFIG_NAME + "' not found");
    Asserts.assertEquals(defaultConfig.getLabel(), DEFAULT_CONFIG_LABEL);
    Asserts.assertEquals(defaultConfig.getDescription(), DEFAULT_CONFIG_DESCRIPTION);
    Asserts.assertEquals(defaultConfig.getProvider(), DEFAULT_CONFIG_PROVIDER);

    Configuration profileConfig = findConfigByName(predefinedConfigs, PROFILE_CONFIG_NAME);
    Asserts.assertNotNull(profileConfig, "Config '" + PROFILE_CONFIG_NAME + "' not found");
    Asserts.assertEquals(profileConfig.getLabel(), PROFILE_CONFIG_LABEL);
    Asserts.assertEquals(profileConfig.getDescription(), PROFILE_CONFIG_DESCRIPTION);
    Asserts.assertEquals(profileConfig.getProvider(), PROFILE_CONFIG_PROVIDER);
}
 
Example #5
Source File: TestGetDescription.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    EventType defaultType = EventType.getEventType(DefaultEvent.class);
    System.out.printf("defaultType.category='%s'%n", defaultType.getCategoryNames());
    System.out.printf("defaultType.desc='%s'%n", defaultType.getDescription());
    System.out.printf("defaultType.label='%s'%n", defaultType.getLabel());

    List<String> defaultCategory = Arrays.asList(new String[] {"Uncategorized"});
    Asserts.assertEquals(defaultType.getCategoryNames(), defaultCategory, "Wrong default category");
    Asserts.assertNull(defaultType.getDescription(), "Wrong default description");
    Asserts.assertEquals(defaultType.getLabel(), null, "Wrong default label"); // JavaDoc says "not null"

    EventType annotatedType = EventType.getEventType(AnnotatedEvent.class);
    System.out.printf("annotated.category='%s'%n", annotatedType.getCategoryNames());
    System.out.printf("annotated.desc='%s'%n", annotatedType.getDescription());
    System.out.printf("annotated.label='%s'%n", annotatedType.getLabel());

    List<String> expectedCategorNames = new ArrayList<>();
    expectedCategorNames.add("MyCategory");
    Asserts.assertEquals(annotatedType.getCategoryNames(), expectedCategorNames, "Wrong default category");
    Asserts.assertEquals(annotatedType.getDescription(), "MyDesc", "Wrong default description");
    Asserts.assertEquals(annotatedType.getLabel(), "MyLabel", "Wrong default label");
}
 
Example #6
Source File: TestG1ConcurrentModeFailureEvent.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String[] vmFlags = {"-Xmx512m", "-Xms512m", "-XX:MaxTenuringThreshold=0",
        "-XX:+UseG1GC", "-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("testG1GC.log", "concurrent-mark-abort");
        System.out.println("isEventTriggered=" +isEventTriggered);
        Asserts.assertFalse(isEventTriggered, "Event found in log, but not in JFR");
    }
}
 
Example #7
Source File: TestDuration.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    final Duration duration = Duration.ofSeconds(1);
    Recording r = new Recording();
    r.setDuration(duration);
    Asserts.assertEquals(duration, r.getDuration(), "Wrong get/set duration");

    r.start();
    Instant afterStart = Instant.now();
    CommonHelper.waitForRecordingState(r, RecordingState.STOPPED);

    Instant afterStop = Instant.now();
    Asserts.assertLessThanOrEqual(r.getStopTime(), afterStop, "getStopTime() > afterStop");
    long durationMillis = Duration.between(afterStart, r.getStopTime()).toMillis();

    // Performance of test servers varies too much to make a strict check of actual duration.
    // We only check that recording stops before timeout of 20 seconds.
    System.out.printf("Recording stopped after %d ms, expected above 1000 ms%n", durationMillis);
    r.close();
}
 
Example #8
Source File: JpsHelper.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generate all possible combinations of {@link JpsArg}
 * (31 argument combinations and no arguments case)
 */
public static List<List<JpsArg>> generateCombinations() {
    final int argCount = JpsArg.values().length;
    // If there are more than 30 args this algorithm will overflow.
    Asserts.assertLessThan(argCount, 31, "Too many args");

    List<List<JpsArg>> combinations = new ArrayList<>();
    int combinationCount = (int) Math.pow(2, argCount);
    for (int currCombo = 0; currCombo < combinationCount; ++currCombo) {
        List<JpsArg> combination = new ArrayList<>();
        for (int position = 0; position < argCount; ++position) {
            int bit = 1 << position;
            if ((bit & currCombo) != 0) {
                combination.add(JpsArg.values()[position]);
            }
        }
        combinations.add(combination);
    }
    return combinations;
}
 
Example #9
Source File: TestNotificationListenerPermission.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try {
        System.getProperty("user.name");
        Asserts.fail("Didn't get security exception. Test not configured propertly?");
    } catch (SecurityException se) {
        // as expected
    }
    FlightRecorderMXBean bean = JmxHelper.getFlighteRecorderMXBean();
    TestListener testListener = new TestListener();
    ManagementFactory.getPlatformMBeanServer().addNotificationListener(new ObjectName(FlightRecorderMXBean.MXBEAN_NAME), testListener, null, null);
    long id = bean.newRecording();
    bean.startRecording(id);
    testListener.awaitNotication();
    Asserts.assertTrue(gotSecurityException, "Should not get elevated privileges in notification handler!");
    bean.stopRecording(id);
    bean.closeRecording(id);
}
 
Example #10
Source File: CatchExceptionTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void assertReturn(Object returned, Object arg0, Object arg1,
        int catchDrops, Object... args) {
    int lag = 0;
    if (throwMode == ThrowMode.CAUGHT) {
        lag = 1;
    }
    Helper.assertCalled(lag, callName(), arg0, arg1);

    if (throwMode == ThrowMode.NOTHING) {
        assertEQ(cast.apply(arg0), returned);
    } else if (throwMode == ThrowMode.CAUGHT) {
        List<Object> catchArgs = new ArrayList<>(Arrays.asList(args));
        // catcher receives an initial subsequence of target arguments:
        catchArgs.subList(args.length - catchDrops, args.length).clear();
        // catcher also receives the exception, prepended:
        catchArgs.add(0, thrown);
        Helper.assertCalled("catcher", catchArgs);
        assertEQ(cast.apply(catchArgs), returned);
    }
    Asserts.assertEQ(0, fakeIdentityCount);
}
 
Example #11
Source File: TestGetStackTrace.java    From dragonwell8_jdk 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 #12
Source File: TestClinitRegistration.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Test basic registration with or without auto registration
    assertClinitRegister(AutoRegisteredEvent.class, true, false);
    assertClinitRegister(NotAutoRegisterededEvent.class, false, false);
    assertClinitRegister(AutoRegisteredUserClinit.class, true, true);
    assertClinitRegister(NotAutoRegisteredUserClinit.class, false, true);

    // Test complex <clinit>
    assertClinitRegister(ComplexClInit.class, true, true);

    // Test hierarchy
    assertClinitRegister(DerivedClinit.class, true, true);
    if (!isClinitExecuted(Base.class)) {
        Asserts.fail("Expected <clinit> of base class to be executed");
    }

    // Test committed event in <clinit>
    Recording r = new Recording();
    r.start();
    r.enable(EventInClinit.class);
    triggerClinit(EventInClinit.class);
    r.stop();
    hasEvent(r, EventInClinit.class.getName());
}
 
Example #13
Source File: CatchExceptionTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void assertReturn(Object returned, Object arg0, Object arg1,
        int catchDrops, Object... args) {
    int lag = 0;
    if (throwMode == ThrowMode.CAUGHT) {
        lag = 1;
    }
    Helper.assertCalled(lag, callName(), arg0, arg1);

    if (throwMode == ThrowMode.NOTHING) {
        assertEQ(cast.apply(arg0), returned);
    } else if (throwMode == ThrowMode.CAUGHT) {
        List<Object> catchArgs = new ArrayList<>(Arrays.asList(args));
        // catcher receives an initial subsequence of target arguments:
        catchArgs.subList(args.length - catchDrops, args.length).clear();
        // catcher also receives the exception, prepended:
        catchArgs.add(0, thrown);
        Helper.assertCalled("catcher", catchArgs);
        assertEQ(cast.apply(catchArgs), returned);
    }
    Asserts.assertEQ(0, fakeIdentityCount);
}
 
Example #14
Source File: HeapSummaryEventAllGcs.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void checkMetaspaceEventContent(RecordedEvent event) {
    long totalUsed = Events.assertField(event, "metaspace.used").atLeast(0L).getValue();
    long totalCommitted = Events.assertField(event, "metaspace.committed").atLeast(totalUsed).getValue();
    long totalReserved = Events.assertField(event, "metaspace.reserved").atLeast(totalCommitted).getValue();

    long dataUsed = Events.assertField(event, "dataSpace.used").atLeast(0L).getValue();
    long dataCommitted = Events.assertField(event, "dataSpace.committed").atLeast(dataUsed).getValue();
    long dataReserved = Events.assertField(event, "dataSpace.reserved").atLeast(dataCommitted).getValue();

    long classUsed = Events.assertField(event, "classSpace.used").atLeast(0L).getValue();
    long classCommitted = Events.assertField(event, "classSpace.committed").atLeast(classUsed).getValue();
    long classReserved = Events.assertField(event, "classSpace.reserved").atLeast(classCommitted).getValue();

    Asserts.assertEquals(dataCommitted + classCommitted, totalCommitted, "Wrong committed memory");
    Asserts.assertEquals(dataUsed + classUsed, totalUsed, "Wrong used memory");
    Asserts.assertEquals(dataReserved + classReserved, totalReserved, "Wrong reserved memory");
}
 
Example #15
Source File: TestRetransform.java    From dragonwell8_jdk 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(TestEvent.class);
    if (type.isEnabled()) {
        Asserts.fail("Expected event to be disabled before recording start");
    }
    Recording r = new Recording();
    r.start();
    if (!type.isEnabled()) {
        Asserts.fail("Expected event to be enabled during recording");
    }
    TestEvent testEvent = new TestEvent();
    testEvent.commit();
    loadEventClassDuringRecording();
    r.stop();
    if (type.isEnabled()) {
        Asserts.fail("Expected event to be disabled after recording stopped");
    }
    Events.hasEvent(r, SimpleEvent.class.getName());
    Events.hasEvent(r, TestEvent.class.getName());
}
 
Example #16
Source File: TestEventMetadata.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void verifyName(String name) {
    System.out.println("Verifying name: " + name);
    Asserts.assertNotEquals(name, null, "Name not allowed to be null");
    Asserts.assertTrue(name.length() > 1, "Name must be at least two characters");
    Asserts.assertTrue(name.length() < 32, "Name should not exceed 32 characters");
    Asserts.assertFalse(isReservedKeyword(name),"Name must not be reserved keyword in the Java language (" + name + ")");
    char firstChar = name.charAt(0);
    Asserts.assertTrue(Character.isAlphabetic(firstChar), "Name must start with a character");
    Asserts.assertTrue(Character.isLowerCase(firstChar), "Name must start with lower case letter");
    Asserts.assertTrue(Character.isJavaIdentifierStart(firstChar), "Not valid first character for Java identifier");
    for (int i = 1; i < name.length(); i++) {
        Asserts.assertTrue(Character.isJavaIdentifierPart(name.charAt(i)), "Not valid character for a Java identifier");
        Asserts.assertTrue(Character.isAlphabetic(name.charAt(i)), "Name must consists of characters, found '" + name.charAt(i) + "'");
    }
    Asserts.assertFalse(name.contains("ID"), "'ID' should not be used in name, consider using 'Id'");
    checkCommonAbbreviations(name);
}
 
Example #17
Source File: TestBiasedLockRevocationEvents.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testBulkRevocation() throws Throwable {
    class MyLock {};

    Recording recording = new Recording();

    recording.enable(EventNames.BiasedLockClassRevocation);
    recording.start();

    Thread biasBreaker = triggerRevocation(BULK_REVOKE_THRESHOLD, MyLock.class);

    recording.stop();
    List<RecordedEvent> events = Events.fromRecording(recording);
    Asserts.assertEQ(events.size(), 1);

    RecordedEvent event = events.get(0);
    Events.assertEventThread(event, biasBreaker);
    Events.assertField(event, "disableBiasing").equal(false);

    RecordedClass lockClass = event.getValue("revokedClass");
    Asserts.assertEquals(lockClass.getName(), MyLock.class.getName());

    validateStackTrace(event.getStackTrace());
}
 
Example #18
Source File: PromotionFailedEvent.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void test(String testName, String[] vmFlags) throws Throwable {
    String jfr_file = testName + ".jfr";

    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;
    }

    // This test can not always trigger the expected event.
    // Test is ok even if no events found.
    List<RecordedEvent> events = RecordingFile.readAllEvents(Paths.get(jfr_file));
    for (RecordedEvent event : events) {
        System.out.println("Event: " + event);
        long smallestSize = Events.assertField(event, "promotionFailed.smallestSize").atLeast(1L).getValue();
        long firstSize = Events.assertField(event, "promotionFailed.firstSize").atLeast(smallestSize).getValue();
        long totalSize = Events.assertField(event, "promotionFailed.totalSize").atLeast(firstSize).getValue();
        long objectCount = Events.assertField(event, "promotionFailed.objectCount").atLeast(1L).getValue();
        Asserts.assertLessThanOrEqual(smallestSize * objectCount, totalSize, "smallestSize * objectCount <= totalSize");
    }
}
 
Example #19
Source File: TestRecordedEventGetThreadOther.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Thread.currentThread().setName("MyMainThread");

    PostingThread thread = new PostingThread();
    thread.start();
    thread.join();
    System.out.println("testing dump in file " + dumpFilePath);

    List<RecordedEvent> events = RecordingFile.readAllEvents(dumpFilePath);
    Asserts.assertEquals(events.size(), 1);

    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.getId());
    Asserts.assertEquals(recordedThread.getOSName(), MY_THREAD_NAME);
}
 
Example #20
Source File: TestGetStream.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void assertContainsId(Recording r, String interval, Instant start, Instant end, Integer... ids) throws IOException {
    List<Integer> idList = new ArrayList<>(Arrays.asList(ids));
    long time = System.currentTimeMillis();
    String fileName = idList.stream().map(x -> x.toString()).collect(Collectors.joining("_", "recording-get-stream_" + time + "_", ".jfr"));
    Path file = Paths.get(fileName);
    try (InputStream is = r.getStream(start, end)) {
        Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
    }
    try (RecordingFile rf = new RecordingFile(file)) {
        while (rf.hasMoreEvents()) {
            RecordedEvent event = rf.readEvent();
            Integer id = event.getValue("id");
            Asserts.assertTrue(idList.contains(id), "Unexpected id " + id + " found in interval " + interval);
            idList.remove(id);
        }
        Asserts.assertTrue(idList.isEmpty(), "Expected events with ids " + idList);
    }
}
 
Example #21
Source File: GetInstanceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check specific attributes of a SecureRandom instance.
 */
private static void checkAttributes(SecureRandom sr, String mech) {
    if (sr == null) {
        return;
    }
    Asserts.assertEquals(sr.getAlgorithm(), (isDRBG(mech) ? "DRBG" : mech));
    Asserts.assertEquals(sr.getProvider().getName(), SUN_PROVIDER);
}
 
Example #22
Source File: GCEventAll.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies field "cause" in garbage_collection event.
 * Only check that at cause is not null and that at least 1 cause is "System.gc()"
 * We might want to check more cause reasons later.
 */
private void verifyCollectionCause(List<GCHelper.GcBatch> batches) {
    int systemGcCount = 0;
    for (GCHelper.GcBatch batch : batches) {
        RecordedEvent endEvent = batch.getEndEvent();
        String cause = Events.assertField(endEvent, "cause").notEmpty().getValue();
        // A System.GC() can be consolidated into a GCLocker GC
        if (cause.equals("System.gc()") || cause.equals("GCLocker Initiated GC")) {
            systemGcCount++;
        }
        Asserts.assertNotNull(batch.getName(), "garbage_collection.name was null");
    }
    final String msg = "No event with cause=System.gc(), collectors(%s, %s)";
    Asserts.assertTrue(systemGcCount > 0, String.format(msg, youngCollector, oldCollector));
}
 
Example #23
Source File: TestValueDescriptorContentType.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Throwable {
    EventType type = EventType.getEventType(AlohaEvent.class);

    // check field annotation on event value
    ValueDescriptor filter = type.getField("greeting");
    Asserts.assertEquals(filter.getContentType(), Hawaiian.class.getName());

    // check field annotation with missing content type
    ValueDescriptor missing = type.getField("missing");
    Asserts.assertEquals(missing.getContentType(), null);

    // check field annotation with annotation but not content type
    ValueDescriptor otherAnnotation = type.getField("otherAnnotation");
    Asserts.assertEquals(otherAnnotation.getContentType(), null);
}
 
Example #24
Source File: CatchExceptionTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private void runTest() {
    Helper.clear();

    Object[] args = Helper.randomArgs(
            argsCount, thrower.type().parameterArray());
    Object arg0 = Helper.MISSING_ARG;
    Object arg1 = testCase.thrown;
    if (argsCount > 0) {
        arg0 = args[0];
    }
    if (argsCount > 1) {
        args[1] = arg1;
    }
    Asserts.assertEQ(nargs, thrower.type().parameterCount());
    if (argsCount < nargs) {
        Object[] appendArgs = {arg0, arg1};
        appendArgs = Arrays.copyOfRange(appendArgs, argsCount, nargs);
        thrower = MethodHandles.insertArguments(
                thrower, argsCount, appendArgs);
    }
    Asserts.assertEQ(argsCount, thrower.type().parameterCount());

    MethodHandle target = MethodHandles.catchException(
            testCase.filter(thrower), testCase.throwableClass,
            testCase.filter(catcher));

    Asserts.assertEQ(thrower.type(), target.type());
    Asserts.assertEQ(argsCount, target.type().parameterCount());

    Object returned;
    try {
        returned = target.invokeWithArguments(args);
    } catch (Throwable ex) {
        testCase.assertCatch(ex);
        returned = ex;
    }

    testCase.assertReturn(returned, arg0, arg1, dropped, args);
}
 
Example #25
Source File: TestJpsSanity.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testJpsUnknownHost() throws Exception {
    String invalidHostName = "Oja781nh2ev7vcvbajdg-Sda1-C";
    OutputAnalyzer output = JpsHelper.jps(invalidHostName);
    Asserts.assertNotEquals(output.getExitValue(), 0, "Exit code shouldn't be 0");
    Asserts.assertFalse(output.getStderr().isEmpty(), "Error output should not be empty");
    output.shouldContain("Unknown host: " + invalidHostName);
}
 
Example #26
Source File: TestClinitRegistration.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void hasEvent(Recording r, String name) throws IOException {
    List<RecordedEvent> events = Events.fromRecording(r);
    Events.hasEvents(events);

    for (RecordedEvent event : events) {
        if (event.getEventType().getName().equals(name)) {
            return;
        }
    }
    Asserts.fail("Missing event " + name + " in recording " + events.toString());
}
 
Example #27
Source File: GCEventAll.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that the collector name in initial configuration matches the name in garbage configuration event.
 * If the names are not equal, then we check if this is an expected collector override.
 * For example, if old collector in initial config is "G1Old" we allow both event "G1Old" and "SerialOld".
 */
private void verifyCollectorNames(List<GCHelper.GcBatch> batches) {
    for (GCHelper.GcBatch batch : batches) {
        String name = batch.getName();
        Asserts.assertNotNull(name, "garbage_collection.name was null");
        boolean isYoung = batch.isYoungCollection();
        String expectedName = isYoung ? youngCollector : oldCollector;
        if (!expectedName.equals(name)) {
            // Collector names not equal. Check if the collector has been overridden by an expected collector.
            String overrideKey = expectedName + "." + name;
            boolean isOverride = GCHelper.collectorOverrides.contains(overrideKey);
            Asserts.assertTrue(isOverride, String.format("Unexpected event name(%s) for collectors(%s, %s)", name, youngCollector, oldCollector));
        }
    }
}
 
Example #28
Source File: TestObjectCountEvent.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Recording recording = new Recording();
    recording.enable(objectCountEventPath);
    recording.enable(heapSummaryEventPath);

    ObjectCountEventVerifier.createTestData();
    System.gc();
    recording.start();
    recording.stop();

    List<RecordedEvent> events = Events.fromRecording(recording);
    for (RecordedEvent event : events) {
        System.out.println("Event: " + event);
    }

    Optional<RecordedEvent> heapSummaryEvent = events.stream()
                            .filter(e -> Events.isEventType(e, heapSummaryEventPath))
                            .filter(e -> "After GC".equals(Events.assertField(e, "when").getValue()))
                            .findFirst();
    Asserts.assertTrue(heapSummaryEvent.isPresent(), "No heapSummary with cause='After GC'");
    System.out.println("Found heapSummaryEvent: " + heapSummaryEvent.get());
    Events.assertField(heapSummaryEvent.get(), "heapUsed").atLeast(0L).getValue();
    int gcId = Events.assertField(heapSummaryEvent.get(), "gcId").getValue();

    List<RecordedEvent> objCountEvents = events.stream()
                            .filter(e -> Events.isEventType(e, objectCountEventPath))
                            .filter(e -> isGcId(e, gcId))
                            .collect(Collectors.toList());
    Asserts.assertFalse(objCountEvents.isEmpty(), "No objCountEvents for gcId=" + gcId);
    ObjectCountEventVerifier.verify(objCountEvents);
}
 
Example #29
Source File: CatchExceptionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void assertEQ(T t, Object returned) {
    if (rtype.isArray()) {
        Asserts.assertEQ(t.getClass(), returned.getClass());
        int n = Array.getLength(t);
        Asserts.assertEQ(n, Array.getLength(returned));
        for (int i = 0; i < n; ++i) {
            Asserts.assertEQ(Array.get(t, i), Array.get(returned, i));
        }
    } else {
        Asserts.assertEQ(t, returned);
    }
}
 
Example #30
Source File: GCEventAll.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private int getLastGcId(List<RecordedEvent> events) {
    int lastGcId = -1;
    for (RecordedEvent event : events) {
        if (GCHelper.isGcEvent(event)) {
            int gcId = GCHelper.getGcId(event);
            if (gcId > lastGcId) {
                lastGcId = gcId;
            }
        }
    }
    Asserts.assertTrue(lastGcId != -1, "No gcId found");
    return lastGcId;
}