Hypothesis - Property-Based Testing

VerifiedSafe

Use Hypothesis for property-based testing to automatically generate test cases, find edge cases, and write robust tests with minimal example shrinking.

Sby Skills Guide Bot
TestingIntermediate
7/23/2026
Claude CodeCursorWindsurfCopilotCodex
#property-based-testing#python#pytest#test-generation#stateful-testing

Recommended for

Automated summary

Guides developers in using Hypothesis for property-based testing in Python, covering strategies, settings, helpers, and stateful tests.

Strengths

  • Covers the core strategy API, combinators, and composite strategies with concise examples.
  • Shows profile-based configuration for development and CI, plus helpers such as assume, note, example, and seed.
  • Includes a stateful testing pattern for rule-based state machines.
  • Links to the official documentation for deeper reference.

Limitations

  • Assumes familiarity with pytest and Python testing; it is not a full tutorial on test design.
  • Property-based testing requires formulating good invariants, which the skill does not fully teach.
  • Polars integration is only briefly mentioned in the visible content.
When to use it

Use when writing or improving Python tests that must verify invariants across a wide range of inputs, especially with pytest.

When not to use it

Avoid when simple example-based unit tests are sufficient, or when the expected behavior cannot be expressed as clear properties or invariants.

Security analysis

Safe
Quality score85/100

The skill is a documentation/reference guide for Hypothesis property-based testing. It contains only Python examples and links to official documentation, with no destructive commands, exfiltration, obfuscation, or safety-disabling instructions.

No concerns found

How this analysis is made

Examples

Integer property test
Write a pytest test using Hypothesis that checks a sorting function returns a list with the same elements as the input and in non-decreasing order.
CI profile setup
Add a Hypothesis settings profile named ci with max_examples=1000 and deadline=None, and explain how to activate it with the HYPOTHESIS_PROFILE environment variable.
Stateful list test
Create a Hypothesis RuleBasedStateMachine test for a simple list-like class with add and clear rules and an invariant that the size is never negative.

name: hypothesis description: Use Hypothesis for property-based testing to automatically generate comprehensive test cases, find edge cases, and write more robust tests with minimal example shrinking. Includes Polars parametric testing integration.

Hypothesis - Property-Based Testing

Property-based testing framework that generates test cases automatically, finds minimal failing examples through shrinking, and verifies invariants.

Official Docs: https://hypothesis.readthedocs.io/en/latest/

Key Features:

  • Automatic test data generation from strategies
  • Minimal failing example shrinking
  • Stateful testing with rule-based state machines
  • pytest integration
  • Deterministic reproducibility

Quick Start

from hypothesis import given
from hypothesis import strategies as st


@given(st.integers())
def test_property(x):
    """Test properties that should always hold"""
    assert abs(x) >= 0


@given(st.lists(st.integers()))
def test_list_property(lst):
    sorted_lst = sorted(lst)
    assert len(sorted_lst) == len(lst)
    # Check monotonic property
    for i in range(len(sorted_lst) - 1):
        assert sorted_lst[i] <= sorted_lst[i + 1]

Strategies

Full reference: https://hypothesis.readthedocs.io/en/latest/data.html

Common strategies:

  • Primitives: st.integers(), st.floats(), st.text(), st.booleans()
  • Collections: st.lists(), st.dictionaries(), st.tuples(), st.sets()
  • Dates/Times: st.dates(), st.datetimes(), st.timedeltas()
  • Combinators: st.one_of(), st.sampled_from(), st.recursive()
  • Type-based: st.from_type(MyClass)

Composite Strategies

from hypothesis import strategies as st
from hypothesis.strategies import composite


@composite
def user_strategy(draw):
    age = draw(st.integers(min_value=18, max_value=100))
    name = draw(st.text(min_size=1))
    return {"name": name, "age": age, "is_adult": age >= 18}


@given(user_strategy())
def test_user(user):
    assert user["is_adult"] == (user["age"] >= 18)

Strategy Combinators

st.integers().filter(lambda x: x % 2 == 0)  # Filter
st.integers().map(str)  # Transform
st.one_of(st.integers(), st.text())  # Choose between strategies
st.sampled_from([1, 2, 3, 4, 5])  # Pick from collection
st.from_type(MyClass)  # Infer from type hints
st.builds(MyClass, arg1=st.integers())  # Build instances

Settings

from hypothesis import given, settings
from hypothesis import strategies as st


@given(st.integers())
@settings(
    max_examples=1000,  # Default: 100
    deadline=None,  # Remove time limit
    derandomize=True,  # Deterministic ordering
)
def test_example(x):
    pass


# Profiles for different environments
settings.register_profile("dev", max_examples=10)
settings.register_profile("ci", max_examples=1000, deadline=None)
# Activate: HYPOTHESIS_PROFILE=ci pytest

Full settings reference: https://hypothesis.readthedocs.io/en/latest/settings.html

Helpers

from hypothesis import given, assume, note, example, seed


@given(st.integers(), st.integers())
def test_division(x, y):
    assume(y != 0)  # Skip invalid cases (prefer .filter() instead)
    note(f"Testing {x} / {y}")  # Add debug info
    assert (x / y) * y == x


@given(st.integers())
@example(0)  # Always test specific cases
@seed(12345)  # Reproducible run
def test_something(x):
    pass

Stateful Testing

For testing complex stateful systems with rule-based state machines.

from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
from hypothesis import strategies as st


class MyStateMachine(RuleBasedStateMachine):
    def __init__(self):
        super().__init__()
        self.data = []

    @rule(value=st.integers())
    def add(self, value):
        self.data.append(value)

    @invariant()
    def check_invariant(self):
        assert isinstance(self.data, list)


TestMachine = MyStateMachine.TestCase

Full stateful testing guide: https://hypothesis.readthedocs.io/en/latest/stateful.html

Polars Integration

Polars provides built-in parametric testing strategies for generating DataFrames.

Official docs: https://docs.pola.rs/api/python/stable/reference/api/polars.testing.parametric.dataframes.html

from hypothesis import given
import polars as pl
from polars.testing.parametric import dataframes, column


# Generate DataFrames with specific column schemas
@given(
    dataframes(
        cols=[
            column("id", dtype=pl.Int64),
            column("name", dtype=pl.String),
            column("value", dtype=pl.Float64),
        ],
        min_size=1,
        max_size=100,
    )
)
def test_dataframe_property(df: pl.DataFrame):
    """Test properties of DataFrame operations"""
    assert df.shape[0] >= 1
    assert set(df.columns) == {"id", "name", "value"}
    assert df["id"].dtype == pl.Int64


# With Narwhals wrapper
import narwhals as nw


@given(dataframes(cols=[column("a", dtype=pl.Int64)]))
def test_narwhals_operation(df: pl.DataFrame):
    nw_df = nw.from_native(df)
    result = nw_df.select(nw.col("a") * 2)
    assert result.shape[0] == nw_df.shape[0]

Key functions:

  • dataframes(): Generate DataFrames with specified columns
  • column(name, dtype, ...): Define column schemas with constraints
  • series(): Generate standalone Series

Column constraints:

  • null_probability: Control null value frequency
  • min_size/max_size: Control row count
  • allow_null: Enable/disable nulls
  • unique: Generate unique values
  • strategy: Custom strategy for column values

Best Practices

  • Use constraints over filters: st.integers(min_value=0) not st.integers().filter(lambda x: x >= 0)
  • Test properties, not examples: Focus on invariants that always hold
  • Combine with @example(): Test specific edge cases explicitly
  • Avoid assume() overuse: Makes tests slow; use filtered strategies
  • Document properties: Clear docstrings explain what invariant is tested
  • Set size limits: Always bound collection sizes to prevent memory issues
  • Use .hypothesis/ in .gitignore: Stores example database locally

Troubleshooting

Common issues and solutions:

  • HealthCheck failures: Too many rejected examples → use constrained strategies or suppress_health_check
  • Flaky tests: Non-deterministic code → use @seed() or @settings(derandomize=True)
  • Slow tests: Too many examples → reduce max_examples or use profiles
  • Deadline exceeded: Complex operations → increase deadline or set to None

Resources

  • Main docs: https://hypothesis.readthedocs.io/
  • Strategies: https://hypothesis.readthedocs.io/en/latest/data.html
  • Stateful testing: https://hypothesis.readthedocs.io/en/latest/stateful.html
  • Ghost writer (auto-generate tests): hypothesis write mymodule.myfunction

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/hypothesis-property-based-testing-mrx3xzpd/download' --output '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md.part' && mv '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md.part' '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && test -s '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/hypothesis' && cp -R '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd' '.claude/skills/hypothesis'

Cursor
test -f '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && test -s '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/hypothesis' && cp -R '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd' '.cursor/skills/hypothesis'

Codex
test -f '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && test -s '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/hypothesis' && cp -R '.skill-downloads/hypothesis-property-based-testing-mrx3xzpd' '.agents/skills/hypothesis'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/hypothesis-property-based-testing-mrx3xzpd'

openskills read 'hypothesis-property-based-testing-mrx3xzpd'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/hypothesis-property-based-testing-mrx3xzpd/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills