@Override public Object get(int index) { Preconditions.condition(index >= 0 && index < this.arguments.length, () -> format("index must be >= 0 and < %d", this.arguments.length)); return this.arguments[index]; }
private void validateWasAtLeastInvokedOnce(int invocationIndex) { Preconditions.condition(invocationIndex > 0, () -> "No supporting " + TestTemplateInvocationContextProvider.class.getSimpleName() + " provided an invocation context"); }
FilterableIgnoringRunnerDecorator(Runner runner) { super(runner); Preconditions.condition(runner instanceof Filterable, () -> "Runner must be an instance of Filterable: " + runner.getClass().getName()); }
static int parseFastForwardLimit(String fastForwardLine) { String text = fastForwardLine.trim().substring(2, fastForwardLine.length() - 2).trim(); try { int limit = Integer.parseInt(text); condition(limit > 0, () -> format("fast-forward(%d) limit must be greater than zero", limit)); return limit; } catch (NumberFormatException e) { return Integer.MAX_VALUE; } }
Optional<Method> findMethod(String methodSpecPart, Class<?> clazz) { Matcher matcher = METHOD_PATTERN.matcher(methodSpecPart); Preconditions.condition(matcher.matches(), () -> String.format("Method [%s] does not match pattern [%s]", methodSpecPart, METHOD_PATTERN)); String methodName = matcher.group(1); String parameterTypeNames = matcher.group(2); return ReflectionUtils.findMethod(clazz, methodName, parameterTypeNames); }
private int totalRepetitions(RepeatedTest repeatedTest, Method method) { int repetitions = repeatedTest.value(); Preconditions.condition(repetitions > 0, () -> String.format( "Configuration error: @RepeatedTest on method [%s] must be declared with a positive 'value'.", method)); return repetitions; }
private static void validateNames(EnumSource enumSource, Set<String> names) { // Do not map using Enum::name here since it results in a rawtypes warning // that fails our Gradle build which is configured with -Werror. Set<String> allNames = stream(enumSource.value().getEnumConstants()).map(e -> e.name()).collect(toSet()); Preconditions.condition(allNames.containsAll(names), () -> "Invalid enum constant name(s) in " + enumSource + ". Valid names include: " + allNames); }
@Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { Method testMethod = context.getRequiredTestMethod(); Preconditions.condition(testMethod.getParameterCount() > 0, () -> String.format( "@NullSource cannot provide a null argument to method [%s]: the method does not declare any formal parameters.", testMethod.toGenericString())); return Stream.of(nullArguments); }
@Override public Object convert(String source, Class<?> targetType) throws Exception { Function<String, Object> executable = findFactoryExecutable(targetType); Preconditions.condition(executable != NULL_EXECUTABLE, "Illegal state: convert() must not be called if canConvert() returned false"); return executable.apply(source); }
@Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { Optional<DisabledOnJre> optional = findAnnotation(context.getElement(), DisabledOnJre.class); if (optional.isPresent()) { JRE[] versions = optional.get().value(); Preconditions.condition(versions.length > 0, "You must declare at least one JRE in @DisabledOnJre"); return (Arrays.stream(versions).anyMatch(JRE::isCurrentVersion)) ? DISABLED_ON_CURRENT_JRE : ENABLED_ON_CURRENT_JRE; } return ENABLED_BY_DEFAULT; }
@Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { Optional<EnabledOnJre> optional = findAnnotation(context.getElement(), EnabledOnJre.class); if (optional.isPresent()) { JRE[] versions = optional.get().value(); Preconditions.condition(versions.length > 0, "You must declare at least one JRE in @EnabledOnJre"); return (Arrays.stream(versions).anyMatch(JRE::isCurrentVersion)) ? ENABLED_ON_CURRENT_JRE : DISABLED_ON_CURRENT_JRE; } return ENABLED_BY_DEFAULT; }
@Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { Optional<EnabledOnOs> optional = findAnnotation(context.getElement(), EnabledOnOs.class); if (optional.isPresent()) { OS[] operatingSystems = optional.get().value(); Preconditions.condition(operatingSystems.length > 0, "You must declare at least one OS in @EnabledOnOs"); return (Arrays.stream(operatingSystems).anyMatch(OS::isCurrentOs)) ? ENABLED_ON_CURRENT_OS : DISABLED_ON_CURRENT_OS; } return ENABLED_BY_DEFAULT; }
@Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { Optional<DisabledOnOs> optional = findAnnotation(context.getElement(), DisabledOnOs.class); if (optional.isPresent()) { OS[] operatingSystems = optional.get().value(); Preconditions.condition(operatingSystems.length > 0, "You must declare at least one OS in @DisabledOnOs"); return (Arrays.stream(operatingSystems).anyMatch(OS::isCurrentOs)) ? DISABLED_ON_CURRENT_OS : ENABLED_ON_CURRENT_OS; } return ENABLED_BY_DEFAULT; }
DefaultParameterContext(Parameter parameter, int index, Optional<Object> target) { Preconditions.condition(index >= 0, "index must be greater than or equal to zero"); this.parameter = Preconditions.notNull(parameter, "parameter must not be null"); this.index = index; this.target = Preconditions.notNull(target, "target must not be null"); }
@Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { Method testMethod = context.getRequiredTestMethod(); Class<?>[] parameterTypes = testMethod.getParameterTypes(); Preconditions.condition(parameterTypes.length > 0, () -> String.format( "@EmptySource cannot provide an empty argument to method [%s]: the method does not declare any formal parameters.", testMethod.toGenericString())); Class<?> parameterType = parameterTypes[0]; if (String.class.equals(parameterType)) { return Stream.of(arguments("")); } if (List.class.equals(parameterType)) { return Stream.of(arguments(Collections.emptyList())); } if (Set.class.equals(parameterType)) { return Stream.of(arguments(Collections.emptySet())); } if (Map.class.equals(parameterType)) { return Stream.of(arguments(Collections.emptyMap())); } if (parameterType.isArray()) { Object array = Array.newInstance(parameterType.getComponentType(), 0); return Stream.of(arguments(array)); } // else throw new PreconditionViolationException( String.format("@EmptySource cannot provide an empty argument to method [%s]: [%s] is not a supported type.", testMethod.toGenericString(), parameterType.getName())); }
@Override @SuppressWarnings({ "unchecked", "rawtypes" }) public void accept(EnumSource enumSource) { Class enumClass = enumSource.value(); this.constants = EnumSet.allOf(enumClass); EnumSource.Mode mode = enumSource.mode(); String[] declaredConstantNames = enumSource.names(); if (declaredConstantNames.length > 0) { Set<String> uniqueNames = stream(declaredConstantNames).collect(toSet()); Preconditions.condition(uniqueNames.size() == declaredConstantNames.length, () -> "Duplicate enum constant name(s) found in " + enumSource); mode.validate(enumSource, uniqueNames); this.constants.removeIf(constant -> !mode.select(constant, uniqueNames)); } }
private Method getMethodByFullyQualifiedName(String fullyQualifiedMethodName) { String[] methodParts = ReflectionUtils.parseFullyQualifiedMethodName(fullyQualifiedMethodName); String className = methodParts[0]; String methodName = methodParts[1]; String methodParameters = methodParts[2]; Preconditions.condition(StringUtils.isBlank(methodParameters), () -> format("factory method [%s] must not declare formal parameters", fullyQualifiedMethodName)); return getMethod(loadRequiredClass(className), methodName); }
@Override public void accept(ValueSource source) { // @formatter:off List<Object> arrays = // Declaration of <Object> is necessary due to a bug in Eclipse Photon. Stream.<Object> of( source.shorts(), source.bytes(), source.ints(), source.longs(), source.floats(), source.doubles(), source.chars(), source.strings(), source.classes() ) .filter(array -> Array.getLength(array) > 0) .collect(toList()); // @formatter:on Preconditions.condition(arrays.size() == 1, () -> "Exactly one type of input must be provided in the @" + ValueSource.class.getSimpleName() + " annotation, but there were " + arrays.size()); Object originalArray = arrays.get(0); arguments = IntStream.range(0, Array.getLength(originalArray)) // .mapToObj(index -> Array.get(originalArray, index)) // .toArray(); }
@Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts( ExtensionContext extensionContext) { Method templateMethod = extensionContext.getRequiredTestMethod(); String displayName = extensionContext.getDisplayName(); ParameterizedTestMethodContext methodContext = getStore(extensionContext)// .get(METHOD_CONTEXT_KEY, ParameterizedTestMethodContext.class); ParameterizedTestNameFormatter formatter = createNameFormatter(templateMethod, displayName); AtomicLong invocationCount = new AtomicLong(0); // @formatter:off return findRepeatableAnnotations(templateMethod, ArgumentsSource.class) .stream() .map(ArgumentsSource::value) .map(this::instantiateArgumentsProvider) .map(provider -> AnnotationConsumerInitializer.initialize(templateMethod, provider)) .flatMap(provider -> arguments(provider, extensionContext)) .map(Arguments::get) .map(arguments -> consumedArguments(arguments, methodContext)) .map(arguments -> createInvocationContext(formatter, methodContext, arguments)) .peek(invocationContext -> invocationCount.incrementAndGet()) .onClose(() -> Preconditions.condition(invocationCount.get() > 0, "Configuration error: You must configure at least one set of arguments for this @ParameterizedTest")); // @formatter:on }
@Override public boolean supportsTestTemplate(ExtensionContext context) { if (!context.getTestMethod().isPresent()) { return false; } Method testMethod = context.getTestMethod().get(); if (!isAnnotated(testMethod, ParameterizedTest.class)) { return false; } ParameterizedTestMethodContext methodContext = new ParameterizedTestMethodContext(testMethod); Preconditions.condition(methodContext.hasPotentiallyValidSignature(), () -> String.format( "@ParameterizedTest method [%s] declares formal parameters in an invalid order: " + "argument aggregators must be declared after any indexed arguments " + "and before any arguments resolved by another ParameterResolver.", testMethod.toGenericString())); getStore(context).put(METHOD_CONTEXT_KEY, methodContext); return true; }