Java Code Examples for org.junit.runner.Description#getAnnotation()

The following examples show how to use org.junit.runner.Description#getAnnotation() . 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: SMTestSender.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void prepareIgnoreMessage(Description description, boolean commentMessage) {
  Map attrs = new HashMap();
  if (commentMessage) {
    try {
      final Ignore ignoredAnnotation = (Ignore)description.getAnnotation(Ignore.class);
      if (ignoredAnnotation != null) {
        final String val = ignoredAnnotation.value();
        if (val != null) {
          attrs.put("message", val);
        }
      }
    }
    catch (NoSuchMethodError ignored) {
      //junit < 4.4
    }
  }
  attrs.put("name", getMethodName(description));
  System.out.println(ServiceMessage.asString(ServiceMessageTypes.TEST_IGNORED, attrs));
}
 
Example 2
Source File: ParseCmmnModelRule.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Override
protected void starting(Description description) {

  if(description.getAnnotation(CmmnModelResource.class) != null) {

    Class<?> testClass = description.getTestClass();
    String methodName = description.getMethodName();

    String resourceFolderName = testClass.getName().replaceAll("\\.", "/");
    String cmmnResourceName = resourceFolderName + "." + methodName + ".cmmn";

    InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(cmmnResourceName);
    try {
      CmmnModelInstance = Cmmn.readModelFromStream(resourceAsStream);
    } finally {
      IoUtil.closeSilently(resourceAsStream);
    }

  }

}
 
Example 3
Source File: DelegateRunNotifier.java    From buck with Apache License 2.0 6 votes vote down vote up
boolean hasJunitTimeout(Description description) {
  // Do not do apply the default timeout if the test has its own @Test(timeout).
  Test testAnnotation = description.getAnnotation(Test.class);
  if (testAnnotation != null && testAnnotation.timeout() > 0) {
    return true;
  }

  // Do not do apply the default timeout if the test has its own @Rule Timeout.
  if (runner instanceof ParentRunner) {
    return BuckBlockJUnit4ClassRunner.hasTimeoutRule(((ParentRunner) runner).getTestClass());
  }

  Class<?> clazz = description.getTestClass();
  while (clazz != null) {
    for (Field field : clazz.getFields()) {
      if (field.getAnnotationsByType(Rule.class).length > 0
          && field.getType().equals(Timeout.class)) {
        return true;
      }
    }

    clazz = clazz.getSuperclass();
  }
  return false;
}
 
Example 4
Source File: ByteBufRule.java    From datakernel with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(Statement base, Description description) {
	if (description.getTestClass().getAnnotation(IgnoreLeaks.class) != null
			|| description.getAnnotation(IgnoreLeaks.class) != null) {
		return base;
	}
	return new LambdaStatement(() -> {
		ByteBufPool.clear();
		base.evaluate();
		assertEquals(ByteBufPool.getStats().getPoolItemsString(), ByteBufPool.getStats().getCreatedItems(), ByteBufPool.getStats().getPoolItems());
	});
}
 
Example 5
Source File: RepeatRule.java    From incubator-weex-playground with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(Statement statement, Description description) {
  Statement result = statement;
  Repeat repeat = description.getAnnotation(Repeat.class);
  if (repeat != null) {
    int times = repeat.value();
    result = new RepeatStatement(statement, times);
  }
  return result;
}
 
Example 6
Source File: TestRequestBuilder.java    From android-test with Apache License 2.0 5 votes vote down vote up
private SdkSuppress getAnnotationForTest(Description description) {
  final SdkSuppress s = description.getAnnotation(SdkSuppress.class);
  if (s != null) {
    return s;
  }
  final Class<?> testClass = description.getTestClass();
  if (testClass != null) {
    return testClass.getAnnotation(SdkSuppress.class);
  }
  return null;
}
 
Example 7
Source File: RepeatRule.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(Statement statement, Description description) {
    Repeat repeat = description.getAnnotation(Repeat.class);

    if (repeat != null) {
        statement = RepeatStatement.builder().build(repeat, statement);
    }

    return statement;
}
 
Example 8
Source File: AllureSpock.java    From allure-java with Apache License 2.0 5 votes vote down vote up
private <T extends Annotation> List<T> getAnnotationsOnMethod(final Description result, final Class<T> clazz) {
    final T annotation = result.getAnnotation(clazz);
    return Stream.concat(
            extractRepeatable(result, clazz).stream(),
            Objects.isNull(annotation) ? Stream.empty() : Stream.of(annotation)
    ).collect(Collectors.toList());
}
 
