org.junit.platform.commons.util.AnnotationUtils Java Examples

The following examples show how to use org.junit.platform.commons.util.AnnotationUtils. 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: OsCondition.java    From mastering-junit5 with Apache License 2.0 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(
        ExtensionContext context) {

    Optional<AnnotatedElement> element = context.getElement();
    ConditionEvaluationResult out = ConditionEvaluationResult
            .enabled("@DisabledOnOs is not present");

    Optional<DisabledOnOs> disabledOnOs = AnnotationUtils
            .findAnnotation(element, DisabledOnOs.class);

    if (disabledOnOs.isPresent()) {
        Os myOs = Os.determine();
        if (Arrays.asList(disabledOnOs.get().value()).contains(myOs)) {
            out = ConditionEvaluationResult
                    .disabled("Test is disabled on " + myOs);
        } else {
            out = ConditionEvaluationResult
                    .enabled("Test is not disabled on " + myOs);
        }
    }

    System.out.println("--> " + out.getReason().get());
    return out;
}
 
Example #2
Source File: JUnit5HttpApi.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeAll(final ExtensionContext extensionContext) {
    final HttpApi config =
            AnnotationUtils.findAnnotation(extensionContext.getElement(), HttpApi.class).orElse(null);
    if (config != null) {
        setGlobalProxyConfiguration(config.globalProxyConfiguration());
        setLogLevel(config.logLevel());
        setPort(config.port());
        newInstance(config.responseLocator(), ResponseLocator.class).ifPresent(this::setResponseLocator);
        newInstance(config.headerFilter(), Predicate.class).ifPresent(this::setHeaderFilter);
        newInstance(config.executor(), Executor.class).ifPresent(this::setExecutor);
        newInstance(config.sslContext(), Supplier.class)
                .map(s -> SSLContext.class.cast(s.get()))
                .ifPresent(this::setSslContext);
        setSkipProxyHeaders(config.skipProxyHeaders());
        if (config.useSsl()) {
            activeSsl();
        }
    }
    extensionContext.getStore(NAMESPACE).put(HttpApiHandler.class.getName(), this);
    final HandlerImpl<JUnit5HttpApi> handler = new HandlerImpl<>(this, null, null);
    extensionContext.getStore(NAMESPACE).put(HandlerImpl.class.getName(), handler);
    handler.start();
}
 
Example #3
Source File: JUnit5HttpApi.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeEach(final ExtensionContext extensionContext) {
    // test name
    final ResponseLocator responseLocator = getResponseLocator();
    if (!DefaultResponseLocator.class.isInstance(responseLocator)) {
        return;
    }
    final String test = extensionContext.getTestMethod().map(m -> {
        final String displayName = sanitizeDisplayName(extensionContext.getDisplayName());
        return AnnotationUtils
                .findAnnotation(m, HttpApiName.class)
                .map(HttpApiName::value)
                .map(it -> it.replace("${class}", m.getDeclaringClass().getName()))
                .map(it -> it.replace("${method}", m.getName()))
                .map(it -> it.replace("${displayName}", displayName))
                .orElseGet(() -> m.getDeclaringClass().getName() + "_" + m.getName()
                        + (displayName.equals(m.getName()) ? "" : ("_" + displayName)));
    }).orElse(null);
    DefaultResponseLocator.class.cast(responseLocator).setTest(test);
}
 
Example #4
Source File: DBUnitExtension.java    From database-rider with Apache License 2.0 6 votes vote down vote up
private DBUnitConfig resolveDbUnitConfig(Class callbackAnnotation, Method callbackMethod, Class testClass) {
    Optional<DBUnit> dbUnitAnnotation = AnnotationUtils.findAnnotation(callbackMethod, DBUnit.class);
    if (!dbUnitAnnotation.isPresent()) {
        dbUnitAnnotation = AnnotationUtils.findAnnotation(testClass, DBUnit.class);
    }
    if (!dbUnitAnnotation.isPresent()) {
        Optional<Method> superclassCallbackMethod = findSuperclassCallbackMethod(testClass, callbackAnnotation);
        if (superclassCallbackMethod.isPresent()) {
            dbUnitAnnotation = AnnotationUtils.findAnnotation(superclassCallbackMethod.get(), DBUnit.class);
        }
    }
    if (!dbUnitAnnotation.isPresent() && testClass.getSuperclass() != null) {
        dbUnitAnnotation = AnnotationUtils.findAnnotation(testClass.getSuperclass(), DBUnit.class);
    }
    return dbUnitAnnotation.isPresent() ? DBUnitConfig.from(dbUnitAnnotation.get()) : DBUnitConfig.fromGlobalConfig();
}
 
