-
-
Notifications
You must be signed in to change notification settings - Fork 64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Consider supporting @UseType for sealed interfaces #523
Comments
Sounds like a very reasonable idea. Currently I've no build setup that allows me to use Java 17 features. |
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
This should be automatically handled by ˋanyForTypeˋ IMO. |
Yes, of course, I can try to submit a PR with this. |
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?
The text was updated successfully, but these errors were encountered: