下面列出了org.junit.jupiter.api.extension.ExtensionConfigurationException#org.junit.platform.commons.support.AnnotationSupport 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
@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();
}
}
@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);
}
}
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);
}
@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));
}
@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);
}
}
}
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;
}
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);
}
@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);
}
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());
}
@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);
});
}
@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;
};
}
@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());
}
}
@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);
}
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;
}
@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"));
}