Example 9
Source File: UiThreadTestRule.java    From android-test with Apache License 2.0 5 votes vote down vote up
protected boolean shouldRunOnUiThread(Description description) {
  if (description.getAnnotation(android.test.UiThreadTest.class) != null) {
    Log.w(
        TAG,
        "Deprecated android.test.UiThreadTest annotation is used! please switch "
            + "to using androidx.test.annotation.UiThreadTest instead.");
    return true;
  }
  return description.getAnnotation(UiThreadTest.class) != null;
}
 
Example 10
Source File: FlakyTestJUnit4RetryRule.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Override
public Statement apply(Statement base, Description description) {

    final Flaky annotation = description.getAnnotation(Flaky.class);

    if (annotation == null) {
        // leave the statement as-is
        return base;
    }

    if (annotation.githubIssueUrl().trim().length() == 0) {
        throw new IllegalArgumentException("A GitHub issue URL must be set for usages of the @Flaky annotation");
    }

    final int maxTries = annotation.maxTries();

    if (maxTries < 1) {
        throw new IllegalArgumentException("@Flaky annotation maxTries must be at least one");
    }

    final LocalDate reviewDate;
    try {
        reviewDate = LocalDate.parse(annotation.reviewDate());
    } catch (DateTimeParseException e) {
        throw new IllegalArgumentException("@Flaky reviewDate could not be parsed. Please provide a date in yyyy-mm-dd format");
    }

    // the annotation should only have an effect before the review date, to encourage review and resolution
    if ( LocalDate.now().isBefore(reviewDate) ) {
        return new RetryingStatement(base, description, maxTries);
    } else {
        return base;
    }
}
 
Example 11
Source File: AllureRunListener.java    From allure-cucumberjvm with Apache License 2.0 5 votes vote down vote up
public String
getIgnoredMessage(Description description) {
    Ignore ignore = description.getAnnotation(Ignore.class
    );
    return ignore
            == null || ignore.value()
            .isEmpty() ? "Test ignored (without reason)!" : ignore.value();
}
 
Example 12
Source File: RunAsRule.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            final RunAs annotation = description.getAnnotation(RunAs.class);
            final As as = description.getAnnotation(As.class);
            String currentRole = role.get();
            role.remove(); // no more needed
            if (annotation == null && as == null && currentRole == null) {
                base.evaluate();
                return;
            }

            final BeanContext beanContext = getBeanContext();
            if (currentRole == null) {
                if (annotation == null) {
                    currentRole = as.value();
                } else {
                    currentRole = annotation.value();
                }
            }
            final String runAs = beanContext.getRunAs();
            final String runAsUser = beanContext.getRunAsUser();
            beanContext.setRunAs(currentRole);
            final ThreadContext old = ThreadContext.enter(new ThreadContext(beanContext, null));
            try {
                base.evaluate();
            } finally {
                // reset for next test
                ThreadContext.exit(old);
                beanContext.setRunAs(runAs);
                beanContext.setRunAsUser(runAsUser);
            }
        }
    };
}
 
Example 13
Source File: ServiceTalkTestTimeout.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(Statement base, Description description) {
    // Check if multiple Timeout are present and annotated with @Rule.
    Class<?> clazz = description.getTestClass();
    List<Class<?>> timeoutRuleClasses = new ArrayList<>(2);
    do {
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Rule.class) && Timeout.class.isAssignableFrom(field.getType())) {
                timeoutRuleClasses.add(clazz);
            }
        }
    } while ((clazz = clazz.getSuperclass()) != Object.class);
    if (timeoutRuleClasses.size() > 1) {
        StringBuilder sb = new StringBuilder(256)
                .append("Only one @Rule for a Timeout is allowed, but ")
                .append(timeoutRuleClasses.size())
                .append(" were detected in types: ");
        for (Class<?> clazz2 : timeoutRuleClasses) {
            sb.append(clazz2.getName()).append(", ");
        }
        sb.setLength(sb.length() - 2);
        throw new IllegalStateException(sb.toString());
    }
    // If timeout is specified in @Test, let that have precedence over the global timeout.
    Test testAnnotation = description.getAnnotation(Test.class);
    if (testAnnotation != null) {
        long timeout = testAnnotation.timeout();
        if (timeout > 0) {
            return new TimeoutStatement(base, timeout, TimeUnit.MILLISECONDS, onTimeout);
        }
    }
    return new TimeoutStatement(base, getTimeout(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS, onTimeout);
}
 
