-
Notifications
You must be signed in to change notification settings - Fork 586
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
Including optional fields in generated examples using the from_type strategy #2648
Comments
|
The underlying problem is as follows: import inspect, typing
from hypothesis.internal.compat import get_type_hints as hypothesis_hints
from pydantic import BaseModel
class Person(BaseModel):
middlename: typing.Optional[str]
assert typing.get_type_hints(Person) == {'middlename': typing.Union[str, NoneType]}
assert hypothesis_hints(Person) == {'middlename': str, ...}
# and this ultimately comes down to...
assert Person.__annotations__['middlename'] == Optional[str]
assert Person.__signature__.parameters['middlename'].annotation == str
# but consider the following - I think we need to make our __signature__
# logic explicitly handle the default value of None:
def f(a: str=None): ...
assert typing_hints(f) == {'a': typing.Union[str, NoneType]}
assert inspect.signature(f).parameters["a"].annotation == str |
|
Thanks for the lightning-fast feedback, workaround and fix! |
|
Happy to help - and your fantastic issue writeup made it easy |
Awesome, awesome project!
The
from_typestrategy is really useful when generating data from pydantic models (see pydantic/pydantic#1666), but it would be nice if it would recognise optional fields and sometimes generate values for these fields, resulting in a more complete set of examples. The behaviour could be the same as that of the fixed dictionaries strategy when provided with theoptionalkeyword argument, except that the optional fields are already known, from the model type hints.To give a concrete example:
It would be great if the behaviour was that the
middlenamefield may or may not be in the generated value. (Currently, it's alwaysNone.) Maybe something like:Is this a sensible idea, or am I missing some other easy way to do this?
So far I've tried:
fixed_dictionaries- not great as you either have to manually provide the required and optional fields and their strategies, or write your own functions to extract them from the pydantic model@given(st.builds(Person, middlename=infer))-middlenameis always set, which isn't what we want.The text was updated successfully, but these errors were encountered: