pytest-hypothesis

10.0.3 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `hypothesis.given` decorator with `pytest`. Tests decorated with `@given` will be run multiple times by Hypothesis, with automatically generated inputs adhering to the specified strategies (e.g., `st.integers()`). Run these tests using the `pytest` command line tool.

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

view raw JSON →