下面列出了org.junit.jupiter.api.extension.ParameterResolver#org.junit.jupiter.api.extension.ExtensionContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Get the compilation context.
*
* @param context the extension context.
* @return the compilation context.
*/
ResourceSetGlobalCompilationContext getOrCreateCompilationContext(ExtensionContext context) {
final ExtensionContext root = context.getRoot();
return root.getStore(NAMESPACE).getOrComputeIfAbsent(
ResourceSetGlobalCompilationExtension.CONTEXT_KEY,
it -> {
final ResourceSetGlobalCompilationContext ctx = new ResourceSetGlobalCompilationContext(
context.getRequiredTestClass().getPackage().getName() + ".tests",
this.injector, this.parseHelper, this.validator);
final GlobalCompilationTestContribution anno = context.getRequiredTestClass().getAnnotation(GlobalCompilationTestContribution.class);
if (anno != null) {
ctx.setValidationRunInEachTestFunction(anno.getValidate());
}
return ctx;
},
ResourceSetGlobalCompilationContext.class);
}
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
Properties properties = new Properties();
try {
properties.load(DisabledOnQAEnvironmentExtension.class.getClassLoader()
.getResourceAsStream("application.properties"));
if ("qa".equalsIgnoreCase(properties.getProperty("env"))) {
String reason = String.format("The test '%s' is disabled on QA environment", context.getDisplayName());
System.out.println(reason);
return ConditionEvaluationResult.disabled(reason);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return ConditionEvaluationResult.enabled("Test enabled");
}
/**
* stop all clients from list of Abstract clients
*
* @throws Exception
*/
public void stopClients(List<ExternalMessagingClient> clients, ExtensionContext context) throws Exception {
if (clients != null) {
LOGGER.info("Stopping clients...");
Path logsDir = Files.createDirectories(TestUtils.getFailedTestLogsPath(context).resolve(SystemtestsKubernetesApps.MESSAGING_PROJECT));
if (context.getExecutionException().isPresent()) {
LOGGER.info("Saving clients output into {}", logsDir.toString());
}
for (var c : clients) {
c.stop();
if (context.getExecutionException().isPresent()) {
try {
Files.write(logsDir.resolve(c.getId() + "-output.log"), c.getStdOutput().getBytes());
Files.write(logsDir.resolve(c.getId() + "-error.log"), c.getStdError().getBytes());
} catch (Exception ex) {
LOGGER.warn("Cannot save output of client " + c.getId(), ex);
}
}
}
;
}
}
public DockerDriverHandler(ExtensionContext context, Parameter parameter,
Optional<Object> testInstance, AnnotationsReader annotationsReader,
Map<String, DockerContainer> containerMap,
DockerService dockerService, Config config,
BrowserInstance browserInstance, String version) {
this.context = context;
this.parameter = parameter;
this.testInstance = testInstance;
this.annotationsReader = annotationsReader;
this.containerMap = containerMap;
this.finalizerCommandMap = new LinkedHashMap<>();
this.dockerService = dockerService;
this.config = config;
this.selenoidConfig = new SelenoidConfig(getConfig(), browserInstance,
version);
this.browserVersion = version;
}
/**
* Each test is assumed to clean up all DB content it entered. After a test method executed, this method scans all tables to see if the DB is completely clean. It throws AssertionFailed in case
* the DB is not clean. If the DB is not clean, it is cleaned by performing a create a drop.
*/
protected void assertAndEnsureCleanDb(EventRegistryEngine eventRegistryEngine, ExtensionContext context, EnsureCleanDb ensureCleanDb) {
EnsureCleanDbUtils.assertAndEnsureCleanDb(
context.getDisplayName(),
logger,
eventRegistryEngine.getEventRegistryEngineConfiguration(),
ensureCleanDb,
!context.getExecutionException().isPresent(),
new Command<Void>() {
@Override
public Void execute(CommandContext commandContext) {
SchemaManager schemaManager = CommandContextUtil.getEventRegistryConfiguration(commandContext).getSchemaManager();
schemaManager.schemaDrop();
schemaManager.schemaCreate();
return null;
}
}
);
}
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context)
throws Exception {
List<Field> appEngineRuleFields =
Stream.of(testInstance.getClass().getFields())
.filter(field -> field.getType().isAssignableFrom(AppEngineRule.class))
.collect(toImmutableList());
if (appEngineRuleFields.size() != 1) {
throw new IllegalStateException(
"@DualDatabaseTest test must have only 1 AppEngineRule field");
}
appEngineRuleFields.get(0).setAccessible(true);
AppEngineRule appEngineRule = (AppEngineRule) appEngineRuleFields.get(0).get(testInstance);
if (!appEngineRule.isWithDatastoreAndCloudSql()) {
throw new IllegalStateException(
"AppEngineRule in @DualDatabaseTest test must set withDatastoreAndCloudSql()");
}
context.getStore(NAMESPACE).put(INJECTED_TM_SUPPLIER_KEY, tmSupplier);
}
@Override public void beforeAll(ExtensionContext context) {
if (!"true".equals(System.getProperty("docker.skip"))) {
try {
container = new ZipkinMySQLContainer(image);
container.start();
LOGGER.info("Starting docker image " + container.getDockerImageName());
} catch (Exception e) {
LOGGER.warn("Couldn't start docker image " + container.getDockerImageName(), e);
}
} else {
LOGGER.info("Skipping startup of docker");
}
try (MySQLStorage result = computeStorageBuilder().build()) {
CheckResult check = result.check();
assumeTrue(check.ok(), () -> "Could not connect to storage, skipping test: "
+ check.error().getMessage());
}
}
/**
* Configures an {@link Executor}, {@link ProjectManager} and {@link CommandExecutor},
* then starts the {@link CommandExecutor} and initializes internal projects.
*/
@Override
public void before(ExtensionContext context) throws Exception {
tempDir.create();
final Executor repositoryWorker = newWorker();
purgeWorker = Executors.newSingleThreadScheduledExecutor(
new DefaultThreadFactory("purge-worker", true));
projectManager = newProjectManager(repositoryWorker, purgeWorker);
executor = newCommandExecutor(projectManager, repositoryWorker);
executor.start().get();
ProjectInitializer.initializeInternalProject(executor);
afterExecutorStarted();
}
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
Optional<OpenShift> annotation = findAnnotation(context.getElement(), OpenShift.class);
if (annotation.isPresent()) {
var version = annotation.get().version();
var type = annotation.get().type();
var multinode = type.equals(ClusterType.CRC) ? MultinodeCluster.NO : annotation.get().multinode();
if ((Kubernetes.getInstance().getCluster().toString().equals(ClusterType.OPENSHIFT.toString().toLowerCase()) ||
Kubernetes.getInstance().getCluster().toString().equals(ClusterType.CRC.toString().toLowerCase())) &&
(version == OpenShiftVersion.WHATEVER || version == Kubernetes.getInstance().getOcpVersion()) &&
(multinode == MultinodeCluster.WHATEVER || multinode == Kubernetes.getInstance().isClusterMultinode())) {
return ConditionEvaluationResult.enabled("Test is supported on current cluster");
} else {
return ConditionEvaluationResult.disabled("Test is not supported on current cluster");
}
}
return ConditionEvaluationResult.enabled("No rule set, test is enabled");
}
private void handleCallBackError(String description, ExtensionContext context, ThrowableRunner runnable) throws Exception {
try {
runnable.run();
} catch (Exception ex) {
try {
saveKubernetesState(description, context, ex);
} catch (Throwable ignored) {
}
LOGGER.error("Exception captured in Junit callback", ex);
throw ex;
}
}
public void testSuccessful(final ExtensionContext context)
{
if (TestMediaDriver.shouldRunCMediaDriver())
{
deleteFiles();
}
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
Properties testProperties = new Properties(backup);
Arrays.stream(ArrayUtils.addAll(
context.getRequiredTestClass().getAnnotationsByType(SystemProperty.class),
context.getRequiredTestMethod().getAnnotationsByType(SystemProperty.class)))
.forEach(p -> testProperties.put(p.name(), p.value()));
System.setProperties(testProperties);
}
@Override
public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
if (isNativeTest(extensionContext)) {
invocation.proceed();
return;
}
runExtensionMethod(invocationContext, extensionContext);
invocation.skip();
}
@Override
public void beforeEach(ExtensionContext extensionContext) throws Exception {
DockerCassandraSingleton.incrementTestsPlayed();
DockerCassandraSingleton.restartAfterMaxTestsPlayed(
cassandraCluster::close,
this::start);
}
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
String testName = context.getRequiredTestMethod().getName();
DirectedNode testNode = executionOrder.stream()
.filter(node -> node.testMethod().getMethod().getName().equals(testName))
// TODO: write proper error messages
.reduce((__, ___) -> {
throw new IllegalArgumentException("");
})
.orElseThrow(IllegalArgumentException::new);
failedTests.add(testNode);
throw throwable;
}
public static ExtensionContext.Store store(final ExtensionContext context) {
final ExtensionContext.Namespace namespace = ExtensionContext.Namespace.create(
context.getRequiredTestClass(),
context.getRequiredTestMethod()
);
return context.getRoot().getStore(namespace);
}
@Override
public void beforeAll(ExtensionContext context) throws Exception {
initCucumberPlugins();
TCKEvents.feature().subscribe(adapt(featureReadEvent()));
TCKEvents.scenario().subscribe(adapt(scenarioStartedEvent()));
TCKEvents.stepStarted().subscribe(adapt(stepStartedEvent()));
TCKEvents.stepFinished().subscribe(adapt(stepFinishedEvent()));
bus.handle(new TestRunStarted(time()));
}
@Override
public void handleTestExecutionException(ExtensionContext extensionContext, Throwable throwable) {
if (!(throwable instanceof RetryException)) {
retry(() -> extensionContext.getRequiredTestMethod()
.invoke(extensionContext.getRequiredTestInstance()));
}
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
boolean ret = false;
//
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
if (parameterContext.getParameter()
.getType() == Person.class) {
ret = true;
}
return ret;
}
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
Method testMethod = context.getRequiredTestMethod();
long start = getStore(context).remove(testMethod, long.class);
long duration = System.currentTimeMillis() - start;
log.info("Method {} took {} ms", testMethod.getName(), duration);
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
if (isNativeTest(context)) {
return;
}
if (!failedBoot) {
ClassLoader original = setCCL(runningQuarkusApplication.getClassLoader());
try {
pushMockContext();
for (Object beforeEachCallback : beforeEachCallbacks) {
Map.Entry<Class<?>, ?> tuple = createQuarkusTestMethodContextTuple(context);
beforeEachCallback.getClass().getMethod("beforeEach", tuple.getKey())
.invoke(beforeEachCallback, tuple.getValue());
}
if (runningQuarkusApplication != null) {
runningQuarkusApplication.getClassLoader().loadClass(RestAssuredURLManager.class.getName())
.getDeclaredMethod("setURL", boolean.class).invoke(null, false);
runningQuarkusApplication.getClassLoader().loadClass(TestScopeManager.class.getName())
.getDeclaredMethod("setup", boolean.class).invoke(null, false);
}
} finally {
setCCL(original);
}
} else {
throwBootFailureException();
return;
}
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) {
if (parameterContext.isAnnotated(DeploymentId.class)) {
return getStore(context).get(context.getUniqueId() + ANNOTATION_DEPLOYMENT_ID_KEY, String.class);
}
return getProcessEngine(context);
}
private static EXCEPTION loadExceptionStatus(ExtensionContext context) {
EXCEPTION thrown = context.getStore(NAMESPACE).get(KEY, EXCEPTION.class);
if (thrown == null)
return EXCEPTION.WAS_NOT_THROWN;
else
return thrown;
}
@Override
public void afterAll(final ExtensionContext context) {
final ExtensionContext.Store store = context.getStore(NAMESPACE);
ofNullable(store.get(LifecyleState.class, LifecyleState.class))
.ifPresent(s -> s.afterLastTest(context));
if (isPerClass(context)) {
store.get(Meecrowave.class, Meecrowave.class).close();
}
}
@Override
public PublishedEvents resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
DefaultPublishedEvents publishedEvents = new DefaultPublishedEvents();
listener.registerDelegate(publishedEvents);
return publishedEvents;
}
@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
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
ExtensionContext.Store store = context.getStore(ExtensionContext.Namespace.create(AppExtension.class, MockApp.class));
Install install = testInstance.getClass().getDeclaredAnnotation(Install.class);
if (install == null) {
throw new ApplicationException("missing @Install annotation");
}
MockApp app = (MockApp) store.getOrComputeIfAbsent(MockApp.class, type -> createApp(install.value()));
app.inject(testInstance);
}
/**
* Delegates to {@link TestContextManager#afterTestClass}.
*/
@Override
public void afterAll(ExtensionContext context) throws Exception {
try {
getTestContextManager(context).afterTestClass();
}
finally {
getStore(context).remove(context.getRequiredTestClass());
}
}
@Override
public void afterEach(ExtensionContext extensionContext) {
if (databaseTester != null) {
try {
databaseTester.onTearDown();
} catch (Exception e) {
throw new TestException(e);
}
}
}
@Override
public void before(ExtensionContext context) throws Exception {
try {
delegate.before();
} catch (Throwable t) {
throw new RuntimeException("Failed to set up before callback", t);
}
}