Example #5
Source File: OsCondition.java    From Mastering-Software-Testing-with-JUnit-5 with MIT License 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(
        ExtensionContext context) {

    Optional<AnnotatedElement> element = context.getElement();
    ConditionEvaluationResult out = ConditionEvaluationResult
            .enabled("@DisabledOnOs is not present");

    Optional<DisabledOnOs> disabledOnOs = AnnotationUtils
            .findAnnotation(element, DisabledOnOs.class);

    if (disabledOnOs.isPresent()) {
        Os myOs = Os.determine();
        if (Arrays.asList(disabledOnOs.get().value()).contains(myOs)) {
            out = ConditionEvaluationResult
                    .disabled("Test is disabled on " + myOs);
        } else {
            out = ConditionEvaluationResult
                    .enabled("Test is not disabled on " + myOs);
        }
    }

    System.out.println("--> " + out.getReason().get());
    return out;
}
 
Example #6
Source File: DBUnitExtension.java    From database-rider with Apache License 2.0 6 votes vote down vote up
private void executeExpectedDataSetForCallback(ExtensionContext extensionContext, Class callbackAnnotation, Method callbackMethod) throws DatabaseUnitException {
    Class testClass = extensionContext.getTestClass().get();
    // get ExpectedDataSet annotation, if any
    Optional<ExpectedDataSet> expectedDataSetAnnotation = AnnotationUtils.findAnnotation(callbackMethod, ExpectedDataSet.class);
    if (!expectedDataSetAnnotation.isPresent()) {
        Optional<Method> superclassCallbackMethod = findSuperclassCallbackMethod(testClass, callbackAnnotation);
        if (superclassCallbackMethod.isPresent()) {
            expectedDataSetAnnotation = AnnotationUtils.findAnnotation(superclassCallbackMethod.get(), ExpectedDataSet.class);
        }
    }
    if (expectedDataSetAnnotation.isPresent()) {
        ExpectedDataSet expectedDataSet = expectedDataSetAnnotation.get();
        // Resolve DBUnit config from annotation or file
        DBUnitConfig dbUnitConfig = resolveDbUnitConfig(callbackAnnotation, callbackMethod, testClass);
        // Verify expected dataset
        final String executorId = getExecutorId(extensionContext, null);
        ConnectionHolder connectionHolder = getTestConnection(extensionContext, executorId);
        DataSetExecutor dataSetExecutor = DataSetExecutorImpl.instance(executorId, connectionHolder, dbUnitConfig);
        dataSetExecutor.compareCurrentDataSetWith(
                new DataSetConfig(expectedDataSet.value()).disableConstraints(true).datasetProvider(expectedDataSet.provider()),
                expectedDataSet.ignoreCols(),
                expectedDataSet.replacers(),
                expectedDataSet.orderBy(),
                expectedDataSet.compareOperation());
    }
}
 
Example #7
Source File: DBUnitExtension.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private void executeDataSetForCallback(ExtensionContext extensionContext, Class callbackAnnotation, Method callbackMethod) {
    Class testClass = extensionContext.getTestClass().get();
    // get DataSet annotation, if any
    Optional<DataSet> dataSetAnnotation = AnnotationUtils.findAnnotation(callbackMethod, DataSet.class);
    if (!dataSetAnnotation.isPresent()) {
        Optional<Method> superclassCallbackMethod = findSuperclassCallbackMethod(testClass, callbackAnnotation);
        if (superclassCallbackMethod.isPresent()) {
            dataSetAnnotation = AnnotationUtils.findAnnotation(superclassCallbackMethod.get(), DataSet.class);
        }
    }
    if (dataSetAnnotation.isPresent()) {
        clearEntityManager();
        DBUnitConfig dbUnitConfig = resolveDbUnitConfig(callbackAnnotation, callbackMethod, testClass);
        DataSet dataSet;
        if (dbUnitConfig.isMergeDataSets()) {
            Optional<DataSet> classLevelDataSetAnnotation = AnnotationUtils.findAnnotation(testClass, DataSet.class);
            dataSet = resolveDataSet(dataSetAnnotation, classLevelDataSetAnnotation);
        } else {
            dataSet = dataSetAnnotation.get();
        }
        // Execute dataset
        final String executorId = getExecutorId(extensionContext, dataSet);
        ConnectionHolder connectionHolder = getTestConnection(extensionContext, executorId);
        DataSetExecutor dataSetExecutor = DataSetExecutorImpl.instance(executorId, connectionHolder, dbUnitConfig);
        dataSetExecutor.createDataSet(new DataSetConfig().from(dataSet));
    }
}
 
