pythonfuzzingpython-hypothesis

How to define hypothesis strategies for custom dataclasses


I am currently using hypothesis for fuzzing my test but I then need to generate random dataclasses, and so to build strategies for each, like

# Base types
uint64 = st.integers(min_value=0, max_value=2**64 - 1)
uint256 = st.integers(min_value=0, max_value=2**256 - 1)

# Dataclasses types
account = st.fixed_dictionaries(
    {
        "nonce": uint64,
        "balance": uint256,
        "code": st.binary(),
    }
).map(lambda x: Account(**x))

Is there a way to avoid this explicit strategy definition? Somehow like with rust arbitrary, producing well-typed, structured values, from raw, byte buffers.


Solution

  • hypothesis.strategies.builds says

    Dataclasses are handled natively by the inference from type hints.

    So if your dataclasses are type-hinted properly with types that are registered (or themselves introspectable) such that from_type returns the strategy you want, it should be just

    account = st.builds(Account)
    

    And if you’re using these in normal Hypothesis tests, you don’t even need to specify that; let Hypothesis infer it.