org.junit.jupiter.api.extension.ExtensionContext Java Examples
The following examples show how to use
org.junit.jupiter.api.extension.ExtensionContext.
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: ProjectManagerExtension.java From centraldogma with Apache License 2.0 | 6 votes |
/** * 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(); }
Example #2
Source File: MySQLStorageExtension.java From zipkin-dependencies with Apache License 2.0 | 6 votes |
@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()); } }
Example #3
Source File: FlowableEventExtension.java From flowable-engine with Apache License 2.0 | 6 votes |
/** * 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; } } ); }
Example #4
Source File: DualDatabaseTestInvocationContextProvider.java From nomulus with Apache License 2.0 | 6 votes |
@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); }
Example #5
Source File: DockerDriverHandler.java From selenium-jupiter with Apache License 2.0 | 6 votes |
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; }
Example #6
Source File: AssumeOpenshiftCondition.java From enmasse with Apache License 2.0 | 6 votes |
@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"); }
Example #7
Source File: AbstractResourceSetGlobalCompilationExtension.java From sarl with Apache License 2.0 | 6 votes |
/** 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); }
Example #8
Source File: ClientUtils.java From enmasse with Apache License 2.0 | 6 votes |
/** * 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); } } } ; } }
Example #9
Source File: DisabledOnQAEnvironmentExtension.java From tutorials with MIT License | 6 votes |
@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"); }
Example #10
Source File: CassandraClusterExtension.java From james-project with Apache License 2.0 | 5 votes |
@Override public void beforeEach(ExtensionContext extensionContext) throws Exception { DockerCassandraSingleton.incrementTestsPlayed(); DockerCassandraSingleton.restartAfterMaxTestsPlayed( cassandraCluster::close, this::start); }
Example #11
Source File: TimingExtension.java From Mastering-Software-Testing-with-JUnit-5 with MIT License | 5 votes |
@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); }
Example #12
Source File: InvalidPersonParameterResolver.java From tutorials with MIT License | 5 votes |
@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; }
Example #13
Source File: CassandraExtension.java From calcite with Apache License 2.0 | 5 votes |
/** * Register cassandra resource in root context so it can be shared with other tests */ private static CassandraResource getOrCreate(ExtensionContext context) { // same cassandra instance should be shared across all extension instances return context.getRoot() .getStore(NAMESPACE) .getOrComputeIfAbsent(KEY, key -> new CassandraResource(), CassandraResource.class); }
Example #14
Source File: Stores.java From skywalking with Apache License 2.0 | 5 votes |
public static ExtensionContext.Store store(final ExtensionContext context) { final ExtensionContext.Namespace namespace = ExtensionContext.Namespace.create( context.getRequiredTestClass(), context.getRequiredTestMethod() ); return context.getRoot().getStore(namespace); }
Example #15
Source File: QuarkusTestExtension.java From quarkus with Apache License 2.0 | 5 votes |
@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; } }
Example #16
Source File: CucumberReportAdapter.java From openCypher with Apache License 2.0 | 5 votes |
@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())); }
Example #17
Source File: StepMethodOrderer.java From demo-junit-5 with Creative Commons Zero v1.0 Universal | 5 votes |
@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; }
Example #18
Source File: BenchmarkExtension.java From demo-junit-5 with Creative Commons Zero v1.0 Universal | 5 votes |
@Override public void afterAll(ExtensionContext context) { if (!shouldBeBenchmarked(context)) return; long launchTime = loadLaunchTime(context, LaunchTimeKey.CLASS); long elapsedTime = currentTimeMillis() - launchTime; report("Test container", context, elapsedTime); }
Example #19
Source File: QuarkusTestExtension.java From quarkus with Apache License 2.0 | 5 votes |
@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(); }
Example #20
Source File: MediaDriverTestWatcher.java From aeron with Apache License 2.0 | 5 votes |
public void testSuccessful(final ExtensionContext context) { if (TestMediaDriver.shouldRunCMediaDriver()) { deleteFiles(); } }
Example #21
Source File: AbstractEventLoopGroupExtension.java From armeria with Apache License 2.0 | 5 votes |
@Override public void before(ExtensionContext context) throws Exception { try { delegate.before(); } catch (Throwable t) { throw new RuntimeException("Failed to set up before callback", t); } }
Example #22
Source File: TemporaryFolderExtension.java From p4ic4idea with Apache License 2.0 | 5 votes |
private TemporaryFolder createFolder(ExtensionContext extensionContext) throws IOException { TemporaryFolder folder = new TemporaryFolder(); folder.prepare(); getFolders(extensionContext).add(folder); return folder; }
Example #23
Source File: DbUnitInitializerRule.java From mycollab with GNU Affero General Public License v3.0 | 5 votes |
@Override public void afterEach(ExtensionContext extensionContext) { if (databaseTester != null) { try { databaseTester.onTearDown(); } catch (Exception e) { throw new TestException(e); } } }
Example #24
Source File: InternalFlowableExtension.java From flowable-engine with Apache License 2.0 | 5 votes |
@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); }
Example #25
Source File: ExpectedExceptionExtension.java From demo-junit-5 with Creative Commons Zero v1.0 Universal | 5 votes |
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; }
Example #26
Source File: SpringExtension.java From spring-analysis-note with MIT License | 5 votes |
/** * Delegates to {@link TestContextManager#afterTestClass}. */ @Override public void afterAll(ExtensionContext context) throws Exception { try { getTestContextManager(context).afterTestClass(); } finally { getStore(context).remove(context.getRequiredTestClass()); } }
Example #27
Source File: AppExtension.java From jweb-cms with GNU Affero General Public License v3.0 | 5 votes |
@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); }
Example #28
Source File: MeecrowaveExtension.java From openwebbeans-meecrowave with Apache License 2.0 | 5 votes |
@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(); } }
Example #29
Source File: PublishedEventsParameterResolver.java From moduliths with Apache License 2.0 | 5 votes |
@Override public PublishedEvents resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { DefaultPublishedEvents publishedEvents = new DefaultPublishedEvents(); listener.registerDelegate(publishedEvents); return publishedEvents; }
Example #30
Source File: LoggingTestExtension.java From ogham with Apache License 2.0 | 5 votes |
@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()); } }