| 1 |
Introduction to Hypothesis |
| 2 |
========================== |
| 3 |
|
| 4 |
This page introduces two fundamental parts of Hypothesis (|@given|, and strategies) and shows how to test a selection sort implementation using Hypothesis. |
| 5 |
|
| 6 |
Install Hypothesis |
| 7 |
------------------ |
| 8 |
|
| 9 |
First, let's install Hypothesis: |
| 10 |
|
| 11 |
.. code-block:: shell |
| 12 |
|
| 13 |
pip install hypothesis |
| 14 |
|
| 15 |
Defining a simple test |
| 16 |
---------------------- |
| 17 |
|
| 18 |
Hypothesis tests are defined using two things; |@given|, and a *strategy*, which is passed to |@given|. Here's a simple example: |
| 19 |
|
| 20 |
.. code-block:: python |
| 21 |
|
| 22 |
from hypothesis import given, strategies as st |
| 23 |
|
| 24 |
@given(st.integers()) |
| 25 |
def test_is_integer(n): |
| 26 |
assert isinstance(n, int) |
| 27 |
|
| 28 |
Adding the |@given| decorator turns this function into a Hypothesis test. Passing |st.integers| to |@given| says that Hypothesis should generate random integers for the argument ``n`` when testing. |
| 29 |
|
| 30 |
We can run this test by calling it: |
| 31 |
|
| 32 |
.. code-block:: python |
| 33 |
|
| 34 |
from hypothesis import given, strategies as st |
| 35 |
|
| 36 |
@given(st.integers()) |
| 37 |
def test_is_integer(n): |
| 38 |
print(f"called with {n}") |
| 39 |
assert isinstance(n, int) |
| 40 |
|
| 41 |
test_is_integer() |
| 42 |
|
| 43 |
Note that we don't pass anything for ``n``; Hypothesis handles generating that value for us. The resulting output looks like this: |
| 44 |
|
| 45 |
.. code-block:: none |
| 46 |
|
| 47 |
called with 0 |
| 48 |
called with -18588 |
| 49 |
called with -672780074 |
| 50 |
called with 32616 |
| 51 |
... |
| 52 |
|
| 53 |
|
| 54 |
Testing a sorting algorithm |
| 55 |
--------------------------- |
| 56 |
|
| 57 |
Suppose we have implemented a simple selection sort: |
| 58 |
|
| 59 |
.. code-block:: python |
| 60 |
|
| 61 |
# contents of example.py |
| 62 |
from hypothesis import given, strategies as st |
| 63 |
|
| 64 |
def selection_sort(lst): |
| 65 |
result = [] |
| 66 |
while lst: |
| 67 |
smallest = min(lst) |
| 68 |
result.append(smallest) |
| 69 |
lst.remove(smallest) |
| 70 |
return result |
| 71 |
|
| 72 |
and want to make sure it's correct. We can write the following test by combining the |st.integers| and |st.lists| strategies: |
| 73 |
|
| 74 |
.. code-block:: python |
| 75 |
|
| 76 |
... |
| 77 |
|
| 78 |
@given(st.lists(st.integers())) |
| 79 |
def test_sort_correct(lst): |
| 80 |
print(f"called with {lst}") |
| 81 |
assert selection_sort(lst.copy()) == sorted(lst) |
| 82 |
|
| 83 |
test_sort_correct() |
| 84 |
|
| 85 |
When running ``test_sort_correct``, Hypothesis uses the ``lists(integers())`` strategy to generate random lists of integers. Feel free to run ``python example.py`` to get an idea of the kinds of lists Hypothesis generates (and to convince yourself that this test passes). |
| 86 |
|
| 87 |
Adding floats to our test |
| 88 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 89 |
|
| 90 |
This test is a good start. But ``selection_sort`` should be able to sort lists with floats, too. If we wanted to generate lists of either integers or floats, we can change our strategy: |
| 91 |
|
| 92 |
.. code-block:: python |
| 93 |
|
| 94 |
# changes to example.py |
| 95 |
@given(st.lists(st.integers() | st.floats())) |
| 96 |
def test_sort_correct(lst): |
| 97 |
pass |
| 98 |
|
| 99 |
The pipe operator ``|`` takes two strategies, and returns a new strategy which generates values from either of its strategies. So the strategy ``integers() | floats()`` can generate either an integer, or a float. |
| 100 |
|
| 101 |
.. note:: |
| 102 |
|
| 103 |
``strategy1 | strategy2`` is equivalent to :func:`st.one_of(strategy1, strategy2) <hypothesis.strategies.one_of>`. |
| 104 |
|
| 105 |
Preventing |st.floats| from generating ``nan`` |
| 106 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 107 |
|
| 108 |
Even though ``test_sort_correct`` passed when we used lists of integers, it actually fails now that we've added floats! If you run ``python example.py``, you'll likely (but not always; this is random testing, after all) find that Hypothesis reports a counterexample to ``test_sort_correct``. For me, that counterexample is ``[1.0, nan, 0]``. It might be different for you. |
| 109 |
|
| 110 |
The issue is that sorting in the presence of ``nan`` is not well defined. As a result, we may decide that we don't want to generate them while testing. We can pass ``floats(allow_nan=False)`` to tell Hypothesis not to generate ``nan``: |
| 111 |
|
| 112 |
.. code-block:: python |
| 113 |
|
| 114 |
# changes to example.py |
| 115 |
@given(st.lists(st.integers() | st.floats(allow_nan=False))) |
| 116 |
def test_sort_correct(lst): |
| 117 |
pass |
| 118 |
|
| 119 |
And now this test passes without issues. |
| 120 |
|
| 121 |
.. note:: |
| 122 |
|
| 123 |
You can use the |.example()| method to get an idea of the kinds of things a strategy will generate: |
| 124 |
|
| 125 |
.. code-block:: pycon |
| 126 |
|
| 127 |
>>> st.lists(st.integers() | st.floats(allow_nan=False)).example() |
| 128 |
[-5.969063e-08, 15283673678, 18717, -inf] |
| 129 |
|
| 130 |
Note that |.example()| is intended for interactive use only (i.e., in a :term:`REPL <python:REPL>`). It is not intended to be used inside tests. |
| 131 |
|
| 132 |
|
| 133 |
Tests with multiple arguments |
| 134 |
----------------------------- |
| 135 |
|
| 136 |
If we wanted to pass multiple arguments to a test, we can do this by passing multiple strategies to |@given|: |
| 137 |
|
| 138 |
.. code-block:: python |
| 139 |
|
| 140 |
from hypothesis import given, strategies as st |
| 141 |
|
| 142 |
@given(st.integers(), st.lists(st.floats())) |
| 143 |
def test_multiple_arguments(n, lst): |
| 144 |
assert isinstance(n, int) |
| 145 |
assert isinstance(lst, list) |
| 146 |
for f in lst: |
| 147 |
assert isinstance(f, float) |
| 148 |
|
| 149 |
Keyword arguments |
| 150 |
~~~~~~~~~~~~~~~~~ |
| 151 |
|
| 152 |
We can also pass strategies using keyword arguments: |
| 153 |
|
| 154 |
.. code-block:: python |
| 155 |
|
| 156 |
@given(lst=st.lists(st.floats()), n=st.integers()) # <-- changed |
| 157 |
def test_multiple_arguments(n, lst): |
| 158 |
pass |
| 159 |
|
| 160 |
Note that even though we changed the order the parameters to |@given| appear, we also explicitly told it which parameters to pass to by using keyword arguments, so the meaning of the test hasn't changed. |
| 161 |
|
| 162 |
In general, you can think of positional and keyword arguments to |@given| as being forwarded to the test arguments. |
| 163 |
|
| 164 |
.. note:: |
| 165 |
|
| 166 |
One exception is that |@given| does not support mixing positional and keyword arguments. See the |@given| documentation for more about how it handles arguments. |
| 167 |
|
| 168 |
|
| 169 |
Running Hypothesis tests |
| 170 |
------------------------ |
| 171 |
|
| 172 |
There are a few ways to run a Hypothesis test. |
| 173 |
|
| 174 |
* Explicitly call it, like ``test_is_integer()``, as we've seen. Hypothesis tests are just normal functions, except |@given| handles generating and passing values for the function arguments. |
| 175 |
* Let a test runner such as :pypi:`pytest` pick up on it (as long as the function name starts with ``test_``). |
| 176 |
|
| 177 |
Concretely, when running a Hypothesis test, Hypothesis will: |
| 178 |
|
| 179 |
* generate 100 random inputs, |
| 180 |
* run the body of the function for each input, and |
| 181 |
* report any exceptions that get raised. |
| 182 |
|
| 183 |
.. note:: |
| 184 |
|
| 185 |
The number of examples can be controlled with the |max_examples| setting. The default is 100. |
| 186 |
|
| 187 |
|
| 188 |
When to use Hypothesis and property-based testing |
| 189 |
------------------------------------------------- |
| 190 |
|
| 191 |
Property-based testing is a powerful *addition* to unit testing. It is not always a replacement. |
| 192 |
|
| 193 |
If you're having trouble coming up with a property in your code to test, we recommend trying the following: |
| 194 |
|
| 195 |
* Look for round-trip properties: encode/decode, serialize/deserialize, etc. These property-based tests tend to be both powerful and easy to write. |
| 196 |
* Look for ``@pytest.mark.parametrize`` in your existing tests. This is sometimes a good hint you can replace the parametrization with a strategy. For instance, ``@pytest.mark.parametrize("n", range(0, 100))`` could be replaced by ``@given(st.integers(0, 100 - 1))``. |
| 197 |
* Simply call your code with random inputs (of the correct shape) from Hypothesis! You might be surprised how often this finds crashes. This can be especially valuable for projects with a single entrypoint interface to a lot of underlying code. |
| 198 |
|
| 199 |
Other examples of properties include: |
| 200 |
|
| 201 |
* An optimized implementation is equivalent to a slower, but clearly correct, implementation. |
| 202 |
* A sequence of transactions in a financial system always "balances"; money never gets lost. |
| 203 |
* The derivative of a polynomial of order ``n`` has order ``n - 1``. |
| 204 |
* A type-checker, linter, formatter, or compiler does not crash when called on syntactically valid code. |
| 205 |
* `And more <https://fsharpforfunandprofit.com/posts/property-based-testing-2/>`_. |