/** * Handle the supplied {@code Throwable throwable}. If the {@code extensionContext} is annotated * with {@link ExpectedException} and if the {@code throwable} matches the expectations expressed * in the {@link ExpectedException} annotation then the supplied {@code throwable} is swallowed * otherwise the supplied {@code throwable} is rethrown. * * @param extensionContext the current extension context * @param throwable the {@code Throwable} to handle * @throws Throwable */ @Override public void handleTestExecutionException(ExtensionContext extensionContext, Throwable throwable) throws Throwable { Optional<ExpectedException> optional = findAnnotation(extensionContext.getTestMethod(), ExpectedException.class); if (optional.isPresent()) { ExpectedException annotation = optional.get(); if (throwable.getClass() == annotation.type()) { if (where(function, getPredicate(annotation)).test(throwable)) { return; } } } throw throwable; }
public static IInjectorProvider getOrCreateInjectorProvider(ExtensionContext context) { InjectWith injectWith = context.getRequiredTestClass().getAnnotation(InjectWith.class); if (injectWith != null) { Class<? extends IInjectorProvider> klass = injectWith.value(); IInjectorProvider injectorProvider = injectorProviderClassCache.get(klass); if (injectorProvider == null) { try { injectorProvider = klass.newInstance(); injectorProviderClassCache.put(klass, injectorProvider); } catch (Exception e) { throwUncheckedException(e); } } return injectorProvider; } return null; }
@Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { List<ParameterFactory> validFactories = getSupportedFactories(parameterContext.getParameter()).collect(toList()); if (validFactories.size() > 1) { throw new ParameterResolutionException( String.format("Too many factories: %s for parameter: %s", validFactories, parameterContext.getParameter())); } return Iterables.getOnlyElement(validFactories) .getParameterValue(parameterContext.getParameter()); }
@Override public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { Optional<ExpectFailure> annotation = getAnnotation(context); if (!annotation.isPresent()) { throw throwable; } ExpectFailure expectedFailure = annotation.get(); context.getStore(NAMESPACE).put(expectedFailure, throwable); ThrowableSubject subject = assertThat(throwable); for (Cause cause : expectedFailure.value()) { subject.isInstanceOf(cause.type()); if (!cause.message().isEmpty()) { subject.hasMessageThat().contains(cause.message()); } subject = subject.hasCauseThat(); } }
/** * Returns module types that are present on the given context or any of its enclosing contexts. */ private static Set<Class<? extends Module>> getContextModuleTypes( Optional<ExtensionContext> context) { // TODO: Cache? Set<Class<? extends Module>> contextModuleTypes = new LinkedHashSet<>(); while (context.isPresent() && (hasAnnotatedElement(context) || hasParent(context))) { context .flatMap(ExtensionContext::getElement) .map(GuiceExtension::getModuleTypes) .ifPresent(contextModuleTypes::addAll); context = context.flatMap(ExtensionContext::getParent); } return contextModuleTypes; }
@Override public void beforeAll(ExtensionContext context) throws Exception { Optional<String> baseUri = getProperty(BASE_URI_PROPERTY); Optional<String> port = getProperty(DEPLOY_PORT_PROPERTY); RestAssured.port = Integer.parseInt(port.orElse("8080")); RestAssured.baseURI = baseUri.map(host -> "http://" + host).orElse(RestAssured.DEFAULT_URI); RestAssured.rootPath = ROOT_PATH; waitForIt(baseUri.orElse("localhost"), RestAssured.port); }
@Override public void afterTestExecution(ExtensionContext context) throws Exception { IInjectorProvider injectorProvider = getOrCreateInjectorProvider(context); if (injectorProvider instanceof IRegistryConfigurator) { final IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) injectorProvider; registryConfigurator.restoreRegistry(); } }
@Override public Stream<? extends Arguments> provideArguments( ExtensionContext context) { System.out.println("Arguments provider [2] to test " + context.getTestMethod().get().getName()); return Stream.of(Arguments.of("more", 3), Arguments.of("arguments", 4)); }
private Object getMock(Parameter parameter, ExtensionContext extensionContext) { Class<?> mockType = parameter.getType(); Store mocks = extensionContext .getStore(Namespace.create(MockitoExtension.class, mockType)); String mockName = getMockName(parameter); if (mockName != null) { return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName)); } else { return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType)); } }
@Override public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { if (throwable instanceof IOException) { return; } throw throwable; }
private Optional<Field> getTestNameField(ExtensionContext extensionContext) { for (Field field : extensionContext.getRequiredTestClass().getDeclaredFields()) { if (isAnnotated(field, TestName.class)) { return Optional.of(field); } } return Optional.empty(); }
@Override public void afterAll(final ExtensionContext context) throws Exception { final TestSetup testSetup = (TestSetup) context.getStore(NS).get(TestSetup.class); if (testSetup != null) { testSetup.shutdown(); } }
@Override public void beforeTestExecution(ExtensionContext context) throws Exception { IInjectorProvider injectorProvider = getOrCreateInjectorProvider(context); if (injectorProvider instanceof IRegistryConfigurator) { final IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) injectorProvider; registryConfigurator.setupRegistry(); } if (injectorProvider != null) { Injector injector = injectorProvider.getInjector(); if (injector != null) injector.injectMembers(context.getRequiredTestInstance()); } }
@Override public void beforeAll(ExtensionContext context) throws Exception { if (!STARTED) { out.println("Starting JavaFX"); Platform.startup(() -> {}); STARTED = true; } }
private Object getMock(Parameter parameter, ExtensionContext extensionContext) { Class<?> mockType = parameter.getType(); Store mocks = extensionContext.getStore(Namespace.create(MockitoExtension.class, mockType)); String mockName = getMockName(parameter); if (mockName != null) { return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName)); } return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType)); }
@Override public void afterTestExecution(ExtensionContext context) throws Exception { Approval<File> approval = Approval.of(File.class)// .withPathMapper(pathMapper)// // TODO #3 Fork and suggest fix .withConveter(new FileConverter())// .withReporter(get(context, JUnitReporter.class, REPORTER_KEY)).build(); String fileName = context.getRequiredTestMethod().getName() + ".approved"; approval.verify(outputFile, Paths.get(fileName)); }
public TemplatedTestPathMapper(ExtensionContext context, Path path) { Class<?> testClass = context.getRequiredTestClass(); Method testMethod = context.getRequiredTestMethod(); String runIdSuffix = getRunIdSuffix(context.getDisplayName()); currentTestPath = path.resolve(testClass.getName().replace(".", File.separator)) .resolve(testMethod.getName() + runIdSuffix); }
@Override public void beforeTestExecution(final ExtensionContext context) throws Exception { getLifecycle().getCurrentTestCase().ifPresent(uuid -> { getLifecycle().updateTestCase(uuid, testResult -> { context.getTestClass().ifPresent(testClass -> { testResult.getLabels().addAll(getLabels(testClass)); testResult.getLinks().addAll(getLinks(testClass)); }); context.getTestMethod().ifPresent(testMethod -> { testResult.getLabels().addAll(getLabels(testMethod)); testResult.getLinks().addAll(getLinks(testMethod)); }); }); }); }
@ParameterizedTest @MethodSource("forcedTestProvider") void forcedTest(Class<? extends DriverHandler> handler, Class<?> testClass, Class<?> driverClass, String testName) throws Exception { Parameter parameter = testClass.getMethod(testName, driverClass) .getParameters()[0]; assertThrows(SeleniumJupiterException.class, () -> { handler.getDeclaredConstructor(Parameter.class, ExtensionContext.class).newInstance(parameter, null) .resolve(); }); }
@Override public void afterEach(ExtensionContext testExtensionContext) throws Exception { if (server == null || !server.isRunning()) { return; } server.resetRequests(); server.resetToDefaultMappings(); log.info("Stopping wiremock server on localhost:{}", server.port()); server.stop(); }
@Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts( ExtensionContext context) { BrowsersTemplate browsers = null; try { String browserJsonContent = getString( "sel.jup.browser.template.json.content"); if (browserJsonContent.isEmpty()) { String browserJsonFile = getString( "sel.jup.browser.template.json.file"); if (browserJsonFile.startsWith(CLASSPATH_PREFIX)) { String browserJsonInClasspath = browserJsonFile .substring(CLASSPATH_PREFIX.length()); browserJsonContent = IOUtils.toString( this.getClass().getResourceAsStream( "/" + browserJsonInClasspath), defaultCharset()); } else { browserJsonContent = new String( readAllBytes(get(browserJsonFile))); } } browsers = new Gson().fromJson(browserJsonContent, BrowsersTemplate.class); } catch (IOException e) { throw new SeleniumJupiterException(e); } return browsers.getStream().map(b -> invocationContext(b, this)); }
private Object getMock(Parameter parameter, ExtensionContext extensionContext) { Class<?> mockType = parameter.getType(); ExtensionContext.Store mocks = extensionContext.getStore(ExtensionContext.Namespace.create(MockitoExtension.class, mockType)); String mockName = getMockName(parameter); if (mockName != null) { return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName)); } else { return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType)); } }
@Override public final void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception { for (Class<?> clazz = testInstance.getClass(); clazz != null; clazz = clazz.getSuperclass()) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getType() == TestCompiler.class) { field.setAccessible(true); field.set(testInstance, getCompiler()); } else if (field.getType() == TestRunner.class) { field.setAccessible(true); field.set(testInstance, TrauteInMemoryTestRunner.INSTANCE); } } } }
@Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { Parameter parameter = parameterContext.getParameter(); Key<?> key = getKey(extensionContext.getTestClass(), parameter); Injector injector = getInjectorForParameterResolution(extensionContext) .orElseThrow(() -> new ParameterResolutionException( String.format( "Could not create injector for: %s It has no annotated element.", extensionContext.getDisplayName()))); return injector.getInstance(key); }
public static IInjectorProvider getInjectorProvider(ExtensionContext context) { InjectWith injectWith = context.getRequiredTestClass().getAnnotation(InjectWith.class); if (injectWith != null) { return injectorProviderClassCache.get(injectWith.value()); } return null; }
/** * Log test method exit, using the start time stored by {@link * #beforeTestExecution(ExtensionContext)} to calculate a duration. * * @param extensionContext the <em>context</em> in which the current test or container is being * executed * @throws Exception */ @Override public void afterTestExecution(ExtensionContext extensionContext) throws Exception { Method testMethod = extensionContext.getRequiredTestMethod(); long start = getStore(extensionContext).remove(testMethod, long.class); long duration = System.currentTimeMillis() - start; logger.info(String.format("Completed test [%s] in %sms", testMethod.getName(), duration)); }
@Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception { return Stream.of( MESSAGE_SIMPLE, MESSAGE_MARKDOWN_IN_ATTACHMENT_PRETEXT, MESSAGE_MARKDOWN_IN_PLAINTEXT_ATTACHMENT_FIELDS, MESSAGE_MARKDOWN_IN_ATTACHMENT_TEXT, MESSAGE_MARKDOWN_IN_ATTACHMENT_FIELDS, MESSAGE_WITH_ATTACHMENT_FOOTER, MESSAGE_WITH_ATTACHMENTS, MESSAGE_COMPLEX ).map(Arguments::of); }
@Override public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context) { return context.getElement() .flatMap(annotatedElement -> findAnnotation(annotatedElement, DisabledWhen.class)) .map(DisabledWhen::value) .map(supplierClass -> ReflectionSupport.newInstance(supplierClass)) .map(Supplier::get) .map(result -> Objects.requireNonNull(result, "Supplier result must not be null")) .map(shouldDisable -> shouldDisable ? disabled(DisabledWhen.class + " evaluated to true") : enabled(DisabledWhen.class + " evaluated to false")) .orElse(DEFAULT); }
private static Injector createInjector(ExtensionContext context) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Optional<Injector> parentInjector = getParentInjector(context); List<? extends Module> modules = getNewModules(context); return parentInjector .map(injector -> injector.createChildInjector(modules)) .orElseGet(() -> Guice.createInjector(modules)); }
private static Optional<Injector> getParentInjector(ExtensionContext context) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { if (context.getParent().isPresent()) { return getOrCreateInjector(context.getParent().get()); } return Optional.empty(); }
@Override public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context) { return context.getElement() .flatMap(annotatedElement -> findAnnotation(annotatedElement, RunOnDay.class)) .map(RunOnDay::value) .map(RunOnDayCondition::evaluateIfRunningOnDay) .orElse(DEFAULT); }
@Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return parameterContext.getParameter().isAnnotationPresent(Mock.class); }
@Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception { return ResourcesReader.readJson(RESOURCES_DIRECTORY).map(Arguments::of); }
@Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return getMock(parameterContext.getParameter(), extensionContext); }
@Override public void beforeTestExecution(ExtensionContext context) throws Exception { getStore(context).put(context.getRequiredTestMethod(), System.currentTimeMillis()); }
@Override // public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return parameterContext.getParameter().isAnnotationPresent(PageObject.class); }
public AppiumDriverHandler(Parameter parameter, ExtensionContext context) { super(parameter, context); }