类org.junit.jupiter.api.extension.ExtensionContext源码实例Demo

下面列出了怎么用org.junit.jupiter.api.extension.ExtensionContext的API类实例代码及写法,或者点击链接到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");
}
 
源代码3 项目: enmasse   文件: ClientUtils.java
/**
 * 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);
                }
            }
        }
        ;
    }
}
 
源代码4 项目: selenium-jupiter   文件: DockerDriverHandler.java
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;
}
 
源代码5 项目: flowable-engine   文件: FlowableEventExtension.java
/**
 * 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());
  }
}
 
源代码8 项目: centraldogma   文件: ProjectManagerExtension.java
/**
 * 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();
}
 
源代码9 项目: enmasse   文件: AssumeOpenshiftCondition.java
@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");
}
 
源代码10 项目: enmasse   文件: JunitCallbackListener.java
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;
    }
}
 
源代码11 项目: aeron   文件: MediaDriverTestWatcher.java
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);
}
 
源代码13 项目: quarkus   文件: QuarkusTestExtension.java
@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();
}
 
源代码14 项目: james-project   文件: CassandraClusterExtension.java
@Override
public void beforeEach(ExtensionContext extensionContext) throws Exception {
    DockerCassandraSingleton.incrementTestsPlayed();
    DockerCassandraSingleton.restartAfterMaxTestsPlayed(
        cassandraCluster::close,
        this::start);
}
 
源代码15 项目: demo-junit-5   文件: StepMethodOrderer.java
@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;
}
 
源代码16 项目: skywalking   文件: Stores.java
public static ExtensionContext.Store store(final ExtensionContext context) {
    final ExtensionContext.Namespace namespace = ExtensionContext.Namespace.create(
        context.getRequiredTestClass(),
        context.getRequiredTestMethod()
    );
    return context.getRoot().getStore(namespace);
}
 
源代码17 项目: openCypher   文件: CucumberReportAdapter.java
@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()));
}
 
源代码18 项目: elepy   文件: TryAgain.java
@Override
public void handleTestExecutionException(ExtensionContext extensionContext, Throwable throwable) {

    if (!(throwable instanceof RetryException)) {
        retry(() -> extensionContext.getRequiredTestMethod()
                .invoke(extensionContext.getRequiredTestInstance()));
    }
}
 
源代码19 项目: tutorials   文件: InvalidPersonParameterResolver.java
@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);
}
 
源代码21 项目: quarkus   文件: QuarkusTestExtension.java
@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);
}
 
源代码23 项目: demo-junit-5   文件: ExpectedExceptionExtension.java
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;
}
 
源代码26 项目: 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());
	}
}
 
源代码27 项目: jweb-cms   文件: AppExtension.java
@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);
}
 
源代码28 项目: spring-analysis-note   文件: SpringExtension.java
/**
 * Delegates to {@link TestContextManager#afterTestClass}.
 */
@Override
public void afterAll(ExtensionContext context) throws Exception {
	try {
		getTestContextManager(context).afterTestClass();
	}
	finally {
		getStore(context).remove(context.getRequiredTestClass());
	}
}
 
源代码29 项目: mycollab   文件: DbUnitInitializerRule.java
@Override
public void afterEach(ExtensionContext extensionContext) {
    if (databaseTester != null) {
        try {
            databaseTester.onTearDown();
        } catch (Exception e) {
            throw new TestException(e);
        }
    }
}
 
源代码30 项目: armeria   文件: AbstractEventLoopGroupExtension.java
@Override
public void before(ExtensionContext context) throws Exception {
    try {
        delegate.before();
    } catch (Throwable t) {
        throw new RuntimeException("Failed to set up before callback", t);
    }
}
 
 类所在包
 同包方法