Debian Codegraph @

hypothesis-python/tests/ghostwriter/test_ghostwriter.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 ast
12 import enum
13 import json
14 import re
15 import socket
16 import sys
17 import unittest
18 import unittest.mock
19 from collections.abc import KeysView, Sequence, Sized, ValuesView
20 from decimal import Decimal
21 from pathlib import Path
22 from textwrap import dedent
23 from types import FunctionType, ModuleType
24 from typing import Any, ForwardRef
25
26 import attr
27 import click
28 import pytest
29
30 from hypothesis import HealthCheck, assume, settings
31 from hypothesis.errors import InvalidArgument, Unsatisfiable
32 from hypothesis.extra import cli, ghostwriter
33 from hypothesis.internal.compat import BaseExceptionGroup
34 from hypothesis.strategies import builds, from_type, just, lists
35 from hypothesis.strategies._internal.core import from_regex
36 from hypothesis.strategies._internal.lazy import LazyStrategy
37
38 varied_excepts = pytest.mark.parametrize("ex", [(), ValueError, (TypeError, re.error)])
39
40
41 pytestmark = pytest.mark.skipif(
42 settings.get_current_profile_name() == "threading",
43 reason="ghostwriter is not thread safe",
44 )
45
46
47 def get_test_function(source_code, settings_decorator=lambda fn: fn):
48 # A helper function to get the dynamically-defined test function.
49 # Note that this also tests that the module is syntatically-valid,
50 # AND free from undefined names, import problems, and so on.
51 namespace = {}
52 try:
53 exec(source_code, namespace)
54 except Exception:
55 print(f"************\n{source_code}\n************")
56 raise
57 tests = [
58 v
59 for k, v in namespace.items()
60 if k.startswith(("test_", "Test")) and not isinstance(v, ModuleType)
61 ]
62 assert len(tests) == 1, tests
63 return settings_decorator(tests[0])
64
65
66 @pytest.mark.parametrize(
67 "badness", ["not an exception", BaseException, [ValueError], (Exception, "bad")]
68 )
69 def test_invalid_exceptions(badness):
70 with pytest.raises(InvalidArgument):
71 ghostwriter._check_except(badness)
72
73
74 def test_style_validation():
75 ghostwriter._check_style("pytest")
76 ghostwriter._check_style("unittest")
77 with pytest.raises(InvalidArgument):
78 ghostwriter._check_style("not a valid style")
79
80
81 def test_strategies_with_invalid_syntax_repr_as_nothing():
82 msg = "$$ this repr is not Python syntax $$"
83
84 class NoRepr:
85 def __repr__(self):
86 return msg
87
88 s = just(NoRepr())
89 assert repr(s) == f"just({msg})"
90 assert ghostwriter._valid_syntax_repr(s)[1] == "nothing()"
91
92
93 class AnEnum(enum.Enum):
94 a = "value of AnEnum.a"
95 b = "value of AnEnum.b"
96
97
98 def takes_enum(foo=AnEnum.a):
99 # This can only fail if we use the default argument to guess
100 # that any instance of that enum type should be allowed.
101 assert foo != AnEnum.b
102
103
104 def test_ghostwriter_exploits_arguments_with_enum_defaults():
105 source_code = ghostwriter.fuzz(takes_enum)
106 test = get_test_function(source_code)
107 with pytest.raises(AssertionError):
108 test()
109
110
111 def timsort(seq: Sequence[int]) -> list[int]:
112 return sorted(seq)
113
114
115 def non_type_annotation(x: 3): # type: ignore
116 pass
117
118
119 def annotated_any(x: Any):
120 pass
121
122
123 space_in_name = type("a name", (type,), {"__init__": lambda self: None})
124
125
126 class NotResolvable:
127 def __init__(self, unannotated_required):
128 pass
129
130
131 def non_resolvable_arg(x: NotResolvable):
132 pass
133
134
135 def test_flattens_one_of_repr():
136 strat = from_type(int | Sequence[int])
137 assert repr(strat).count("one_of(") == 2
138 assert ghostwriter._valid_syntax_repr(strat)[1].count("one_of(") == 1
139
140
141 def takes_keys(x: KeysView[int]) -> None:
142 pass
143
144
145 def takes_values(x: ValuesView[int]) -> None:
146 pass
147
148
149 def takes_match(x: re.Match[bytes]) -> None:
150 pass
151
152
153 def takes_pattern(x: re.Pattern[str]) -> None:
154 pass
155
156
157 def takes_sized(x: Sized) -> None:
158 pass
159
160
161 def takes_frozensets(a: frozenset[int], b: frozenset[int]) -> None:
162 pass
163
164
165 @attr.s()
166 class Foo:
167 foo: str = attr.ib()
168
169
170 def takes_attrs_class(x: Foo) -> None:
171 pass
172
173
174 @varied_excepts
175 @pytest.mark.parametrize(
176 "func",
177 [
178 re.compile,
179 json.loads,
180 json.dump,
181 timsort,
182 ast.literal_eval,
183 non_type_annotation,
184 annotated_any,
185 space_in_name,
186 non_resolvable_arg,
187 takes_keys,
188 takes_values,
189 takes_match,
190 takes_pattern,
191 takes_sized,
192 takes_frozensets,
193 takes_attrs_class,
194 ],
195 )
196 def test_ghostwriter_fuzz(func, ex):
197 source_code = ghostwriter.fuzz(func, except_=ex)
198 get_test_function(source_code)
199
200
201 def test_socket_module():
202 source_code = ghostwriter.magic(socket)
203 exec(source_code, {})
204
205
206 def test_binary_op_also_handles_frozensets():
207 # Using str.replace in a loop would convert `frozensets()` into
208 # `st.frozenst.sets()` instead of `st.frozensets()`; fixed with re.sub.
209 source_code = ghostwriter.binary_operation(takes_frozensets)
210 exec(source_code, {})
211
212
213 def test_binary_op_with_numpy_arrays_includes_imports():
214 # Regression test for issue #4576: binary_operation should include imports
215 # for numpy strategies like arrays(), scalar_dtypes(), and array_shapes()
216 pytest.importorskip("numpy")
217 import numpy as np
218
219 def numpy_add(a: np.ndarray, b: np.ndarray) -> np.ndarray:
220 return a + b
221
222 source_code = ghostwriter.binary_operation(
223 numpy_add, associative=True, commutative=True, identity=None
224 )
225 # Check that the necessary imports are present
226 assert "from hypothesis.extra.numpy import" in source_code
227 assert "arrays" in source_code
228 assert "scalar_dtypes" in source_code
229 assert "array_shapes" in source_code
230 # Most importantly: the code should execute without NameError
231 exec(source_code, {})
232
233
234 @varied_excepts
235 @pytest.mark.parametrize(
236 "func", [re.compile, json.loads, json.dump, timsort, ast.literal_eval]
237 )
238 def test_ghostwriter_unittest_style(func, ex):
239 source_code = ghostwriter.fuzz(func, except_=ex, style="unittest")
240 assert issubclass(get_test_function(source_code), unittest.TestCase)
241
242
243 def no_annotations(foo=None, *, bar=False):
244 pass
245
246
247 def test_inference_from_defaults_and_none_booleans_reprs_not_just_and_sampled_from():
248 source_code = ghostwriter.fuzz(no_annotations)
249 assert "@given(foo=st.none(), bar=st.booleans())" in source_code
250
251
252 def hopefully_hashable(foo: set[Decimal]):
253 pass
254
255
256 def test_no_hashability_filter():
257 # In from_type, we ordinarily protect users from really weird cases like
258 # `Decimal('snan')` - a unhashable value of a hashable type - but in the
259 # ghostwriter we instead want to present this to the user for an explicit
260 # decision. They can pass `allow_nan=False`, fix their custom type's
261 # hashing logic, or whatever else; simply doing nothing will usually work.
262 source_code = ghostwriter.fuzz(hopefully_hashable)
263 assert "@given(foo=st.sets(st.decimals()))" in source_code
264 assert "_can_hash" not in source_code
265
266
267 @pytest.mark.parametrize(
268 "gw,args",
269 [
270 (ghostwriter.fuzz, ["not callable"]),
271 (ghostwriter.idempotent, ["not callable"]),
272 (ghostwriter.roundtrip, []),
273 (ghostwriter.roundtrip, ["not callable"]),
274 (ghostwriter.equivalent, [sorted]),
275 (ghostwriter.equivalent, [sorted, "not callable"]),
276 ],
277 )
278 def test_invalid_func_inputs(gw, args):
279 with pytest.raises(InvalidArgument):
280 gw(*args)
281
282
283 class A:
284 @classmethod
285 def to_json(cls, obj: dict | list) -> str:
286 return json.dumps(obj)
287
288 @classmethod
289 def from_json(cls, obj: str) -> dict | list:
290 return json.loads(obj)
291
292 @staticmethod
293 def static_sorter(seq: Sequence[int]) -> list[int]:
294 return sorted(seq)
295
296
297 @pytest.mark.parametrize(
298 "gw,args",
299 [
300 (ghostwriter.fuzz, [A.static_sorter]),
301 (ghostwriter.idempotent, [A.static_sorter]),
302 (ghostwriter.roundtrip, [A.to_json, A.from_json]),
303 (ghostwriter.equivalent, [A.to_json, json.dumps]),
304 ],
305 )
306 def test_class_methods_inputs(gw, args):
307 source_code = gw(*args)
308 get_test_function(source_code)()
309
310
311 def test_run_ghostwriter_fuzz():
312 # Our strategy-guessing code works for all the arguments to sorted,
313 # and we handle positional-only arguments in calls correctly too.
314 source_code = ghostwriter.fuzz(sorted)
315 assert "st.nothing()" not in source_code
316 get_test_function(source_code)()
317
318
319 class MyError(UnicodeDecodeError):
320 pass
321
322
323 @pytest.mark.parametrize(
324 "exceptions,output",
325 [
326 # Discard subclasses of other exceptions to catch, including non-builtins,
327 # and replace OSError aliases with OSError.
328 ((Exception, UnicodeError), "Exception"),
329 ((UnicodeError, MyError), "UnicodeError"),
330 ((IOError,), "OSError"),
331 ((IOError, UnicodeError), "(OSError, UnicodeError)"),
332 ],
333 )
334 def test_exception_deduplication(exceptions, output):
335 _, body = ghostwriter._make_test_body(
336 lambda: None,
337 ghost="",
338 test_body="pass",
339 except_=exceptions,
340 style="pytest",
341 annotate=False,
342 )
343 assert f"except {output}:" in body
344
345
346 def test_run_ghostwriter_roundtrip():
347 # This test covers the whole lifecycle: first, we get the default code.
348 # The first argument is unknown, so we fail to draw from st.nothing()
349 source_code = ghostwriter.roundtrip(json.dumps, json.loads)
350 with pytest.raises(Unsatisfiable):
351 get_test_function(source_code)()
352
353 # Replacing that nothing() with a strategy for JSON allows us to discover
354 # two possible failures: `nan` is not equal to itself, and if dumps is
355 # passed allow_nan=False it is a ValueError to pass a non-finite float.
356 source_code = source_code.replace(
357 "st.nothing()",
358 "st.recursive(st.one_of(st.none(), st.booleans(), st.floats(), st.text()), "
359 "lambda v: st.lists(v, max_size=2) | st.dictionaries(st.text(), v, max_size=2)"
360 ", max_leaves=2)",
361 )
362 s = settings(deadline=None, suppress_health_check=[HealthCheck.too_slow])
363 try:
364 get_test_function(source_code, settings_decorator=s)()
365 except (AssertionError, ValueError, BaseExceptionGroup):
366 pass
367
368 # Finally, restricting ourselves to finite floats makes the test pass!
369 source_code = source_code.replace(
370 "st.floats()", "st.floats(allow_nan=False, allow_infinity=False)"
371 )
372 get_test_function(source_code, settings_decorator=s)()
373
374
375 @varied_excepts
376 @pytest.mark.parametrize("func", [sorted, timsort])
377 def test_ghostwriter_idempotent(func, ex):
378 source_code = ghostwriter.idempotent(func, except_=ex)
379 test = get_test_function(source_code)
380 if "=st.nothing()" in source_code:
381 with pytest.raises(Unsatisfiable):
382 test()
383 else:
384 test()
385
386
387 def test_overlapping_args_use_union_of_strategies():
388 def f(arg: int) -> None:
389 pass
390
391 def g(arg: float) -> None:
392 pass
393
394 source_code = ghostwriter.equivalent(f, g)
395 assert "arg=st.one_of(st.integers(), st.floats())" in source_code
396
397
398 def test_module_with_mock_does_not_break():
399 # Before we added an explicit check for unspec'd mocks, they would pass
400 # through the initial validation and then fail when used in more detailed
401 # logic in the ghostwriter machinery.
402 ghostwriter.magic(unittest.mock)
403
404
405 def compose_types(x: type, y: type):
406 pass
407
408
409 def test_unrepr_identity_elem():
410 # Works with inferred identity element
411 source_code = ghostwriter.binary_operation(compose_types)
412 exec(source_code, {})
413 # and also works with explicit identity element
414 source_code = ghostwriter.binary_operation(compose_types, identity=type)
415 exec(source_code, {})
416
417
418 @pytest.mark.parametrize(
419 "strategy, imports",
420 # The specifics don't matter much here; we're just demonstrating that
421 # we can walk the strategy and collect all the objects to import.
422 [
423 # Lazy from_type() is handled without being unwrapped
424 (LazyStrategy(from_type, (enum.Enum,), {}), {("enum", "Enum")}),
425 # Mapped, filtered, and flatmapped check both sides of the method
426 (
427 builds(enum.Enum).map(Decimal),
428 {("enum", "Enum"), ("decimal", "Decimal")},
429 ),
430 (
431 builds(enum.Enum).flatmap(Decimal),
432 {("enum", "Enum"), ("decimal", "Decimal")},
433 ),
434 (
435 builds(enum.Enum).filter(Decimal).filter(re.compile),
436 {("enum", "Enum"), ("decimal", "Decimal"), ("re", "compile")},
437 ),
438 # one_of() strategies recurse into all the branches
439 (
440 builds(enum.Enum) | builds(Decimal) | builds(re.compile),
441 {("enum", "Enum"), ("decimal", "Decimal"), ("re", "compile")},
442 ),
443 # and builds() checks the arguments as well as the target
444 (
445 builds(enum.Enum, builds(Decimal), kw=builds(re.compile)),
446 {("enum", "Enum"), ("decimal", "Decimal"), ("re", "compile")},
447 ),
448 # lists recurse on imports
449 (
450 lists(builds(Decimal)),
451 {("decimal", "Decimal")},
452 ),
453 # find the needed import for from_regex if needed
454 (
455 from_regex(re.compile(".+")),
456 {"re"},
457 ),
458 # but don't add superfluous imports
459 (
460 from_regex(".+"),
461 set(),
462 ),
463 ],
464 )
465 def test_get_imports_for_strategy(strategy, imports):
466 assert ghostwriter._imports_for_strategy(strategy) == imports
467
468
469 @pytest.fixture
470 def temp_script_file():
471 """Fixture to yield a Path to a temporary file in the local directory. File name will end
472 in .py and will include an importable function.
473 """
474 p = Path("my_temp_script.py")
475 if p.exists():
476 raise FileExistsError(f"Did not expect {p} to exist during testing")
477 p.write_text(
478 dedent(
479 """
480 def say_hello():
481 print("Hello world!")
482 """
483 ),
484 encoding="utf-8",
485 )
486 yield p
487 p.unlink()
488
489
490 @pytest.fixture
491 def temp_script_file_with_py_function():
492 """Fixture to yield a Path to a temporary file in the local directory. File name will end
493 in .py and will include an importable function named "py"
494 """
495 p = Path("my_temp_script_with_py_function.py")
496 if p.exists():
497 raise FileExistsError(f"Did not expect {p} to exist during testing")
498 p.write_text(
499 dedent(
500 """
501 def py():
502 print('A function named "py" has been called')
503 """
504 ),
505 encoding="utf-8",
506 )
507 yield p
508 p.unlink()
509
510
511 def test_obj_name(temp_script_file, temp_script_file_with_py_function):
512 # Module paths (strings including a "/") should raise a meaningful UsageError
513 with pytest.raises(click.exceptions.UsageError) as e:
514 cli.obj_name("mydirectory/myscript.py")
515 assert e.match(
516 "Remember that the ghostwriter should be passed the name of a module, not a path."
517 )
518 # Windows paths (strings including a "\") should also raise a meaningful UsageError
519 with pytest.raises(click.exceptions.UsageError) as e:
520 cli.obj_name(R"mydirectory\myscript.py")
521 assert e.match(
522 "Remember that the ghostwriter should be passed the name of a module, not a path."
523 )
524 # File names of modules (strings ending in ".py") should raise a meaningful UsageError
525 with pytest.raises(click.exceptions.UsageError) as e:
526 cli.obj_name("myscript.py")
527 assert e.match(
528 "Remember that the ghostwriter should be passed the name of a module, not a file."
529 )
530 # File names of modules (strings ending in ".py") that exist should get a suggestion
531 with pytest.raises(click.exceptions.UsageError) as e:
532 cli.obj_name(str(temp_script_file))
533 assert e.match(
534 "Remember that the ghostwriter should be passed the name of a module, not a file."
535 f"\n\tTry: hypothesis write {temp_script_file.stem}"
536 )
537 # File names of modules (strings ending in ".py") that define a py function should succeed
538 assert isinstance(
539 cli.obj_name(str(temp_script_file_with_py_function)), FunctionType
540 )
541
542
543 def test_gets_public_location_not_impl_location():
544 assert ghostwriter._get_module(assume) == "hypothesis" # not "hypothesis.control"
545
546
547 class ForwardRefA:
548 pass
549
550
551 @pytest.mark.parametrize(
552 "parameter, type_name",
553 [
554 (ForwardRef("this_ref_does_not_exist"), None),
555 # ForwardRef.evaluate() logic is new in 3.14
556 *(
557 []
558 if sys.version_info[:2] < (3, 14)
559 else [
560 (
561 ForwardRef("ForwardRefA", owner=A),
562 ghostwriter._AnnotationData(
563 "test_ghostwriter.ForwardRefA", {"test_ghostwriter"}
564 ),
565 )
566 ]
567 ),
568 ],
569 )
570 def test_parameter_to_annotation(parameter, type_name):
571 assert ghostwriter._parameter_to_annotation(parameter) == type_name