Example #8
Source File: AbstractDataProviderInvocationContextProvider.java    From junit-dataprovider with Apache License 2.0 5 votes vote down vote up
@Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext context) {
    Method testMethod = context.getRequiredTestMethod();

    return AnnotationUtils.findAnnotation(testMethod, testAnnotationClass)
            .map(annotation -> provideInvocationContexts(context, annotation))
            .orElseThrow(() -> new ExtensionConfigurationException(String.format(
                    "Could not find annotation '%s' on test method '%s'.", testAnnotationClass, testMethod)));
}
 
Example #9
Source File: TestcontainersExtension.java    From testcontainers-java with MIT License 5 votes vote down vote up
private Optional<Testcontainers> findTestcontainers(ExtensionContext context) {
    Optional<ExtensionContext> current = Optional.of(context);
    while (current.isPresent()) {
        Optional<Testcontainers> testcontainers = AnnotationUtils.findAnnotation(current.get().getRequiredTestClass(), Testcontainers.class);
        if (testcontainers.isPresent()) {
            return testcontainers;
        }
        current = current.get().getParent();
    }
    return Optional.empty();
}
 
Example #10
Source File: VideoExtension.java    From video-recorder-java with MIT License 5 votes vote down vote up
private boolean videoDisabled(Method testMethod) {
  Optional<com.automation.remarks.video.annotations.Video> video = AnnotationUtils.findAnnotation(testMethod, com.automation.remarks.video.annotations.Video.class);

  return video.map(v -> !videoEnabled(v))
          .orElseGet(() -> true);

  //return !video.isPresent() && !videoEnabled(video.get());
}
 
Example #11
Source File: VaultVersionExtension.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {

	Optional<RequiresVaultVersion> optional = AnnotationUtils.findAnnotation(context.getElement(),
			RequiresVaultVersion.class);

	if (!optional.isPresent()) {
		return ENABLED_BY_DEFAULT;
	}

	ExtensionContext.Store store = context.getStore(VAULT);

	Version runningVersion = store.getOrComputeIfAbsent(Version.class, versionClass -> {

		VaultInitializer initializer = new VaultInitializer();
		initializer.initialize();
		return initializer.prepare().getVersion();
	}, Version.class);

	RequiresVaultVersion requiredVersion = optional.get();

	Version required = Version.parse(requiredVersion.value());

	if (runningVersion.isGreaterThanOrEqualTo(required)) {
		return ConditionEvaluationResult
				.enabled(String.format("@VaultVersion check passed current Vault version is %s", runningVersion));
	}

	return ConditionEvaluationResult.disabled(String.format(
			"@VaultVersion requires since version %s, current Vault version is %s", required, runningVersion));
}
 
Example #12
Source File: DBUnitExtension.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private DataSet resolveDataSet(Optional<DataSet> methodLevelDataSet,
                               Optional<DataSet> classLevelDataSet) {
    if (classLevelDataSet.isPresent()) {
        return com.github.database.rider.core.util.AnnotationUtils.mergeDataSetAnnotations(classLevelDataSet.get(), methodLevelDataSet.get());
    } else {
        return methodLevelDataSet.get();
    }
}
 
Example #13
Source File: RegistryServiceExtension.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext context) {
    RegistryServiceTest rst = AnnotationUtils.findAnnotation(context.getRequiredTestMethod(), RegistryServiceTest.class)
                                             .orElseThrow(IllegalStateException::new); // should be there

    String registryUrl = TestUtils.getRegistryUrl(rst);

    ExtensionContext.Store store = context.getStore(ExtensionContext.Namespace.GLOBAL);

    List<TestTemplateInvocationContext> invocationCtxts = new ArrayList<>();

    if (testRegistryClient(REGISTRY_CLIENT_CREATE)) {
        RegistryServiceWrapper plain = store.getOrComputeIfAbsent(
                "plain_client",
                k -> new RegistryServiceWrapper(k, REGISTRY_CLIENT_CREATE, registryUrl),
                RegistryServiceWrapper.class
            );
        invocationCtxts.add(new RegistryServiceTestTemplateInvocationContext(plain, context.getRequiredTestMethod()));
    }

    if (testRegistryClient(REGISTRY_CLIENT_CACHED)) {
        RegistryServiceWrapper cached = store.getOrComputeIfAbsent(
                "cached_client",
                k -> new RegistryServiceWrapper(k, REGISTRY_CLIENT_CACHED, registryUrl),
                RegistryServiceWrapper.class
            );
        invocationCtxts.add(new RegistryServiceTestTemplateInvocationContext(cached, context.getRequiredTestMethod()));
    }

    return invocationCtxts.stream();
}
 
