I had a look at hypothesis recently and used it like this:
import hypothesis.strategies as s
from hypothesis import given
@given(s.integers(min_value=-(10 ** 6), max_value=10 ** 6))
def test_factorize(an_integer):
if an_integer == 0:
# This is tested in `test_factorize_zero` and should throw an exception
return
factors = mpu.math.factorize(an_integer)
product = 1
for factor in factors:
product *= factor
assert product == an_integer
This is pretty cool. The main limitation I see is the strategy (e.g. s.integers
), although there are a lot of strategies and I'm still learning which ones there are / how to use them properly.
Is there a strategy to generate objects, given a type-annotated class which uses pydantic?
My Try
from typing import Optional
from hypothesis import given
from hypothesis.strategies import from_type
from pydantic import BaseModel
class Adress(BaseModel):
city: str
street: str
house_number: int
postal_code: int
class Person(BaseModel):
prename: str
middlename: Optional[str]
lastname: str
address: Adress
@given(from_type(Person))
def test_me(person: Person):
assert isinstance(person, Person)
when I save this as test_foo.py
and execute pytest
, I get:
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― test_me ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
@given(from_type(Person))
> def test_me(person: Person):
test_foo.py:20:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> ???
E pydantic.error_wrappers.ValidationError: 3 validation errors for Person
E prename
E field required (type=value_error.missing)
E lastname
E field required (type=value_error.missing)
E address
E field required (type=value_error.missing)
pydantic/main.py:283: ValidationError
---------------------------------------------------------------- Hypothesis ----------------------------------------------------------------
You can add @seed(42732672939050403878146949573829059697) to this test or run pytest with --hypothesis-seed=42732672939050403878146949573829059697 to reproduce this failure.
I would especially love if hypothesis generated a person without a middle name and a person with a middle name.