Debian Codegraph @

hypothesis-python/docs/tutorial/flaky.rst

raw
1 Flaky failures
2 ==============
3
4 Have you ever had a test fail, and then you re-run it, only for the test to magically pass? That is a *flaky test*. A flaky test is one which might behave differently when called again. You can think of it as a test which is not deterministic.
5
6 Any test can be flaky, but because Hypothesis runs your test many times, Hypothesis tests are particularly likely to uncover flaky behavior.
7
8 Note that Hypothesis does not require tests to be fully deterministic. Only the sequence of calls to Hypothesis APIs like ``draw`` from |st.composite| and the outcome of the test (pass or fail) need to be deterministic. This means you can use randomness, threads, or nondeterminism in your test, as long as it doesn't impact anything Hypothesis can see.
9
10 Why is flakiness bad?
11 ---------------------
12
13 Hypothesis raises an exception when it detects flakiness. This might seem extreme, relative to a simple warning. But there are good reasons to consider flakiness a fatal error.
14
15 .. TODO_DOCS: link to not-yet-written database page
16
17 * Hypothesis relies on deterministic behavior for the database to work.
18 * Flakiness makes debugging failures substantially harder if the failing input reported by Hypothesis only flakily reproduces.
19 * Flakiness makes effectively exploration of the test's behavior space by Hypothesis difficult or impossible.
20
21 Common sources of flakiness
22 ---------------------------
23
24 Here is a quick and non-exhaustive enumeration of some reasons you might encounter flakiness:
25
26 * Decisions based on global state.
27 * Explicit dependencies between inputs.
28 * Test depends on filesystem or database state which isn't reset between inputs.
29 * Un-managed sources of randomness. This includes standard PRNGs (see also |register_random|), but also thread scheduling, network timing, etc.
30
31 .. note::
32
33 If your tests depend on global state, consider replacing that state with |st.shared|. This is a common way to refactor your test to bring conceptually-global state under the control and visibility of Hypothesis.
34
35 Types of flakiness
36 ------------------
37
38 When Hypothesis detects that a test is flaky, it will raise one of two |Flaky| exceptions.
39
40 Flaky failure
41 ~~~~~~~~~~~~~
42
43 The most common form of flakiness is that Hypothesis finds a failure, but then replaying that input does not reproduce the failure. For example, here is a contrived test which only fails the first time it is called:
44
45 .. code-block:: python
46
47 called = False
48
49 @given(st.integers())
50 def test_fails_flakily(n):
51 global called
52 if not called:
53 called = True
54 assert False
55
56 The first time Hypothesis generates an input, this test will fail. But when Hypothesis tries replaying that failure—by generating the same input—the test will succeed. This test is flaky.
57
58 As a result, running ``test_fails_flakily()`` will raise |FlakyFailure|. |FlakyFailure| is an ``ExceptionGroup``, which contains the origin failure as a sub-exception:
59
60 .. code-block:: none
61
62 + Exception Group Traceback (most recent call last):
63 | hypothesis.errors.FlakyFailure: Hypothesis test_fails_flakily(n=0) produces unreliable results: Falsified on the first call but did not on a subsequent one (1 sub-exception)
64 | Falsifying example: test_fails_flakily(
65 | n=0,
66 | )
67 | Failed to reproduce exception. Expected:
68 | Traceback (most recent call last):
69 | File "/Users/tybug/Desktop/sandbox2.py", line 13, in test_fails_flakily
70 | assert False
71 | ^^^^^
72 | AssertionError
73 +-+---------------- 1 ----------------
74 | ...
75 | Traceback (most recent call last):
76 | File "/Users/tybug/Desktop/sandbox2.py", line 13, in test_fails_flakily
77 | assert False
78 | ^^^^^
79 | AssertionError
80 +------------------------------------
81
82 The solution to seeing |FlakyFailure| is to refactor the test to not depend on external state. In this case, the external state is the variable ``called``.
83
84 Flaky strategy definition
85 ~~~~~~~~~~~~~~~~~~~~~~~~~
86
87 Each strategy must 'do the same thing' (again, as seen by Hypothesis) if we replay a previously-seen input. Failing to do so is a more subtle but equally serious form of flakiness, which leaves us unable to shrink to a minimal failing input, or even reliably report the failure in future runs.
88
89 One easy way for this to occur is if a strategy depends on external state. For example, this strategy filters out previously-generated integers, including those seen in any previous test case:
90
91 .. code-block:: python
92
93 seen = set()
94
95 @st.composite
96 def unique_ints(draw):
97 while (n := draw(st.integers())) in seen:
98 pass
99 seen.add(n)
100 return n
101
102 @given(unique_ints(), unique_ints())
103 def test_ints(x, y): ...
104
105 By using ``seen``, this test is relying on outside state! In the first test case where |st.integers| generates ``0``, ``unique_ints`` draws only one integer. But if in the next test case |st.integers| generates ``0``, ``unique_ints`` has to draw two integers because ``0`` is already in ``seen``. This means data generation is not deterministic.
106
107 As a result, running ``test_ints()`` will raise |FlakyStrategyDefinition|. The solution is to refactor the strategy to not depend on external state. One way to do this is using |st.shared|:
108
109 .. code-block:: python
110
111 @st.composite
112 def unique_ints(draw):
113 seen_this_test = draw(st.shared(st.builds(set), key="seen_ints"))
114 while (n := draw(st.integers())) in seen_this_test:
115 pass
116 seen_this_test.add(n)
117 return n