Property-based testing is a complementary approach to traditional unit testing, where test cases are generated based on properties or constriants that the code should satisfy.
Hypothesis addresses this limitation by automatically generating test data based on specified strategies.
To use Hypothesis in this example, we import the given
, strategies
and assume
in-built methods.
The @given
decorator is placed just before each test followed by a strategy.
A strategy is specified using the strategy.X
method which can be st.list()
, st.integers()
, st.text()
and so on.
Here’s a comprehensive list of strategies.
Strategies are used to generate test data and can be heavily customised to your liking for example — generate only positive/negative numbers, X/Y key, value pairs, integer with a maximum value of 100 and so on.
Common issues discovered (that aren’t accounted for) include
- Empty lists, strings, and dicts as input
- Repeated values in lists
- Negative numbers, 0 as input
- Keys not present in dict
- ASCII characters