Randomizing a user dataclass with pytest and hypothesis

Issue

This Content is from Stack Overflow. Question asked by OrenIshShalom

I can manually define an Address builder strategy:

import attrs
from hypothesis import given
import hypothesis.strategies as st

@attrs.frozen(kw_only=True)
class Address:

    street: str
    city: str

AddressStrategy = st.builds(
    Address,
    street=st.text(),
    city=st.text()
)

@given(AddressStrategy)
def test_proper_address(address):
    assert len(address.city) < 4

When I run pytest, it indeed catches my bug:

address = Address(street='', city='0000') # <--- counterexample address found - good !

    @given(AddressStrategy)
    def test_proper_address(address):
>       assert len(address.city) < 4
E       AssertionError: assert 4 < 4
E        +  where 4 = len('0000')
E        +    where '0000' = Address(street='', city='0000').city

main.py:23: AssertionError

According to the docs, it seems like it should be possible to use an auto-generated address builder:

builds() will be used automatically for classes with type annotations on init

But when I try the following options, neither work:

  • st.register_type_strategy(Address)
  • @given(Address)



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?