Debian Codegraph @

hypothesis-python/tests/patching/test_patching.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import re
12 from datetime import datetime
13 from pathlib import Path
14
15 import pytest
16
17 from hypothesis.extra._patching import (
18 FAIL_MSG,
19 HEADER,
20 get_patch_for,
21 indent,
22 make_patch,
23 )
24 from hypothesis.internal.compat import WINDOWS
25
26 from .callables import WHERE, Cases, covered, fn, undef_name
27 from .toplevel import WHERE_TOP, fn_top
28 from tests.common.utils import skipif_threading
29
30 SIMPLE = (
31 fn,
32 ("fn(\n x=1,\n)", FAIL_MSG),
33 indent('@example(x=1).via("discovered failure")', prefix="+"),
34 )
35 CASES = (
36 Cases.mth,
37 ('mth(\n n=100,\n label="a long label which forces a newline",\n)', FAIL_MSG),
38 indent(
39 '@example(n=100, label="a long label which forces a newline")'
40 '.via(\n "discovered failure"\n)',
41 prefix="+ ",
42 ),
43 )
44 TOPLEVEL = (
45 fn_top,
46 ("fn_top(\n x=1,\n)", FAIL_MSG),
47 indent('@hypothesis.example(x=1).via("discovered failure")', prefix="+"),
48 )
49 COVERING = (
50 covered,
51 ("covered(\n x=0,\n)", "covering example"),
52 indent('@example(x=1).via("covering example")', prefix="-")
53 + "\n"
54 + indent('@example(x=0).via("covering example")', prefix="+"),
55 )
56 UNDEF_NAME = (
57 undef_name,
58 ("undef_name(\n array=array([100], dtype=int8),\n)", FAIL_MSG),
59 '+@example(array=np.array([100], dtype=np.int8)).via("discovered failure")',
60 )
61
62
63 def strip_trailing_whitespace(s):
64 """Patches have whitespace-only lines; strip that out."""
65 return re.sub(r" +$", "", s, flags=re.MULTILINE)
66
67
68 @pytest.mark.parametrize(
69 "tst, example, expected",
70 [
71 pytest.param(*SIMPLE, id="simple"),
72 pytest.param(*CASES, id="cases"),
73 ],
74 )
75 def test_adds_simple_patch(tst, example, expected):
76 where, before, after = get_patch_for(tst, [example])
77 assert Path(where) == WHERE
78 added = set(after.splitlines()) - set(before.splitlines())
79 assert added == {line.lstrip("+") for line in expected.splitlines()}
80
81
82 SIMPLE_PATCH_BODY = f'''\
83 --- ./{WHERE}
84 +++ ./{WHERE}
85 @@ -21,6 +21,7 @@
86
87
88 @given(st.integers())
89 {{0}}
90 def fn(x):
91 """A trivial test function."""
92
93 '''
94 CASES_PATCH_BODY = f'''\
95 --- ./{WHERE}
96 +++ ./{WHERE}
97 @@ -28,6 +28,9 @@
98 class Cases:
99 @example(n=0, label="whatever")
100 @given(st.integers(), st.text())
101 {{0}}
102 def mth(self, n, label):
103 """Indented method with existing example decorator."""
104
105 '''
106 TOPLEVEL_PATCH_BODY = f'''\
107 --- ./{WHERE_TOP}
108 +++ ./{WHERE_TOP}
109 @@ -19,5 +19,6 @@
110
111
112 @hypothesis.given(st.integers())
113 {{0}}
114 def fn_top(x):
115 """A trivial test function."""
116 '''
117 COVERING_PATCH_BODY = f'''\
118 --- ./{WHERE}
119 +++ ./{WHERE}
120 @@ -34,7 +34,7 @@
121
122 @given(st.integers())
123 @example(x=2).via("not a literal when repeated " * 2)
124 {{0}}
125 def covered(x):
126 """A test function with a removable explicit example."""
127
128 '''
129
130 UNDEF_NAME_PATCH_BODY = f"""\
131 --- ./{WHERE}
132 +++ ./{WHERE}
133 @@ -40,6 +40,7 @@
134
135
136 @given(npst.arrays(np.int8, 1))
137 {{0}}
138 def undef_name(array):
139 assert sum(array) < 100
140
141 """
142
143
144 @pytest.mark.parametrize(
145 "tst, example, expected, body, remove",
146 [
147 pytest.param(*SIMPLE, SIMPLE_PATCH_BODY, (), id="simple"),
148 pytest.param(*CASES, CASES_PATCH_BODY, (), id="cases"),
149 pytest.param(*TOPLEVEL, TOPLEVEL_PATCH_BODY, (), id="toplevel"),
150 pytest.param(
151 *COVERING, COVERING_PATCH_BODY, ("covering example",), id="covering"
152 ),
153 pytest.param(*UNDEF_NAME, UNDEF_NAME_PATCH_BODY, (), id="undef_name"),
154 ],
155 )
156 def test_make_full_patch(tst, example, expected, body, remove):
157 when = datetime.now()
158 msg = "a message from the test"
159 author = "the patch author"
160 expected = HEADER.format(when=when, msg=msg, author=author) + body.format(expected)
161
162 triple = get_patch_for(tst, [example], strip_via=remove)
163 got = make_patch([triple], when=when, msg=msg, author=author)
164 stripped = strip_trailing_whitespace(got)
165
166 assert stripped.splitlines() == expected.splitlines()
167
168
169 @pytest.mark.parametrize("n", [0, 1, 2])
170 def test_invalid_syntax_cases_dropped(n):
171 tst, (ex, via), _expected = SIMPLE
172 example_ls = [(ex.replace("x=1", f"x={x}"), via) for x in range(n)]
173 example_ls.insert(-1, ("fn(\n x=<__main__.Cls object at 0x>,\n)", FAIL_MSG))
174
175 got = get_patch_for(tst, example_ls)
176 if n == 0:
177 assert got is None, "no valid examples, and hence no patch"
178 return
179 where, _, after = got
180
181 assert Path(where) == WHERE
182 assert after.count("@example(x=") == n
183
184
185 def test_no_example_for_data_strategy():
186 assert get_patch_for(fn, [("fn(data=data(...))", "msg")]) is None
187 assert get_patch_for(fn, [("fn(123, data(...))", "msg")]) is None
188
189 assert get_patch_for(fn, [("fn(data='data(...)')", "msg")]) is not None
190 assert get_patch_for(fn, [("fn(Foo(data=data(...)))", "msg")]) is not None
191
192
193 def test_patch_order_preserved():
194 (_fname, _before, after) = get_patch_for(
195 fn, [("fn(a=1)", "msg"), ("fn(b=2)", "msg")]
196 )
197 assert after.startswith(
198 '@given(st.integers())\n@example(a=1).via("msg")\n@example(b=2).via("msg")'
199 )
200
201 (_fname, _before, after) = get_patch_for(
202 fn, [("fn(b=2)", "msg"), ("fn(a=1)", "msg")]
203 )
204 assert after.startswith(
205 '@given(st.integers())\n@example(b=2).via("msg")\n@example(a=1).via("msg")'
206 )
207
208
209 def test_deduplicates_examples():
210 tst, example, expected = SIMPLE
211 where, _, after = get_patch_for(tst, [example, example])
212 assert Path(where) == WHERE
213 assert after.count(expected.lstrip("+")) == 1
214
215
216 def test_irretrievable_callable():
217 # Check that we return None instead of raising an exception
218 old_module = fn.__module__
219 try:
220 fn.__module__ = "this.does.not.exist"
221 triple = get_patch_for(fn, [(SIMPLE[1], FAIL_MSG)])
222 finally:
223 fn.__module__ = old_module
224 assert triple is None
225
226
227 TESTSCRIPT_DUMPS_PATCH = """
228 from hypothesis import Phase, given, settings, strategies as st
229
230 @settings(phases=list(Phase))
231 @given(st.integers(0, 10), st.integers(0, 10))
232 def test_failing_pbt(x, y):
233 assert not x
234 """
235 ADDED_LINES = """
236 +@example(
237 + x=1,
238 + y=0, # or any other generated value
239 +).via("discovered failure")
240 """
241
242
243 @skipif_threading
244 @pytest.mark.skipif(WINDOWS, reason="backslash support is tricky")
245 def test_pytest_reports_patch_file_location(pytester):
246 script = pytester.makepyfile(TESTSCRIPT_DUMPS_PATCH)
247 result = pytester.runpytest(script)
248 result.assert_outcomes(failed=1)
249
250 fname_pat = r"\.hypothesis/patches/\d{4}-\d\d-\d\d--[0-9a-f]{8}.patch"
251 pattern = f"`git apply ({fname_pat})` to add failing examples to your code\\."
252 print(f"{pattern=}")
253 print(f"result.stdout=\n{indent(str(result.stdout), ' ')}")
254 fname = re.search(pattern, str(result.stdout)).group(1)
255 patch = Path(pytester.path).joinpath(fname).read_text(encoding="utf-8")
256 print(patch)
257 assert ADDED_LINES in patch