pytest-hypothesis
pytest-hypothesis is a bridge for using the Hypothesis property-based testing library with the pytest test framework. It enables developers to write tests that automatically generate varied inputs, helping to discover edge cases and subtle bugs in their code. While the `pytest-hypothesis` PyPI package is a legacy wrapper, its core functionality for pytest integration is now built directly into the main Hypothesis library (version 6.0.0 and later). It is actively maintained as part of Hypothesis, with a continuous release cadence.
Warnings
- deprecated The standalone `pytest-hypothesis` PyPI package is deprecated. Its functionality is now integrated directly into the core `Hypothesis` library (version 6.0.0 and newer). You no longer need to install `pytest-hypothesis` separately.
- gotcha `pytest` function-scoped fixtures (e.g., `@pytest.fixture(scope='function')`) will run only once for the entire Hypothesis test function, not once for each generated example. This can lead to unexpected state issues if your fixture is meant to reset state per example (e.g., database transactions).
- gotcha Hypothesis tests can report 'Flaky: Inconsistent test results!' if the test's outcome depends on external state or non-deterministic factors that are not reset between examples. This often indicates a lack of proper test isolation.
- gotcha Hypothesis test functions decorated with `@given` should not return any value other than `None`. Returning a value will cause Hypothesis to error, and `pytest` itself will also raise a warning or error for non-None return values from test functions.
- gotcha When defining strategies, if certain generated inputs are invalid for your test's logic but are valid according to the strategy, use `hypothesis.assume()` to filter them out. Using `assert False` for filtering will be reported as a test failure, not a discarded example, and prevents Hypothesis from finding a valid failing example.
Install
-
pip install hypothesis pytest
Imports
- given
from hypothesis import given
- strategies
from hypothesis import strategies as st
Quickstart
from hypothesis import given, strategies as st
import pytest
def add(a, b):
return a + b
@given(st.integers(), st.integers())
def test_add_integers(a, b):
"""Test that addition is commutative and associative for integers."""
assert add(a, b) == a + b
assert add(a, b) == add(b, a) # Commutativity
# Run this file with `pytest -v your_test_file.py`
# Example of using assume() to filter inputs without failing the test
@given(st.integers(min_value=1), st.integers(min_value=1))
def test_division_produces_float_or_int(numerator, denominator):
# Hypothesis generates pairs, but we might only care about certain conditions
# For instance, if we only want to test non-zero results, we can use assume
from hypothesis import assume
assume(denominator != 0)
result = numerator / denominator
assert isinstance(result, (float, int))
assert numerator == result * denominator