Debian Codegraph @

hypothesis-python/tests/ghostwriter/test_expected_output.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 """
12 'Golden master' tests for the ghostwriter.
13
14 To update the recorded outputs, run:
15
16 pytest test_expected_output.py --hypothesis-update-outputs
17 """
18
19 import ast
20 import base64
21 import builtins
22 import collections.abc
23 import operator
24 import pathlib
25 import re
26 import subprocess
27 import sys
28 from collections.abc import Sequence
29
30 import black
31 import numpy
32 import numpy.typing
33 import pytest
34 from example_code.future_annotations import (
35 add_custom_classes,
36 invalid_types,
37 merge_dicts,
38 )
39
40 import hypothesis
41 from hypothesis import settings
42 from hypothesis.extra import ghostwriter
43 from hypothesis.utils.conventions import not_set
44
45 pytestmark = pytest.mark.skipif(
46 settings.get_current_profile_name() == "threading",
47 reason="ghostwriter is not thread safe",
48 )
49
50
51 @pytest.fixture
52 def update_recorded_outputs(request):
53 return request.config.getoption("--hypothesis-update-outputs")
54
55
56 def get_recorded(name, actual=""):
57 file_ = pathlib.Path(__file__).parent / "recorded" / f"{name}.txt"
58 if actual:
59 file_.write_text(actual, encoding="utf-8")
60 return file_.read_text(encoding="utf-8")
61
62
63 def timsort(seq: Sequence[int]) -> Sequence[int]:
64 return sorted(seq)
65
66
67 def with_docstring(a, b, c, d=int, e=lambda x: f"xx{x}xx") -> None:
68 """Demonstrates parsing params from the docstring
69
70 :param a: sphinx docstring style
71 :type a: sequence of integers
72
73 b (list, tuple, or None): Google docstring style
74
75 c : {"foo", "bar", or None}
76 Numpy docstring style
77 """
78
79
80 class A_Class:
81 @classmethod
82 def a_classmethod(cls, arg: int):
83 pass
84
85 @staticmethod
86 def a_staticmethod(arg: int):
87 pass
88
89
90 def add(a: float, b: float) -> float:
91 return a + b
92
93
94 def divide(a: int, b: int) -> float:
95 """This is a RST-style docstring for `divide`.
96
97 :raises ZeroDivisionError: if b == 0
98 """
99 return a / b
100
101
102 def optional_parameter(a: float, b: float | None) -> float:
103 return optional_union_parameter(a, b)
104
105
106 def optional_union_parameter(a: float, b: float | int | None) -> float:
107 return a if b is None else a + b
108
109
110 def union_sequence_parameter(items: Sequence[float | int]) -> float:
111 return sum(items)
112
113
114 def sequence_from_collections(items: collections.abc.Sequence[int]) -> int:
115 return min(items)
116
117
118 def various_numpy_annotations(
119 f: numpy.typing.NDArray[numpy.float64],
120 fc: numpy.typing.NDArray[numpy.float64 | numpy.complex128],
121 union: numpy.typing.NDArray[numpy.float64 | numpy.complex128] | None,
122 ):
123 pass
124
125
126 # Note: for some of the `expected` outputs, we replace away some small
127 # parts which vary between minor versions of Python.
128 @pytest.mark.parametrize(
129 "data",
130 [
131 ("fuzz_sorted", lambda: ghostwriter.fuzz(sorted)),
132 (
133 "fuzz_sorted_with_annotations",
134 lambda: ghostwriter.fuzz(sorted, annotate=True),
135 ),
136 ("fuzz_with_docstring", lambda: ghostwriter.fuzz(with_docstring)),
137 ("fuzz_classmethod", lambda: ghostwriter.fuzz(A_Class.a_classmethod)),
138 ("fuzz_staticmethod", lambda: ghostwriter.fuzz(A_Class.a_staticmethod)),
139 ("fuzz_ufunc", lambda: ghostwriter.fuzz(numpy.add)),
140 ("magic_gufunc", lambda: ghostwriter.magic(numpy.matmul)),
141 ("optional_parameter", lambda: ghostwriter.magic(optional_parameter)),
142 (
143 "optional_union_parameter",
144 lambda: ghostwriter.magic(optional_union_parameter),
145 ),
146 (
147 "union_sequence_parameter",
148 lambda: ghostwriter.magic(union_sequence_parameter),
149 ),
150 (
151 "sequence_from_collections",
152 lambda: ghostwriter.magic(sequence_from_collections),
153 ),
154 ("add_custom_classes", lambda: ghostwriter.magic(add_custom_classes)),
155 ("merge_dicts", lambda: ghostwriter.magic(merge_dicts)),
156 ("invalid_types", lambda: ghostwriter.magic(invalid_types)),
157 ("magic_base64_roundtrip", lambda: ghostwriter.magic(base64.b64encode)),
158 (
159 "magic_base64_roundtrip_with_annotations",
160 lambda: ghostwriter.magic(base64.b64encode, annotate=True),
161 ),
162 ("re_compile", lambda: ghostwriter.fuzz(re.compile)),
163 (
164 "re_compile_except",
165 lambda: ghostwriter.fuzz(re.compile, except_=re.error).replace(
166 "re.PatternError", "re.error" # changed in Python 3.13
167 ),
168 ),
169 ("re_compile_unittest", lambda: ghostwriter.fuzz(re.compile, style="unittest")),
170 pytest.param(
171 ("base64_magic", lambda: ghostwriter.magic(base64)),
172 marks=pytest.mark.skipif("sys.version_info[:2] >= (3, 10)"),
173 ),
174 ("sorted_idempotent", lambda: ghostwriter.idempotent(sorted)),
175 ("timsort_idempotent", lambda: ghostwriter.idempotent(timsort)),
176 (
177 "timsort_idempotent_asserts",
178 lambda: ghostwriter.idempotent(timsort, except_=AssertionError),
179 ),
180 pytest.param(
181 ("eval_equivalent", lambda: ghostwriter.equivalent(eval, ast.literal_eval)),
182 marks=[pytest.mark.skipif(sys.version_info[:2] >= (3, 13), reason="kw")],
183 ),
184 (
185 "sorted_self_equivalent",
186 lambda: ghostwriter.equivalent(sorted, sorted, sorted),
187 ),
188 (
189 "sorted_self_equivalent_with_annotations",
190 lambda: ghostwriter.equivalent(sorted, sorted, sorted, annotate=True),
191 ),
192 ("addition_op_magic", lambda: ghostwriter.magic(add)),
193 ("multiplication_magic", lambda: ghostwriter.magic(operator.mul)),
194 ("matmul_magic", lambda: ghostwriter.magic(operator.matmul)),
195 (
196 "addition_op_multimagic",
197 lambda: ghostwriter.magic(add, operator.add, numpy.add),
198 ),
199 ("division_fuzz_error_handler", lambda: ghostwriter.fuzz(divide)),
200 (
201 "division_binop_error_handler",
202 lambda: ghostwriter.binary_operation(divide, identity=1),
203 ),
204 (
205 "division_roundtrip_error_handler",
206 lambda: ghostwriter.roundtrip(divide, operator.mul),
207 ),
208 (
209 "division_roundtrip_error_handler_without_annotations",
210 lambda: ghostwriter.roundtrip(divide, operator.mul, annotate=False),
211 ),
212 (
213 "division_roundtrip_arithmeticerror_handler",
214 lambda: ghostwriter.roundtrip(
215 divide, operator.mul, except_=ArithmeticError
216 ),
217 ),
218 (
219 "division_roundtrip_typeerror_handler",
220 lambda: ghostwriter.roundtrip(divide, operator.mul, except_=TypeError),
221 ),
222 (
223 "division_operator",
224 lambda: ghostwriter.binary_operation(
225 operator.truediv, associative=False, commutative=False
226 ),
227 ),
228 (
229 "division_operator_with_annotations",
230 lambda: ghostwriter.binary_operation(
231 operator.truediv, associative=False, commutative=False, annotate=True
232 ),
233 ),
234 (
235 "multiplication_operator",
236 lambda: ghostwriter.binary_operation(
237 operator.mul, identity=1, distributes_over=operator.add
238 ),
239 ),
240 (
241 "multiplication_operator_unittest",
242 lambda: ghostwriter.binary_operation(
243 operator.mul,
244 identity=1,
245 distributes_over=operator.add,
246 style="unittest",
247 ),
248 ),
249 (
250 "sorted_self_error_equivalent_simple",
251 lambda: ghostwriter.equivalent(sorted, sorted, allow_same_errors=True),
252 ),
253 (
254 "sorted_self_error_equivalent_threefuncs",
255 lambda: ghostwriter.equivalent(
256 sorted, sorted, sorted, allow_same_errors=True
257 ),
258 ),
259 (
260 "sorted_self_error_equivalent_1error",
261 lambda: ghostwriter.equivalent(
262 sorted,
263 sorted,
264 allow_same_errors=True,
265 except_=ValueError,
266 ),
267 ),
268 (
269 "sorted_self_error_equivalent_2error_unittest",
270 lambda: ghostwriter.equivalent(
271 sorted,
272 sorted,
273 allow_same_errors=True,
274 except_=(TypeError, ValueError),
275 style="unittest",
276 ),
277 ),
278 ("magic_class", lambda: ghostwriter.magic(A_Class)),
279 pytest.param(
280 ("magic_builtins", lambda: ghostwriter.magic(builtins)),
281 marks=[
282 pytest.mark.skipif(
283 sys.version_info[:2] != (3, 10),
284 reason="often small changes",
285 )
286 ],
287 ),
288 pytest.param(
289 (
290 "magic_numpy",
291 lambda: ghostwriter.magic(various_numpy_annotations, annotate=False),
292 ),
293 marks=pytest.mark.skipif(various_numpy_annotations is add, reason="<=3.9"),
294 ),
295 ],
296 ids=lambda x: x[0],
297 )
298 def test_ghostwriter_example_outputs(update_recorded_outputs, data):
299 name, get_actual = data
300 # ghostwriter computations can be expensive, so defer collection-time
301 # computations until test-time
302 actual = get_actual()
303 expected = get_recorded(name, actual * update_recorded_outputs)
304 assert actual == expected # We got the expected source code
305 exec(expected, {}) # and there are no SyntaxError or NameErrors
306
307
308 def test_ghostwriter_on_hypothesis(update_recorded_outputs):
309 actual = (
310 ghostwriter.magic(hypothesis)
311 .replace("Strategy[+Ex]", "Strategy")
312 .replace("hypothesis._settings.settings", "hypothesis.settings")
313 )
314 # hypothesis._settings.settings wraps the line before replacement, and doesn't
315 # after replacement
316 actual = black.format_str(actual, mode=black.Mode())
317 expected = get_recorded("hypothesis_module_magic", actual * update_recorded_outputs)
318 if sys.version_info[:2] == (3, 10):
319 assert actual == expected
320 exec(expected, {"not_set": not_set})
321
322
323 def test_ghostwriter_suggests_submodules_for_empty_toplevel(
324 tmp_path, update_recorded_outputs
325 ):
326 foo = tmp_path / "foo"
327 foo.mkdir()
328 (foo / "__init__.py").write_text("from . import bar\n", encoding="utf-8")
329 (foo / "bar.py").write_text("def baz(x: int): ...\n", encoding="utf-8")
330
331 proc = subprocess.run(
332 ["hypothesis", "write", "foo"],
333 check=True,
334 capture_output=True,
335 encoding="utf-8",
336 cwd=tmp_path,
337 )
338 actual = proc.stdout.replace(re.search(r"from '(.+)foo/", proc.stdout).group(1), "")
339
340 expected = get_recorded("nothing_found", actual * update_recorded_outputs)
341 assert actual == expected # We got the expected source code
342 exec(expected, {}) # and there are no SyntaxError or NameErrors