Martin Thoma
Martin Thoma

Reputation: 136379

Can I list which objects are generated by a hypothesis strategy?

hypothesis has a lot of strategies and I'm still struggling with understanding them. It would help me a lot to see which values they generate. Is that possible?

MVCE

With hypothesis==5.18.3 and pydantic==1.5.1:

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):
    seen = [
        Person(
            prename="",
            middlename=None,
            lastname="",
            address=Adress(city="", street="", house_number=0, postal_code=0),
        ),
        Person(
            prename="0",
            middlename=None,
            lastname="",
            address=Adress(city="", street="", house_number=0, postal_code=0),
        ),
        Person(
            prename="",
            middlename=None,
            lastname="0",
            address=Adress(city="", street="", house_number=0, postal_code=0),
        ),
        Person(
            prename="",
            middlename=None,
            lastname="",
            address=Adress(city="", street="0", house_number=0, postal_code=0),
        ),
    ]
    assert person in seen

As you can see, the way I currently figure out what hypothesis is doing is by manually adding it to this seen list. Is there a way to use a strategy as a generator / produce the list of values that the strategy tests?

Upvotes: 0

Views: 473

Answers (1)

Zac Hatfield-Dodds
Zac Hatfield-Dodds

Reputation: 3003

I would recommend turning up the verbosity setting, which will print all the examples Hypothesis generates for your test.

If you're using pytest, you'll also need to disable output capturing: pytest -s --hypothesis-verbosity=verbose MY_TEST_HERE

Alternatively, in an interactive session you can call the .example() method on strategy objects to get an arbitrary example.

Upvotes: 1

Related Questions