Debian Codegraph @

hypothesis-python/docs/quickstart.rst

raw
1 Quickstart
2 ==========
3
4 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.
5
6 Install Hypothesis
7 ------------------
8
9 .. code-block:: shell
10
11 pip install hypothesis
12
13
14 Write your first test
15 ---------------------
16
17 Create a new file called ``example.py``, containing a simple test:
18
19 .. code-block:: python
20
21 # contents of example.py
22 from hypothesis import given, strategies as st
23
24 @given(st.integers())
25 def test_integers(n):
26 print(f"called with {n}")
27 assert isinstance(n, int)
28
29 test_integers()
30
31 |@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``:
32
33 .. code-block:: none
34
35 called with 0
36 called with -18588
37 called with -672780074
38 called with 32616
39 ...
40
41 We just called ``test_integers()``, without passing a value for ``n``, because Hypothesis generates random values of ``n`` for us.
42
43 .. note::
44
45 By default, Hypothesis generates 100 random inputs. You can control this with the |max_examples| setting.
46
47 Running in a test suite
48 -----------------------
49
50 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.
51
52 .. code-block:: python
53
54 # contents of example.py
55 from hypothesis import given, strategies as st
56
57 @given(st.integers(0, 200))
58 def test_integers(n):
59 assert n < 50
60
61 This test will clearly fail, which can be confirmed by running ``pytest example.py``:
62
63 .. code-block:: none
64
65 $ pytest example.py
66
67 ...
68
69 @given(st.integers())
70 def test_integers(n):
71 > assert n < 50
72 E assert 50 < 50
73 E Falsifying example: test_integers(
74 E n=50,
75 E )
76
77
78 Arguments to |@given|
79 ---------------------
80
81 You can pass multiple arguments to |@given|:
82
83 .. code-block:: python
84
85 @given(st.integers(), st.text())
86 def test_integers(n, s):
87 assert isinstance(n, int)
88 assert isinstance(s, str)
89
90 Or use keyword arguments:
91
92 .. code-block:: python
93
94 @given(n=st.integers(), s=st.text())
95 def test_integers(n, s):
96 assert isinstance(n, int)
97 assert isinstance(s, str)
98
99 .. note::
100
101 See |@given| for details about how |@given| handles different types of arguments.
102
103 Filtering inside a test
104 -----------------------
105
106 Sometimes, you need to remove invalid cases from your test. The best way to do this is with |.filter|:
107
108 .. code-block:: python
109
110 @given(st.integers().filter(lambda n: n % 2 == 0))
111 def test_integers(n):
112 assert n % 2 == 0
113
114 For more complicated conditions, you can use |assume|, which tells Hypothesis to discard any test case with a false-y argument:
115
116 .. code-block:: python
117
118 @given(st.integers(), st.integers())
119 def test_integers(n1, n2):
120 assume(n1 != n2)
121 # n1 and n2 are guaranteed to be different here
122
123 .. note::
124
125 You can learn more about |.filter| and |assume| in the :doc:`/tutorial/adapting-strategies` tutorial page.
126
127 Dependent generation
128 --------------------
129
130 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``.
131
132 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.
133
134 .. code-block:: python
135
136 @st.composite
137 def ordered_pairs(draw):
138 n1 = draw(st.integers())
139 n2 = draw(st.integers(min_value=n1))
140 return (n1, n2)
141
142 @given(ordered_pairs())
143 def test_pairs_are_ordered(pair):
144 n1, n2 = pair
145 assert n1 <= n2
146
147 In more complex cases, you might need to interleave generation and test code. In this case, use |st.data|.
148
149 .. code-block:: python
150
151 @given(st.data(), st.text(min_size=1))
152 def test_string_characters_are_substrings(data, string):
153 assert isinstance(string, str)
154 index = data.draw(st.integers(0, len(string) - 1))
155 assert string[index] in string
156
157 Combining Hypothesis with pytest
158 --------------------------------
159
160 Hypothesis works with pytest features, like |pytest.mark.parametrize|:
161
162 .. code-block:: python
163
164 import pytest
165
166 from hypothesis import given, strategies as st
167
168 @pytest.mark.parametrize("operation", [reversed, sorted])
169 @given(st.lists(st.integers()))
170 def test_list_operation_preserves_length(operation, lst):
171 assert len(lst) == len(list(operation(lst)))
172
173 Hypothesis also works with pytest fixtures:
174
175 .. code-block:: python
176
177 import pytest
178
179 @pytest.fixture(scope="session")
180 def shared_mapping():
181 return {n: 0 for n in range(101)}
182
183 @given(st.integers(0, 100))
184 def test_shared_mapping_keys(shared_mapping, n):
185 assert n in shared_mapping