Example 14
Source File: JUnitGradeSheetListener.java    From public with Apache License 2.0 5 votes vote down vote up
private static GradingSuite parseSuite(final Description description, final List<GradingTest> tests) {
    final GradedCategory annotation = description.getAnnotation(GradedCategory.class);

    final String suiteName =
            annotation.name().equals(GradedTest.DEFAULT_NAME) ?
                    description.getDisplayName() : annotation.name();

    final String suiteDescription =
            annotation.description().equals(GradedTest.DEFAULT_DESCRIPTION) ?
                    null : annotation.description();

    return new GradingSuite(description.getClassName(), suiteName, suiteDescription, tests);
}
 
Example 15
Source File: VersionMatcherRule.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void starting(Description d) {
  final TargetVersions targetVersions = d.getAnnotation(TargetVersions.class);
  if (targetVersions == null) return;

  myMatcher = new CustomMatcher<String>("Gradle version '" + targetVersions.value() + "'") {
    @Override
    public boolean matches(Object item) {
      return item instanceof String && new VersionMatcher(GradleVersion.version(item.toString())).isVersionMatch(targetVersions);
    }
  };
}
 
Example 16
Source File: TestSize.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if the test method in the {@link Description} is annotated with the test size
 *     annotation class.
 */
public boolean testMethodIsAnnotatedWithTestSize(Description description) {
  if (description.getAnnotation(runnerFilterAnnotationClass) != null
      || description.getAnnotation(platformAnnotationClass) != null) {
    // If the test method is annotated with a test size annotation include it
    return true;
  }
  // Otherwise exclude it
  return false;
}
 
Example 17
Source File: VideoRule.java    From video-recorder-java with MIT License 4 votes vote down vote up
protected String getFileName(Description description) {
    String methodName = description.getMethodName();
    Video video = description.getAnnotation(Video.class);
    return RecordingUtils.getVideoFileName(video,methodName);
}
 
Example 18
Source File: LoggingListener.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public void testStarted(final Description description) throws Exception {
    final TestLogging testLogging = description.getAnnotation(TestLogging.class);
    previousLoggingMap = processTestLogging(testLogging);
}
 
Example 19
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
public Statement apply(final Statement base, final Description description) {
    if (description.getAnnotation(WithoutJenkins.class) != null) {
        // request has been made to not create the instance for this test method
        return base;
    }
    Statement wrapped = new Statement() {
        @Override
        public void evaluate() throws Throwable {
            testDescription = description;
            Thread t = Thread.currentThread();
            String o = t.getName();
            t.setName("Executing "+ testDescription.getDisplayName());
            System.out.println("=== Starting " + testDescription.getDisplayName());
            before();
            try {
                // so that test code has all the access to the system
                ACL.impersonate(ACL.SYSTEM);
                try {
                    base.evaluate();
                } catch (Throwable th) {
                    // allow the late attachment of a debugger in case of a failure. Useful
                    // for diagnosing a rare failure
                    try {
                        throw new BreakException();
                    } catch (BreakException e) {}

                    RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class);
                    if (rf != null) {
                        System.err.println("Note: known to randomly fail: " + rf.value());
                    }

                    throw th;
                }
            } finally {
                after();
                testDescription = null;
                t.setName(o);
            }
        }
    };
    final int testTimeout = getTestTimeoutOverride(description);
    if (testTimeout <= 0) {
        System.out.println("Test timeout disabled.");
        return wrapped;
    } else {
        final Statement timeoutStatement = Timeout.seconds(testTimeout).apply(wrapped, description);
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                    timeoutStatement.evaluate();
                } catch (TestTimedOutException x) {
                    // withLookingForStuckThread does not work well; better to just have a full thread dump.
                    LOGGER.warning(String.format("Test timed out (after %d seconds).", testTimeout));
                    dumpThreads();
                    throw x;
                }
            }
        };
    }
}
 
Example 20
Source File: Script262Test.java    From es6draft with MIT License 4 votes vote down vote up
@Override
protected void starting(Description description) {
    isStrictTest = description.getAnnotation(Strict.class) != null;
}