Property based testing with Hypothesis
Alexander Hultnér @ PyCon SE 2019
@ahultner
Founder of Hultnér Technologies
@ahultner
Test Faster, Fix More
What is property based testing? Why?
Cheatsheet, two minute abstract
Hypothesis
Usage examples
Advanced strategies
Rule state machines
Interactive demo in Jupyter
Conclusion
Questions and links
@ahultner
Test Faster, Fix More
@ahultner
Test Faster, Fix More
pip install hypothesis
@ahultner
Test Faster, Fix More
@ahultner
Test Faster, Fix More
Generates positional arguments x, y
Strategies ensure integers are given
Strategies exists for a vast number of input types, they can be inferred and passed constraints via arguments.
from hypothesis import given
import hypothesis.strategies as st
@given(
st.integers(),
st.integers()
)
def test_ints_are_commutative(x, y):
assert x + y == y + x
@ahultner
Test Faster, Fix More
When an error is found it will be shrunk
to smallest possible example
=== FAILURES ===
___ test_add ___
@given(st.integers(), st.integers())
> def test_add(a, b):
_ _ _ _ _ _ _
a = -1, b = 1
@given(st.integers(), st.integers())
def test_add(a, b):
> assert add(a, b) == a + b
E assert -1 == 0
E --1
E +0
AssertionError
--- Hypothesis ---
Falsifying example: test_add(a=-1, b=1)
# Buggy implementation of add
def add(a, b):
return a if a < 0 else a + b
@ahultner
Test Faster, Fix More
We can explicitly define input with @example.
Useful to keep track of known tricky cases
@given(st.integers(), st.integers())
@example(
-1, 1
)
def test_add(a, b):
assert add(a, b) == a + b
@ahultner
Test Faster, Fix More
@ahultner
Test Faster, Fix More
…
@given(
st.integers(),
st.integers()
)
def test_add(a, b):
assert add_py3(a, b) == add_py2(a, b)
…
@ahultner
Test Faster, Fix More
With Hypothesis’s stateful testing, Hypothesis instead tries to generate not just data but entire tests.
Rule based state machines will allow you to define primitives from which tests are generated, gives you detailed steps taken to produce the bug, read more.
@ahultner
Test Faster, Fix More
I've prepared a Jupyter Notebook with a few interactive and more thorough examples.
@ahultner
Test Faster, Fix More
@ahultner
Test Faster, Fix More
Contact me if you have any further
questions.
Want to learn more?
Available for training, workshops and
consulting.
@ahultner
Test Faster, Fix More