类org.junit.platform.commons.support.AnnotationSupport源码实例Demo

下面列出了怎么用org.junit.platform.commons.support.AnnotationSupport的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: microshed-testing   文件: ContainerGroup.java
private Set<GenericContainer<?>> discoverContainers(Class<?> clazz) {
    Set<GenericContainer<?>> discoveredContainers = new HashSet<>();
    for (Field containerField : AnnotationSupport.findAnnotatedFields(clazz, Container.class)) {
        if (!Modifier.isPublic(containerField.getModifiers()))
            throw new ExtensionConfigurationException("@Container annotated fields must be public visibility");
        if (!Modifier.isStatic(containerField.getModifiers()))
            throw new ExtensionConfigurationException("@Container annotated fields must be static");
        boolean isStartable = GenericContainer.class.isAssignableFrom(containerField.getType());
        if (!isStartable)
            throw new ExtensionConfigurationException("@Container annotated fields must be a subclass of " + GenericContainer.class);
        try {
            GenericContainer<?> startableContainer = (GenericContainer<?>) containerField.get(null);
            discoveredContainers.add(startableContainer);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            LOG.warn("Unable to access field " + containerField, e);
        }
    }
    return discoveredContainers;
}
 
private Set<GenericContainer<?>> discoverContainers(Class<?> clazz) {
    Set<GenericContainer<?>> discoveredContainers = new HashSet<>();
    for (Field containerField : AnnotationSupport.findAnnotatedFields(clazz, Container.class)) {
        if (!Modifier.isPublic(containerField.getModifiers()))
            throw new ExtensionConfigurationException("@Container annotated fields must be public visibility");
        if (!Modifier.isStatic(containerField.getModifiers()))
            throw new ExtensionConfigurationException("@Container annotated fields must be static");
        boolean isStartable = GenericContainer.class.isAssignableFrom(containerField.getType());
        if (!isStartable)
            throw new ExtensionConfigurationException("@Container annotated fields must be a subclass of " + GenericContainer.class);
        try {
            GenericContainer<?> startableContainer = (GenericContainer<?>) containerField.get(null);
            discoveredContainers.add(startableContainer);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            LOG.warn("Unable to access field " + containerField, e);
        }
    }
    return discoveredContainers;
}
 
private static void injectRestClients(Class<?> clazz, TestcontainersConfiguration config) throws Exception {
    List<Field> restClientFields = AnnotationSupport.findAnnotatedFields(clazz, Inject.class);
    if (restClientFields.size() == 0)
        return;

    String mpAppURL = config.getApplicationURL();

    for (Field restClientField : restClientFields) {
        if (!Modifier.isPublic(restClientField.getModifiers()) ||
            !Modifier.isStatic(restClientField.getModifiers()) ||
            Modifier.isFinal(restClientField.getModifiers())) {
            throw new ExtensionConfigurationException("REST-client field must be public, static, and non-final: " + restClientField.getName());
        }
        String jwt = createJwtIfNeeded(restClientField);
        Object restClient = JAXRSUtilities.createRestClient(restClientField.getType(), mpAppURL, jwt);
        //Object restClient = JAXRSUtilities.createRestClient(restClientField.getType(), mpAppURL);
        restClientField.set(null, restClient);
        LOGGER.debug("Injecting rest client for " + restClientField);
    }
}
 
源代码4 项目: flowable-engine   文件: FlowableExtension.java
@Override
public void beforeEach(ExtensionContext context) throws Exception {
    FlowableTestHelper flowableTestHelper = getTestHelper(context);
    FlowableMockSupport mockSupport = flowableTestHelper.getMockSupport();

    if (mockSupport != null) {
        AnnotationSupport.findRepeatableAnnotations(context.getRequiredTestClass(), MockServiceTask.class)
            .forEach(mockServiceTask -> TestHelper.handleMockServiceTaskAnnotation(mockSupport, mockServiceTask));
        AnnotationSupport.findRepeatableAnnotations(context.getRequiredTestMethod(), MockServiceTask.class)
            .forEach(mockServiceTask -> TestHelper.handleMockServiceTaskAnnotation(mockSupport, mockServiceTask));
        AnnotationSupport.findAnnotation(context.getRequiredTestMethod(), NoOpServiceTasks.class)
            .ifPresent(noOpServiceTasks -> TestHelper.handleNoOpServiceTasksAnnotation(mockSupport, noOpServiceTasks));
    }

    AnnotationSupport.findAnnotation(context.getTestMethod(), Deployment.class)
        .ifPresent(deployment -> {
            String deploymentIdFromDeploymentAnnotation = TestHelper
                .annotationDeploymentSetUp(flowableTestHelper.getProcessEngine(), context.getRequiredTestClass(), context.getRequiredTestMethod(),
                    deployment);
            flowableTestHelper.setDeploymentIdFromDeploymentAnnotation(deploymentIdFromDeploymentAnnotation);
        });

}
 
protected void doFinally(ExtensionContext context, TestInstance.Lifecycle lifecycleForClean) {
    FormEngine formEngine = getFormEngine(context);
    FormEngineConfiguration formEngineConfiguration = formEngine.getFormEngineConfiguration();
    try {
        String annotationDeploymentKey = context.getUniqueId() + ANNOTATION_DEPLOYMENT_ID_KEY;
        String deploymentIdFromDeploymentAnnotation = getStore(context).get(annotationDeploymentKey, String.class);
        if (deploymentIdFromDeploymentAnnotation != null) {
            FormTestHelper.annotationDeploymentTearDown(formEngine, deploymentIdFromDeploymentAnnotation, context.getRequiredTestClass(),
                context.getRequiredTestMethod().getName());
            getStore(context).remove(annotationDeploymentKey);
        }

        AnnotationSupport.findAnnotation(context.getTestMethod(), CleanTest.class)
            .ifPresent(cleanTest -> removeDeployments(formEngine.getFormRepositoryService()));
        if (context.getTestInstanceLifecycle().orElse(TestInstance.Lifecycle.PER_METHOD) == lifecycleForClean) {
            cleanTestAndAssertAndEnsureCleanDb(context, formEngine);
        }

    } finally {
        formEngineConfiguration.getClock().reset();
    }
}
 
源代码6 项目: flowable-engine   文件: FlowableEventExtension.java
@Override
public void beforeEach(ExtensionContext context) {
    Optional<EventDeploymentAnnotation> optionalEventDeploymentAnnotation = AnnotationSupport.findAnnotation(
                    context.getTestMethod(), EventDeploymentAnnotation.class);
    
    Optional<ChannelDeploymentAnnotation> optionalChannelDeploymentAnnotation = AnnotationSupport.findAnnotation(
                    context.getTestMethod(), ChannelDeploymentAnnotation.class);
    
    if (optionalEventDeploymentAnnotation.isPresent() || optionalChannelDeploymentAnnotation.isPresent()) {
        EventDeploymentAnnotation eventDeploymentAnnotation = null;
        if (optionalEventDeploymentAnnotation.isPresent()) {
            eventDeploymentAnnotation = optionalEventDeploymentAnnotation.get();
        }
        
        ChannelDeploymentAnnotation channelDeploymentAnnotation = null;
        if (optionalChannelDeploymentAnnotation.isPresent()) {
            channelDeploymentAnnotation = optionalChannelDeploymentAnnotation.get();
        }
        
        FlowableEventTestHelper testHelper = getTestHelper(context);
        String deploymentIdFromDeploymentAnnotation = EventTestHelper
            .annotationDeploymentSetUp(testHelper.getEventRepositoryService(), context.getRequiredTestClass(), context.getRequiredTestMethod(),
                            eventDeploymentAnnotation, channelDeploymentAnnotation);
        testHelper.setDeploymentIdFromDeploymentAnnotation(deploymentIdFromDeploymentAnnotation);
    }
}
 
源代码7 项目: bootique   文件: BQTestExtension.java
protected Predicate<Field> isRunnable() {
    return f -> {

        // provide diagnostics for misapplied or missing annotations
        // TODO: will it be actually more useful to throw instead of print a warning?
        if (AnnotationSupport.isAnnotated(f, BQApp.class)) {

            if (!BQRuntime.class.isAssignableFrom(f.getType())) {
                logger.warn(() -> "Field '" + f.getName() + "' is annotated with @BQRun but is not a BQRuntime. Ignoring...");
                return false;
            }

            if (!ReflectionUtils.isStatic(f)) {
                logger.warn(() -> "BQRuntime field '" + f.getName() + "' is annotated with @BQRun but is not static. Ignoring...");
                return false;
            }

            return true;
        }

        return false;
    };
}
 
@Override
protected DropwizardTestSupport<?> prepareTestSupport(final ExtensionContext context) {
    if (config == null) {
        // Configure from annotation
        // Note that it is impossible to have both manually build config and annotation because annotation
        // will be processed first and manual registration will be simply ignored

        final TestGuiceyApp ann = AnnotationSupport
                // also search annotation inside other annotations (meta)
                .findAnnotation(context.getElement(), TestGuiceyApp.class).orElse(null);

        // catch incorrect usage by direct @ExtendWith(...)
        Preconditions.checkNotNull(ann, "%s annotation not declared: can't work without configuration, "
                        + "so either use annotation or extension with @%s for manual configuration",
                TestGuiceyApp.class.getSimpleName(),
                RegisterExtension.class.getSimpleName());
        config = Config.parse(ann);
    }

    HooksUtil.register(config.hooks);

    // config overrides work through system properties so it is important to have unique prefixes
    final String configPrefix = ConfigOverrideUtils.createPrefix(context.getRequiredTestClass());
    return create(context, config.app, config.configPath, configPrefix, config.configOverrides);
}
 
@Override
public ConditionEvaluationResult evaluate(TestExtensionContext context) {
    Properties props = new Properties();
    String env = "";
    try {
        props.load(ConnectionUtil.class.getResourceAsStream("/application.properties"));
        env = props.getProperty("env");
    } catch (IOException e) {
        e.printStackTrace();
    }
    Optional<DisabledOnEnvironment> disabled = AnnotationSupport.findAnnotation(context.getElement().get(), DisabledOnEnvironment.class);
    if (disabled.isPresent()) {
        String[] envs = disabled.get().value();
        if (Arrays.asList(envs).contains(env)) {
            return ConditionEvaluationResult.disabled("Disabled on environment " + env);
        }
    }

    return ConditionEvaluationResult.enabled("Enabled on environment "+env);
}
 
源代码10 项目: micronaut-test   文件: MicronautJunit5Extension.java
@Override
public void beforeAll(ExtensionContext extensionContext) throws Exception {
    final Class<?> testClass = extensionContext.getRequiredTestClass();
    final MicronautTest micronautTest = AnnotationSupport.findAnnotation(testClass, MicronautTest.class).orElse(null);
    beforeClass(extensionContext, testClass, micronautTest);
    getStore(extensionContext).put(ApplicationContext.class, applicationContext);
    if (specDefinition != null) {
        TestInstance ti = AnnotationSupport.findAnnotation(testClass, TestInstance.class).orElse(null);
        if (ti != null && ti.value() == TestInstance.Lifecycle.PER_CLASS) {
            Object testInstance = extensionContext.getRequiredTestInstance();
            applicationContext.inject(testInstance);
        }
    }
    beforeTestClass(buildContext(extensionContext));
}
 
源代码11 项目: micronaut-test   文件: MicronautJunit5Extension.java
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) {
    final Optional<Object> testInstance = extensionContext.getTestInstance();
    if (testInstance.isPresent()) {

        final Class<?> requiredTestClass = extensionContext.getRequiredTestClass();
        if (applicationContext.containsBean(requiredTestClass)) {
            return ConditionEvaluationResult.enabled("Test bean active");
        } else {

            final boolean hasBeanDefinition = isTestSuiteBeanPresent(requiredTestClass);
            if (!hasBeanDefinition) {
                throw new TestInstantiationException(MISCONFIGURED_MESSAGE);
            } else {
                return ConditionEvaluationResult.disabled(DISABLED_MESSAGE);
            }

        }
    } else {
        final Class<?> testClass = extensionContext.getRequiredTestClass();
        if (AnnotationSupport.isAnnotated(testClass, MicronautTest.class)) {
            return ConditionEvaluationResult.enabled("Test bean active");
        } else {
            return ConditionEvaluationResult.disabled(DISABLED_MESSAGE);
        }
    }
}
 
源代码12 项目: wiremock-extension   文件: WireMockExtension.java
private static <A extends Annotation> Optional<A> retrieveAnnotation(final ExtensionContext context,
                                                                     final Class<A> annotationType) {

	Optional<ExtensionContext> currentContext = Optional.of(context);
	Optional<A> annotation = Optional.empty();

	while (currentContext.isPresent() && !annotation.isPresent()) {
		annotation = AnnotationSupport.findAnnotation(currentContext.get().getElement(), annotationType);
		currentContext = currentContext.get().getParent();
	}
	return annotation;
}
 
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    Optional<RequireSystemProperty> annotation = AnnotationSupport.findAnnotation(context.getElement(), RequireSystemProperty.class);
    if (annotation.isPresent()) {
        for (String propertyKey : annotation.get().value()) {
            String propertyValue = System.getProperty(propertyKey);
            if (propertyValue == null || propertyValue.isEmpty()) {
                return ConditionEvaluationResult.disabled(String.format("System property '%s' not set. Skipping test.", propertyKey));
            }
        }
        return ConditionEvaluationResult.enabled("All required system properties present. Continuing test.");
    }
    return ConditionEvaluationResult.enabled("No RequireSystemProperty annotation found. Continuing test.");
}
 
private MicroProfileApplication<?> autoDiscoverMPApp(Class<?> clazz, boolean errorIfNone) {
    // First check for any MicroProfileApplicaiton directly present on the test class
    List<Field> mpApps = AnnotationSupport.findAnnotatedFields(clazz, Container.class,
                                                               f -> Modifier.isStatic(f.getModifiers()) &&
                                                                    Modifier.isPublic(f.getModifiers()) &&
                                                                    MicroProfileApplication.class.isAssignableFrom(f.getType()),
                                                               HierarchyTraversalMode.TOP_DOWN);
    if (mpApps.size() == 1)
        try {
            return (MicroProfileApplication<?>) mpApps.get(0).get(null);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            // This should never happen because we only look for fields that are public+static
            e.printStackTrace();
        }
    if (mpApps.size() > 1)
        throw new ExtensionConfigurationException("Should be no more than 1 public static MicroProfileApplication field on " + clazz);

    // If none found, check any SharedContainerConfig
    String sharedConfigMsg = "";
    if (sharedConfigClass != null) {
        MicroProfileApplication<?> mpApp = autoDiscoverMPApp(sharedConfigClass, false);
        if (mpApp != null)
            return mpApp;
        sharedConfigMsg = " or " + sharedConfigClass;
    }

    if (errorIfNone)
        throw new ExtensionConfigurationException("No public static MicroProfileApplication fields annotated with @Container were located " +
                                                  "on " + clazz + sharedConfigMsg + " to auto-connect with REST-client fields.");
    return null;
}
 
源代码15 项目: microprofile-sandbox   文件: JAXRSUtilities.java
public static <T> T createRestClient(Class<T> clazz, String appContextRoot, String jwt) {
    String resourcePackage = clazz.getPackage().getName();

    // First check for a javax.ws.rs.core.Application in the same package as the resource
    List<Class<?>> appClasses = ReflectionSupport.findAllClassesInPackage(resourcePackage,
                                                                          c -> Application.class.isAssignableFrom(c) &&
                                                                               AnnotationSupport.isAnnotated(c, ApplicationPath.class),
                                                                          n -> true);
    if (appClasses.size() == 0) {
        // If not found, check under the 3rd package, so com.foo.bar.*
        // Classpath scanning can be expensive, so we jump straight to the 3rd package from root instead
        // of recursing up one package at a time and scanning the entire CP for each step
        String[] pkgs = resourcePackage.split("(.*)\\.(.*)\\.(.*)\\.", 2);
        if (pkgs.length > 0 && !pkgs[0].isEmpty() && !pkgs[0].equals(resourcePackage)) {
            appClasses = ReflectionSupport.findAllClassesInPackage(pkgs[0],
                                                                   c -> Application.class.isAssignableFrom(c) &&
                                                                        AnnotationSupport.isAnnotated(c, ApplicationPath.class),
                                                                   n -> true);
        }
    }

    if (appClasses.size() == 0) {
        LOGGER.info("No classes implementing 'javax.ws.rs.core.Application' found on classpath to set as context root for " + clazz +
                    ". Defaulting context root to '/'");
        return createRestClient(clazz, appContextRoot, "", jwt);
    }

    Class<?> selectedClass = appClasses.get(0);
    if (appClasses.size() > 1) {
        appClasses.sort((c1, c2) -> c1.getCanonicalName().compareTo(c2.getCanonicalName()));
        LOGGER.warn("Found multiple classes implementing 'javax.ws.rs.core.Application' on classpath: " + appClasses +
                    ". Setting context root to the first class discovered (" + selectedClass.getCanonicalName() + ")");
    }
    ApplicationPath appPath = AnnotationSupport.findAnnotation(selectedClass, ApplicationPath.class).get();
    return createRestClient(clazz, appContextRoot, appPath.value(), jwt);
}
 
源代码16 项目: taskana   文件: JaasExtension.java
@Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(
    ExtensionContext context) {
  List<WithAccessId> accessIds =
      AnnotationSupport.findRepeatableAnnotations(context.getElement(), WithAccessId.class);
  Store store = getStore(context);
  return accessIds.stream()
      .peek(a -> store.put(ACCESS_IDS_STORE_KEY, a))
      .map(JaasExtensionInvocationContext::new);
}
 
源代码17 项目: ArchUnit   文件: AbstractArchUnitTestDescriptor.java
AbstractArchUnitTestDescriptor(UniqueId uniqueId, String displayName, TestSource source, AnnotatedElement... elements) {
    super(uniqueId, displayName, source);
    tags = Arrays.stream(elements).map(this::findTagsOn).flatMap(Collection::stream).collect(toSet());
    skipResult = Arrays.stream(elements)
            .map(e -> AnnotationSupport.findAnnotation(e, ArchIgnore.class))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .findFirst()
            .map(ignore -> SkipResult.skip(ignore.reason()))
            .orElse(SkipResult.doNotSkip());
}
 
源代码18 项目: flowable-engine   文件: FlowableCmmnExtension.java
@Override
public void beforeEach(ExtensionContext context) {
    FlowableCmmnTestHelper flowableTestHelper = getTestHelper(context);

    AnnotationSupport.findAnnotation(context.getTestMethod(), CmmnDeployment.class)
        .ifPresent(deployment -> {
            String deploymentIdFromDeploymentAnnotation = CmmnTestHelper
                .annotationDeploymentSetUp(flowableTestHelper.getCmmnEngine(), context.getRequiredTestClass(), context.getRequiredTestMethod(),
                    deployment);
            flowableTestHelper.setDeploymentIdFromDeploymentAnnotation(deploymentIdFromDeploymentAnnotation);
        });

}
 
