Hypothesis
Hypothesis is the property-based testing library for Python. With Hypothesis, you write tests which should pass for all inputs in whatever range you describe, and let Hypothesis randomly choose which of those inputs to check - including edge cases you might not have thought about. This randomized testing can catch bugs and edge cases that you didn't think of and wouldn't have found. When Hypothesis finds a bug, it reports the simplest possible example. It is currently at version 6.151.10 and receives regular updates.
Warnings
- breaking Documented APIs only guarantee backward compatibility across major version bumps. Undocumented attributes, modules, and behavior may include breaking changes in patch or minor releases. Always check the changelog for significant updates.
- deprecated Deprecated features will emit a `HypothesisDeprecationWarning` for at least six months before being removed in a subsequent major release.
- gotcha Tests must have deterministic outcomes and data generation. If tests involve threads or other non-deterministic elements and data generation depends on timing, Hypothesis may report flaky failures.
- gotcha Using overly broad strategies (e.g., `st.text()` without length limits) can lead to extremely slow test runs, high memory consumption, or tests that struggle to find simple counterexamples due to the vast search space.
- gotcha The `.example()` method on strategies is intended for interactive use (e.g., in a REPL) and should not be used within test functions or production code.
Install
-
pip install hypothesis
Imports
- given
from hypothesis import given
- strategies
from hypothesis import strategies as st
Quickstart
from hypothesis import given, strategies as st
def my_function(x):
return x + 1
@given(st.integers())
def test_my_function_increments(n):
assert my_function(n) == n + 1
# To run this, save as a Python file (e.g., example.py) and run with pytest
# For manual execution, uncomment and call the function:
# test_my_function_increments()