@Override public Serializable apply(Description description) { // @formatter:off return tryToReadFieldValue(Description.class, fieldName, description) .andThenTry(Serializable.class::cast) .ifFailure(cause -> logger.warn(cause, () -> format("Could not read unique ID for Description; using display name instead: %s", description))) .toOptional() .orElseGet(description::getDisplayName); // @formatter:on }
private static Class<?> toClass(String type) { //@formatter:off return ReflectionUtils .tryToLoadClass(type) .getOrThrow(cause -> new ArgumentConversionException( "Failed to convert String \"" + type + "\" to type " + Class.class.getName(), cause)); //@formatter:on }
private Optional<Class<?>> loadTestClass(String className, UniqueId uniqueId) { // @formatter:off return ReflectionUtils.tryToLoadClass(className) .ifFailure(cause -> logger.warn(cause, () -> format("Unresolvable Unique ID (%s): Unknown class %s", uniqueId, className))) .toOptional(); // @formatter:on }
@Override public ParallelExecutionConfiguration createConfiguration(ConfigurationParameters configurationParameters) { String className = configurationParameters.get(CONFIG_CUSTOM_CLASS_PROPERTY_NAME).orElseThrow( () -> new JUnitException(CONFIG_CUSTOM_CLASS_PROPERTY_NAME + " must be set")); return ReflectionUtils.tryToLoadClass(className) // .andThenTry(strategyClass -> { Preconditions.condition( ParallelExecutionConfigurationStrategy.class.isAssignableFrom(strategyClass), CONFIG_CUSTOM_CLASS_PROPERTY_NAME + " does not implement " + ParallelExecutionConfigurationStrategy.class); return (ParallelExecutionConfigurationStrategy) ReflectionUtils.newInstance(strategyClass); }) // .andThenTry(strategy -> strategy.createConfiguration(configurationParameters)) // .getOrThrow(cause -> new JUnitException( "Could not create configuration for strategy class: " + className, cause)); } };
private ForkJoinPool createForkJoinPool(ConfigurationParameters configurationParameters) { ParallelExecutionConfigurationStrategy strategy = DefaultParallelExecutionConfigurationStrategy.getStrategy( configurationParameters); ParallelExecutionConfiguration configuration = strategy.createConfiguration(configurationParameters); ForkJoinWorkerThreadFactory threadFactory = new WorkerThreadFactory(); return Try.call(() -> { // Try to use constructor available in Java >= 9 Constructor<ForkJoinPool> constructor = ForkJoinPool.class.getDeclaredConstructor(Integer.TYPE, ForkJoinWorkerThreadFactory.class, UncaughtExceptionHandler.class, Boolean.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, Predicate.class, Long.TYPE, TimeUnit.class); return constructor.newInstance(configuration.getParallelism(), threadFactory, null, false, configuration.getCorePoolSize(), configuration.getMaxPoolSize(), configuration.getMinimumRunnable(), null, configuration.getKeepAliveSeconds(), TimeUnit.SECONDS); }).orElseTry(() -> { // Fallback for Java 8 return new ForkJoinPool(configuration.getParallelism(), threadFactory, null, false); }).getOrThrow(cause -> new JUnitException("Failed to create ForkJoinPool", cause)); }
private static Predicate<? super Throwable> createAbortedExecutionPredicate() { Predicate<Throwable> otaPredicate = TestAbortedException.class::isInstance; // Additionally support JUnit 4's AssumptionViolatedException? Class<?> clazz = ReflectionUtils.tryToLoadClass( "org.junit.internal.AssumptionViolatedException").toOptional().orElse(null); if (clazz != null) { return otaPredicate.or(clazz::isInstance); } // Else just OTA's TestAbortedException return otaPredicate; }
/** * Register extensions in the supplied registry from fields in the supplied * class that are annotated with {@link RegisterExtension @RegisterExtension}. * * <p>The extensions will be sorted according to {@link Order @Order} semantics * prior to registration. * * @param registry the registry in which to register the extensions; never {@code null} * @param clazz the class or interface in which to find the fields; never {@code null} * @param instance the instance of the supplied class; may be {@code null} * when searching for {@code static} fields in the class */ static void registerExtensionsFromFields(ExtensionRegistry registry, Class<?> clazz, Object instance) { Preconditions.notNull(clazz, "Class must not be null"); Preconditions.notNull(registry, "ExtensionRegistry must not be null"); Predicate<Field> predicate = (instance == null) ? isStaticExtension : isNonStaticExtension; // Ensure that the list is modifiable, since findAnnotatedFields() returns an unmodifiable list. List<Field> fields = new ArrayList<>(findAnnotatedFields(clazz, RegisterExtension.class, predicate)); // Sort fields based on @Order. fields.sort(orderComparator); fields.forEach(field -> { tryToReadFieldValue(field, instance).ifSuccess(value -> { Preconditions.notNull(value, () -> String.format( "Failed to register extension via @RegisterExtension field [%s]: field must not be null when evaluated.", field)); Extension extension = (Extension) value; registry.registerExtension(extension, field); }); }); }
@Override public Optional<TestDescriptor> resolveUniqueId(UniqueId.Segment segment, TestDescriptor parent) { if (!segment.getType().equals(getSegmentType())) { return Optional.empty(); } if (!requiredParentType().isInstance(parent)) { return Optional.empty(); } String className = getClassName(parent, segment.getValue()); Optional<Class<?>> optionalContainerClass = ReflectionUtils.tryToLoadClass(className).toOptional(); if (!optionalContainerClass.isPresent()) { return Optional.empty(); } Class<?> containerClass = optionalContainerClass.get(); if (!isPotentialCandidate(containerClass)) { return Optional.empty(); } UniqueId uniqueId = createUniqueId(containerClass, parent); return Optional.of(resolveClass(containerClass, uniqueId)); }
private Class<?> loadRequiredClass(String className) { return ReflectionUtils.tryToLoadClass(className).getOrThrow( cause -> new JUnitException(format("Could not load class [%s]", className), cause)); }
private void lazyLoadJavaClass() { if (this.javaClass == null) { // @formatter:off this.javaClass = ReflectionUtils.tryToLoadClass(this.className).getOrThrow( cause -> new PreconditionViolationException("Could not load class with name: " + this.className, cause)); // @formatter:on } }
/** * Get the selected {@link Class}. * * <p>If the {@link Class} was not provided, but only the name, this method * attempts to lazily load the {@link Class} based on its name and throws a * {@link PreconditionViolationException} if the class cannot be loaded. */ public Class<?> getJavaClass() { if (this.javaClass == null) { this.javaClass = ReflectionUtils.tryToLoadClass(this.className).getOrThrow( cause -> new PreconditionViolationException("Could not load class with name: " + this.className, cause)); } return this.javaClass; }
/** * Get the {@linkplain Class Java class} of this source. * * <p>If the {@link Class} was not provided, but only the name, this method * attempts to lazily load the {@link Class} based on its name and throws a * {@link PreconditionViolationException} if the class cannot be loaded. * * @see #getClassName() * @see #getPosition() */ public final Class<?> getJavaClass() { if (this.javaClass == null) { this.javaClass = ReflectionUtils.tryToLoadClass(this.className).getOrThrow( cause -> new PreconditionViolationException("Could not load class with name: " + this.className, cause)); } return this.javaClass; }