Open dlesl opened 1 year ago
Sounds like a very reasonable idea.
Currently I've no build setup that allows me to use Java 17 features. I wonder if an additional module for Java 17 would do.
Same for kotlin module would be great.
Just FYI, If the type hierarchy is deeper, recursive search for subclasses is needed:
public static <T> Stream<Class<T>> implementationsOfSealedInterface(final Class<T> clazz) {
if (!clazz.isSealed()) {
throw new IllegalArgumentException(String.format("Class %s is not sealed", clazz.getName()));
}
return Stream.of(clazz.getPermittedSubclasses())
.flatMap(
c -> {
if (c.isSealed()) {
return implementationsOfSealedInterface((Class<T>) c);
} else {
return Stream.of((Class<T>) c);
}
});
}
Since work for Jqwik2 will probably be started in the upcoming months, this feature might have to wait till then.
Another solution with Kotlin where we use custom arbitrary for some subtypes:
Usage:
anyForSubtype<MyInterface> {
use<MySubtype> { mySubTypeArbitrary() }
}
Implementation:
inline fun <reified T> anyForSubtype(
customize: SubTypeDeclaration<T>.() -> Unit = {}
): Arbitrary<T> where T : Any {
val subTypeDeclaration = SubTypeDeclaration<T>().apply(customize)
return Arbitraries.of(T::class.sealedSubclasses).flatMap {
subTypeDeclaration.arbitraryFor(it) ?: buildArbitrary<T>(it)
}
}
inline fun <reified T> buildArbitrary(it: KClass<out T>) where T : Any =
Arbitraries.forType(it.java as Class<T>).enableRecursion().map { obj -> obj as T }
class SubTypeDeclaration<T> {
val arbitraryFactoriesByTargetClass = mutableMapOf<KClass<*>, ArbitraryFactory<*>>()
inline fun <reified S> use(noinline factory: ArbitraryFactory<S>) where S : T {
arbitraryFactoriesByTargetClass[S::class] = factory
}
fun <S : Any> arbitraryFor(target: KClass<S>): Arbitrary<T>? =
arbitraryFactoriesByTargetClass[target]?.invoke() as Arbitrary<T>?
}
typealias ArbitraryFactory<T> = () -> Arbitrary<T>
Kotlin only
Another solution with Kotlin where we use custom arbitrary for some subtypes:
Usage:
anyForSubtype<MyInterface> { use<MySubtype> { mySubTypeArbitrary() } }
This should be automatically handled by ˋanyForType
Yes, of course, I can try to submit a PR with this.
PR #555 created @jlink.
Testing Problem
Here is an example of testing a
sealed interface
which represents a data type.Perhaps this strategy could be attempted by jqwik's
@UseType
by default?Discussion
The current behaviour is that generation fails immediately for a sealed interface. Having this as the default behaviour could potentially be worse if it fails to discover/generate some of the subclasses and they get missed in testing?