@Override
public void afterEach(ExtensionContext context) throws Exception {
    try {
        super.afterEach(context);
    } finally {
        if (AnnotationSupport.isAnnotated(context.getRequiredTestClass(), EnableVerboseExecutionTreeLogging.class)) {
            swapCommandInvoker(getProcessEngine(context), false);
        }
    }
}
 
@Override
protected ProcessEngine getProcessEngine(ExtensionContext context) {
    ProcessEngine processEngine = getStore(context).getOrComputeIfAbsent(PROCESS_ENGINE, key -> initializeProcessEngine(), ProcessEngine.class);

    // Enable verbose execution tree debugging if needed
    Class<?> testClass = context.getRequiredTestClass();
    if (AnnotationSupport.isAnnotated(testClass, EnableVerboseExecutionTreeLogging.class)) {
        swapCommandInvoker(processEngine, true);
    }
    return processEngine;
}
 
@Override
public void beforeEach(ExtensionContext context) {
    ProcessEngine processEngine = getProcessEngine(context);

    AnnotationSupport.findAnnotation(context.getTestMethod(), Deployment.class)
        .ifPresent(deployment -> {
            String deploymentIdFromDeploymentAnnotation = TestHelper
                .annotationDeploymentSetUp(processEngine, context.getRequiredTestClass(), context.getRequiredTestMethod(), deployment);
            getStore(context).put(context.getUniqueId() + ANNOTATION_DEPLOYMENT_ID_KEY, deploymentIdFromDeploymentAnnotation);
        });
}
 
@Override
public void beforeEach(ExtensionContext context) {
    FormEngine formEngine = getFormEngine(context);

    AnnotationSupport.findAnnotation(context.getTestMethod(), FormDeploymentAnnotation.class)
        .ifPresent(deployment -> {
            String deploymentIdFromDeploymentAnnotation = FormTestHelper
                .annotationDeploymentSetUp(formEngine, context.getRequiredTestClass(), context.getRequiredTestMethod(), deployment);
            getStore(context).put(context.getUniqueId() + ANNOTATION_DEPLOYMENT_ID_KEY, deploymentIdFromDeploymentAnnotation);
        });
}
 
源代码23 项目: flowable-engine   文件: FlowableFormExtension.java
@Override
public void beforeEach(ExtensionContext context) {
    AnnotationSupport.findAnnotation(context.getTestMethod(), FormDeploymentAnnotation.class)
        .ifPresent(deployment -> {
            FlowableFormTestHelper testHelper = getTestHelper(context);
            String deploymentIdFromDeploymentAnnotation = FormTestHelper
                .annotationDeploymentSetUp(testHelper.getFormEngine(), context.getRequiredTestClass(), context.getRequiredTestMethod(),
                    deployment);
            testHelper.setDeploymentIdFromDeploymentAnnotation(deploymentIdFromDeploymentAnnotation);
        });

}
 
private static Predicate<Field> isContainer() {
    return field -> {
        boolean isAnnotatedWithContainer = AnnotationSupport.isAnnotated(field, Container.class);
        if (isAnnotatedWithContainer) {
            boolean isStartable = Startable.class.isAssignableFrom(field.getType());

            if (!isStartable) {
                throw new ExtensionConfigurationException(String.format("FieldName: %s does not implement Startable", field.getName()));
            }
            return true;
        }
        return false;
    };
}
 
源代码25 项目: ogham   文件: LoggingTestExtension.java
@Override
public void beforeAll(ExtensionContext context) throws InstantiationException, IllegalAccessException {
	if (logger != null) {
		return;
	}
	LogTestInformation annotation = AnnotationSupport.findAnnotation(context.getElement(), LogTestInformation.class).orElse(null);
	if (annotation == null) {
		logger = new TestInformationLogger();
	} else {
		logger = new TestInformationLogger(annotation.maxLength(), annotation.marker(), annotation.printer().newInstance());
	}
}
 
源代码26 项目: dropwizard-guicey   文件: TestParametersSupport.java
@Override
@SuppressWarnings("checkstyle:ReturnCount")
public boolean supportsParameter(final ParameterContext parameterContext,
                                 final ExtensionContext extensionContext) throws ParameterResolutionException {
    final Parameter parameter = parameterContext.getParameter();
    if (parameter.getAnnotations().length > 0) {
        if (AnnotationSupport.isAnnotated(parameter, Jit.class)) {
            return true;
        } else if (!isQualifierAnnotation(parameter.getAnnotations())) {
            // if any other annotation declared on the parameter - skip it (possibly other extension's parameter)
            return false;
        }
    }

    final Class<?> type = parameter.getType();
    if (Application.class.isAssignableFrom(type) || Configuration.class.isAssignableFrom(type)) {
        // special case when exact app or configuration class used
        return true;
    } else {
        for (Class<?> cls : supportedClasses) {
            if (type.equals(cls)) {
                return true;
            }
        }
    }

    // declared guice binding (by class only)
    return getInjector(extensionContext)
            .map(it -> it.getExistingBinding(getKey(parameter)) != null)
            .orElse(false);
}
 
源代码27 项目: dropwizard-guicey   文件: TestParametersSupport.java
private Key<?> getKey(final Parameter parameter) {
    final Key<?> key;
    if (parameter.getAnnotations().length > 0
            && !AnnotationSupport.isAnnotated(parameter, Jit.class)) {
        // qualified bean
        key = Key.get(parameter.getParameterizedType(), parameter.getAnnotations()[0]);
    } else {
        key = Key.get(parameter.getParameterizedType());
    }
    return key;
}
 
@SuppressWarnings({"unchecked", "checkstyle:Indentation"})
private void activateFieldHooks(final Class<?> testClass) {
    final List<Field> fields = AnnotationSupport.findAnnotatedFields(testClass, EnableHook.class);
    HooksUtil.validateFieldHooks(fields);
    if (!fields.isEmpty()) {
        HooksUtil.register((List<GuiceyConfigurationHook>)
                (List) ReflectionUtils.readFieldValues(fields, null));
    }
}
 
@Override
@SuppressWarnings("unchecked")
protected DropwizardTestSupport<?> prepareTestSupport(final ExtensionContext context) {
    if (config == null) {
        // Configure from annotation
        // Note that it is impossible to have both manually build config and annotation because annotation
        // will be processed first and manual registration will be simply ignored

        final TestDropwizardApp ann = AnnotationSupport
                // also search annotation inside other annotations (meta)
                .findAnnotation(context.getElement(), TestDropwizardApp.class).orElse(null);

        // catch incorrect usage by direct @ExtendWith(...)
        Preconditions.checkNotNull(ann, "%s annotation not declared: can't work without configuration, "
                        + "so either use annotation or extension with @%s for manual configuration",
                TestDropwizardApp.class.getSimpleName(),
                RegisterExtension.class.getSimpleName());

        config = Config.parse(ann);
    }

    HooksUtil.register(config.hooks);

    // config overrides work through system properties so it is important to have unique prefixes
    final String configPrefix = ConfigOverrideUtils.createPrefix(context.getRequiredTestClass());
    final DropwizardTestSupport support = new DropwizardTestSupport(config.app,
            config.configPath,
            configPrefix,
            buildConfigOverrides(configPrefix));

    if (config.randomPorts) {
        support.addListener(new RandomPortsListener());
    }
    return support;
}
 
源代码30 项目: calcite   文件: RequiresNetworkExtension.java
@Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
  return context.getElement()
      .flatMap(element -> AnnotationSupport.findAnnotation(element, RequiresNetwork.class))
      .map(net -> {
        try (Socket ignored = new Socket(net.host(), net.port())) {
          return enabled(net.host() + ":" + net.port() + " is reachable");
        } catch (Exception e) {
          return disabled(net.host() + ":" + net.port() + " is unreachable: " + e.getMessage());
        }
      })
      .orElseGet(() -> enabled("@RequiresNetwork is not found"));
}
 
 类所在包
 同包方法