File: quickstart.rst

package info (click to toggle)
python-hypothesis 6.138.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 15,272 kB
  • sloc: python: 62,853; ruby: 1,107; sh: 253; makefile: 41; javascript: 6
file content (185 lines) | stat: -rw-r--r-- 5,252 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
Quickstart
==========

This is a lightning introduction to the most important features of Hypothesis; enough to get you started writing tests. The :doc:`tutorial <tutorial/index>` introduces these features (and more) in greater detail.

Install Hypothesis
------------------

.. code-block:: shell

    pip install hypothesis


Write your first test
---------------------

Create a new file called ``example.py``, containing a simple test:

.. code-block:: python

    # contents of example.py
    from hypothesis import given, strategies as st

    @given(st.integers())
    def test_integers(n):
        print(f"called with {n}")
        assert isinstance(n, int)

    test_integers()

|@given| is the standard entrypoint to Hypothesis. It takes a *strategy*, which describes the type of inputs you want the decorated function to accept. When we call ``test_integers``, Hypothesis will generate random integers (because we used the |st.integers| strategy) and pass them as ``n``. Let's see that in action now by running ``python example.py``:

.. code-block:: none

    called with 0
    called with -18588
    called with -672780074
    called with 32616
    ...

We can just call ``test_integers()``, without passing a value for ``n``, because Hypothesis takes care of generating values of ``n`` for us.

.. note::

    By default, Hypothesis generates 100 random examples. You can control this with the |max_examples| setting.

Running in a test suite
-----------------------

A Hypothesis test is still a regular python function, which means pytest or unittest will pick it up and run it in all the normal ways.

.. code-block:: python

    # contents of example.py
    from hypothesis import given, strategies as st

    @given(st.integers(0, 200))
    def test_integers(n):
        assert n < 50

This test will clearly fail, which can be confirmed by running ``pytest example.py``:

.. code-block:: none

    $ pytest example.py

        ...

        @given(st.integers())
        def test_integers(n):
    >       assert n < 50
    E       assert 50 < 50
    E       Falsifying example: test_integers(
    E           n=50,
    E       )


Arguments to |@given|
---------------------

You can pass multiple arguments to |@given|:

.. code-block:: python

    @given(st.integers(), st.text())
    def test_integers(n, s):
        assert isinstance(n, int)
        assert isinstance(s, str)

Or use keyword arguments:

.. code-block:: python

    @given(n=st.integers(), s=st.text())
    def test_integers(n, s):
        assert isinstance(n, int)
        assert isinstance(s, str)

.. note::

    See |@given| for details about how |@given| handles different types of arguments.

Filtering inside a test
-----------------------

Sometimes, you need to remove invalid cases from your test. The best way to do this is with |.filter|:

.. code-block:: python

    @given(st.integers().filter(lambda n: n % 2 == 0))
    def test_integers(n):
        assert n % 2 == 0

For more complicated conditions, you can use |assume|, which tells Hypothesis to discard any test case with a false-y argument:

.. code-block:: python

    @given(st.integers(), st.integers())
    def test_integers(n1, n2):
        assume(n1 != n2)
        # n1 and n2 are guaranteed to be different here

.. note::

    You can learn more about |.filter| and |assume| in the :doc:`/tutorial/adapting-strategies` tutorial page.

Dependent generation
--------------------

You may want an input to depend on the value of another input. For instance, you might want to generate two integers ``n1`` and ``n2`` where ``n1 <= n2``.

You can do this using the |st.composite| strategy. |st.composite| lets you define a new strategy which is itself built by drawing values from other strategies, using the automatically-passed ``draw`` function.

.. code-block:: python

    @st.composite
    def ordered_pairs(draw):
        n1 = draw(st.integers())
        n2 = draw(st.integers(min_value=n1))
        return (n1, n2)

    @given(ordered_pairs())
    def test_pairs_are_ordered(pair):
        n1, n2 = pair
        assert n1 <= n2

In more complex cases, you might need to interleave generation and test code. In this case, use |st.data|.

.. code-block:: python

    @given(st.data(), st.text(min_size=1))
    def test_string_characters_are_substrings(data, string):
        assert isinstance(string, str)
        index = data.draw(st.integers(0, len(string) - 1))
        assert string[index] in string

Combining Hypothesis with pytest
--------------------------------

Hypothesis works with pytest features, like :ref:`pytest:pytest.mark.parametrize ref`:

.. code-block:: python

    import pytest

    from hypothesis import given, strategies as st

    @pytest.mark.parametrize("operation", [reversed, sorted])
    @given(st.lists(st.integers()))
    def test_list_operation_preserves_length(operation, lst):
        assert len(lst) == len(list(operation(lst)))

Hypothesis also works with pytest fixtures:

.. code-block:: python

    import pytest

    @pytest.fixture(scope="session")
    def shared_mapping():
        return {n: 0 for n in range(101)}

    @given(st.integers(0, 100))
    def test_shared_mapping_keys(shared_mapping, n):
        assert n in shared_mapping