Example #14
Source File: DBUnitExtension.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private static String getConfiguredDataSourceBeanName(ExtensionContext extensionContext) {
    Optional<Method> testMethod = extensionContext.getTestMethod();
    if (testMethod.isPresent()) {
        Optional<DBRider> annotation = AnnotationUtils.findAnnotation(testMethod.get(), DBRider.class);
        if (!annotation.isPresent()) {
            annotation = AnnotationUtils.findAnnotation(extensionContext.getRequiredTestClass(), DBRider.class);
        }
        return annotation.map(DBRider::dataSourceBeanName).orElse(EMPTY_STRING);
    } else {
        return EMPTY_STRING;
    }
}
 
Example #15
Source File: DBUnitExtension.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private Optional<DataSet> findDataSetAnnotation(ExtensionContext extensionContext) {
    Optional<Method> testMethod = extensionContext.getTestMethod();
    if (testMethod.isPresent()) {
        Optional<DataSet> annDataSet = AnnotationUtils.findAnnotation(testMethod.get(), DataSet.class);
        if (!annDataSet.isPresent()) {
            annDataSet = AnnotationUtils.findAnnotation(extensionContext.getRequiredTestClass(), DataSet.class);
        }
        return annDataSet;
    } else {
        return Optional.empty();
    }
}
 
Example #16
Source File: SparkExtension.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(final ExtensionContext extensionContext) throws Exception {
    temporaryFolderExtension.beforeAll(extensionContext);
    root = TemporaryFolder.class
            .cast(temporaryFolderExtension.findInstance(extensionContext, TemporaryFolder.class))
            .getRoot();

    final ExtensionContext.Store store = extensionContext.getStore(NAMESPACE);
    store.put(BaseSpark.class.getName(), this);
    AnnotationUtils.findAnnotation(extensionContext.getElement(), WithSpark.class).ifPresent(ws -> {
        withSlaves(ws.slaves());
        withHadoopBase(ws.hadoopBase());
        withHadoopVersion(ws.hadoopVersion());
        withInstallWinUtils(ws.installWinUtils());
        withScalaVersion(of(ws.scalaVersion())
                .filter(it -> !"auto".equals(it))
                .orElse(SparkVersions.SPARK_SCALA_VERSION.getValue()));
        withSparkVersion(of(ws.sparkVersion())
                .filter(it -> !"auto".equals(it))
                .orElse(SparkVersions.SPARK_VERSION.getValue()));
    });
    final Instances instances = start();
    if (instances.getException() != null) {
        instances.close();
        if (Exception.class.isInstance(instances.getException())) {
            throw Exception.class.cast(instances.getException());
        }
        if (Error.class.isInstance(instances.getException())) {
            throw Error.class.cast(instances.getException());
        }
        throw new IllegalStateException(instances.getException());
    }
    store.put(AutoCloseable.class, instances);
}
 
Example #17
Source File: ComponentExtension.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(final ExtensionContext extensionContext) {
    final WithComponents element = AnnotationUtils
            .findAnnotation(extensionContext.getElement(), WithComponents.class)
            .orElseThrow(() -> new IllegalArgumentException(
                    "No annotation @WithComponents on " + extensionContext.getRequiredTestClass()));
    this.packageName = element.value();
    if (element.isolatedPackages().length > 0) {
        withIsolatedPackage(null, element.isolatedPackages());
    }

    final boolean shouldUseEach = shouldIgnore(extensionContext.getElement());
    if (!shouldUseEach) {
        doStart(extensionContext);
    } else if (!extensionContext.getElement().map(AnnotatedElement::getAnnotations).map(annotations -> {
        int componentIndex = -1;
        for (int i = 0; i < annotations.length; i++) {
            final Class<? extends Annotation> type = annotations[i].annotationType();
            if (type == WithComponents.class) {
                componentIndex = i;
            } else if (type == Environment.class && componentIndex >= 0) {
                return false;
            }
        }
        return true;
    }).orElse(false)) {
        // check the ordering, if environments are put after this then the context is likely wrong
        // this condition is a simple heuristic but enough for most cases
        throw new IllegalArgumentException("If you combine @WithComponents and @Environment, you must ensure "
                + "environment annotations are becoming before the component one otherwise you will run in an "
                + "unexpected context and will not reproduce real execution.");
    }
    extensionContext.getStore(NAMESPACE).put(USE_EACH_KEY, shouldUseEach);
    extensionContext.getStore(NAMESPACE).put(SHARED_INSTANCE, this);
}
 
Example #18
Source File: EnvironmentalContext.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEach(final ExtensionContext context) {
    closeable = provider
            .start(context.getRequiredTestClass(),
                    Stream
                            .concat(Stream.of(context.getRequiredTestClass().getAnnotations()),
                                    Stream
                                            .of(of(AnnotationUtils
                                                    .findRepeatableAnnotations(context.getRequiredTestClass(),
                                                            EnvironmentConfiguration.class))
                                                                    .filter(it -> !it.isEmpty())
                                                                    .map(l -> new Annotation[] {
                                                                            new EnvironmentConfigurations() {

                                                                                @Override
                                                                                public Class<? extends Annotation>
                                                                                        annotationType() {
                                                                                    return EnvironmentConfigurations.class;
                                                                                }

                                                                                @Override
                                                                                public EnvironmentConfiguration[]
                                                                                        value() {
                                                                                    return l
                                                                                            .toArray(
                                                                                                    new EnvironmentConfiguration[0]);
                                                                                }
                                                                            } })
                                                                    .orElseGet(() -> new Annotation[0])))
                            .toArray(Annotation[]::new));
    ofNullable(componentExtension).ifPresent(c -> {
        c.doStart(context);
        c.doInject(context);
    });
}
 
Example #19
Source File: WireMockExtension.java    From wiremock-extension with MIT License 5 votes vote down vote up
private static List<Field> retrieveAnnotatedFields(final ExtensionContext context,
                                                   final Class<? extends Annotation> annotationType,
                                                   final Class<?> fieldType) {

	return context.getElement()
			.filter(Class.class::isInstance)
			.map(Class.class::cast)
			.map(testInstanceClass ->
					AnnotationUtils.findAnnotatedFields(testInstanceClass, annotationType, field -> fieldType.isAssignableFrom(field.getType()))
			)
			.orElseGet(Collections::emptyList);
}
 
Example #20
Source File: ComponentExtension.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private boolean shouldIgnore(final Optional<AnnotatedElement> element) {
    return !AnnotationUtils.findRepeatableAnnotations(element, Environment.class).isEmpty();
}
 
Example #21
Source File: JUnit5RiderTestContext.java    From database-rider with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends Annotation> T getMethodAnnotation(Class<T> clazz) {
    return AnnotationUtils.findAnnotation(extensionContext.getTestMethod(), clazz).orElse(null);
}
 
Example #22
Source File: JUnit5RiderTestContext.java    From database-rider with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends Annotation> T getClassAnnotation(Class<T> clazz) {
    return AnnotationUtils.findAnnotation(extensionContext.getTestClass(), clazz).orElse(null);
}
 
Example #23
Source File: DockerExtension.java    From junit5-docker with Apache License 2.0 4 votes vote down vote up
private Docker findDockerAnnotation(ExtensionContext extensionContext) {
    Class<?> testClass = extensionContext.getTestClass().get();
    return AnnotationUtils.findAnnotation(testClass, Docker.class).orElseThrow(
        () -> new IllegalStateException(String.format("Could not find @Docker on class %s", testClass.getName())));
}
 
Example #24
Source File: FakeParameterContext.java    From junit-servers with MIT License 4 votes vote down vote up
@Override
public boolean isAnnotated(Class<? extends Annotation> annotationType) {
	return AnnotationUtils.isAnnotated(parameter, annotationType);
}
 
Example #25
Source File: FakeParameterContext.java    From junit-servers with MIT License 4 votes vote down vote up
@Override
public <A extends Annotation> Optional<A> findAnnotation(Class<A> annotationType) {
	return AnnotationUtils.findAnnotation(parameter, annotationType);
}
 
Example #26
Source File: FakeParameterContext.java    From junit-servers with MIT License 4 votes vote down vote up
@Override
public <A extends Annotation> List<A> findRepeatableAnnotations(Class<A> annotationType) {
	return AnnotationUtils.findRepeatableAnnotations(parameter, annotationType);
}
 
Example #27
Source File: DualPlannerExtension.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supportsTestTemplate(ExtensionContext context) {
    return AnnotationUtils.isAnnotated(context.getTestMethod(), DualPlannerTest.class) &&
           FDBRecordStoreQueryTestBase.class.isAssignableFrom(context.getRequiredTestClass());
}