The Hypothesis docs say that you may not register type strategies for parametrised generic types such as MyCollection[int] [1]. As expected, we see an error when trying this out:
from typing import Generic, TypeVar, List
import hypothesis.strategies as st
T = TypeVar("T")
class MyCollection(Generic[T]):
def __init__(self, items: List[T]):
self.items = items
st.register_type_strategy(MyCollection[int], st.lists(st.integers()).map(lambda x: MyCollection(x)))
InvalidArgument: Cannot register generic type MyCollection[int], because it has type arguments which would not be handled. Instead, register a function for <class 'MyCollection'> which can inspect specific type objects and return a strategy.
However, the behaviour is different and surprising when using Pydantic GenericModels. Specifically:
- It seems it's not possible to register a dynamic
lambda T: ... strategy for MyCollection.
- In contrast to what the docs say, it seems it is possible to register a strategy for a specific
MyCollection[T].
from typing import Generic, TypeVar, List
from pydantic.generics import GenericModel
import hypothesis.strategies as st
T = TypeVar("T")
class MyCollection(GenericModel, Generic[T]):
items: List[T]
def select_strategy(type_):
print(type_)
raise ValueError("This is never reached")
# Try registering a generic strategy for all `MyCollection[T]`.
st.register_type_strategy(MyCollection, select_strategy)
st.from_type(MyCollection[int]).example() # Surprise 1: `select_strategy` is not called!
# Try registering a strategy for a specific `MyCollection[int]`.
st.register_type_strategy(MyCollection[int], st.lists(st.booleans()).map(lambda x: MyCollection(items=x)))
st.from_type(MyCollection[int]).example() # Surprise 2: this uses the registered strategy!
[1] https://hypothesis.readthedocs.io/en/latest/data.html#hypothesis.strategies.register_type_strategy
The Hypothesis docs say that you may not register type strategies for parametrised generic types such as
MyCollection[int][1]. As expected, we see an error when trying this out:However, the behaviour is different and surprising when using Pydantic
GenericModels. Specifically:lambda T: ...strategy forMyCollection.MyCollection[T].[1] https://hypothesis.readthedocs.io/en/latest/data.html#hypothesis.strategies.register_type_strategy