All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.jqwik.engine.properties.PropertyMethodDataResolver Maven / Gradle / Ivy

The newest version!
package net.jqwik.engine.properties;

import java.lang.reflect.*;
import java.util.*;
import java.util.function.*;

import org.junit.platform.commons.support.*;

import net.jqwik.api.*;
import net.jqwik.api.providers.*;
import net.jqwik.engine.support.*;

import static net.jqwik.engine.support.JqwikReflectionSupport.*;

public class PropertyMethodDataResolver implements DataResolver {
	private final Class containerClass;
	private final List testInstances;

	public PropertyMethodDataResolver(Class containerClass, List testInstances) {
		this.containerClass = containerClass;
		this.testInstances = testInstances;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Optional> forMethod(Method method) {
		Optional optionalDataFrom = AnnotationSupport.findAnnotation(method, FromData.class);
		return optionalDataFrom
				   .map(FromData::value)
				   .map(generatorName -> {
					   Supplier exceptionSupplier =
						   () -> new JqwikException("No data provider method (annotated with @Data) for generator [" + generatorName + "] found");
					   return findGenerator(generatorName).orElseThrow(exceptionSupplier);
				   })
				   .map(generatorMethod -> JqwikReflectionSupport.invokeMethodOnContainer(generatorMethod, testInstances))
				   .map(invocationResult -> (Iterable) invocationResult);
	}

	private Optional findGenerator(String generatorName) {
		Function generatorNameSupplier = method -> {
			Data generateAnnotation = method.getDeclaredAnnotation(Data.class);
			return generateAnnotation.value();
		};
		TypeUsage expectedReturnType = TypeUsage.of(Iterable.class, TypeUsage.wildcard(TypeUsage.of(Tuple.class)));
		return findGeneratorMethod(generatorName, this.containerClass, Data.class, generatorNameSupplier, expectedReturnType);
	}
}