Debian Codegraph @

hypothesis-python/tests/cover/test_reflection.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 sys
12 from copy import deepcopy
13 from datetime import time
14 from functools import partial, wraps
15 from inspect import Parameter, Signature, signature
16 from textwrap import dedent
17 from unittest.mock import MagicMock, Mock, NonCallableMagicMock, NonCallableMock
18
19 import pytest
20 from pytest import raises
21
22 from hypothesis import assume, example, given, strategies as st
23 from hypothesis.errors import HypothesisWarning
24 from hypothesis.internal import lambda_sources, reflection
25 from hypothesis.internal.reflection import (
26 convert_keyword_arguments,
27 convert_positional_arguments,
28 define_function_signature,
29 function_digest,
30 get_pretty_function_description,
31 get_signature,
32 is_first_param_referenced_in_function,
33 is_identity_function,
34 is_mock,
35 proxies,
36 repr_call,
37 required_args,
38 source_exec_as_module,
39 )
40 from hypothesis.strategies._internal.lazy import LazyStrategy
41
42
43 def do_conversion_test(f, args, kwargs):
44 result = f(*args, **kwargs)
45
46 cargs, ckwargs = convert_keyword_arguments(f, args, kwargs)
47 assert result == f(*cargs, **ckwargs)
48
49 cargs2, ckwargs2 = convert_positional_arguments(f, args, kwargs)
50 assert result == f(*cargs2, **ckwargs2)
51
52
53 def test_simple_conversion():
54 def foo(a, b, c):
55 return (a, b, c)
56
57 assert convert_keyword_arguments(foo, (1, 2, 3), {}) == ((1, 2, 3), {})
58 assert convert_keyword_arguments(foo, (), {"a": 3, "b": 2, "c": 1}) == (
59 (3, 2, 1),
60 {},
61 )
62
63 do_conversion_test(foo, (1, 0), {"c": 2})
64 do_conversion_test(foo, (1,), {"c": 2, "b": "foo"})
65
66
67 def test_leaves_unknown_kwargs_in_dict():
68 def bar(x, **kwargs):
69 pass
70
71 assert convert_keyword_arguments(bar, (1,), {"foo": "hi"}) == ((1,), {"foo": "hi"})
72 assert convert_keyword_arguments(bar, (), {"x": 1, "foo": "hi"}) == (
73 (1,),
74 {"foo": "hi"},
75 )
76 do_conversion_test(bar, (1,), {})
77 do_conversion_test(bar, (), {"x": 1, "y": 1})
78
79
80 def test_errors_on_bad_kwargs():
81 def bar():
82 pass
83
84 with raises(TypeError):
85 convert_keyword_arguments(bar, (), {"foo": 1})
86
87
88 def test_passes_varargs_correctly():
89 def foo(*args):
90 pass
91
92 assert convert_keyword_arguments(foo, (1, 2, 3), {}) == ((1, 2, 3), {})
93
94 do_conversion_test(foo, (1, 2, 3), {})
95
96
97 def test_errors_if_keyword_precedes_positional():
98 def foo(x, y):
99 pass
100
101 with raises(TypeError):
102 convert_keyword_arguments(foo, (1,), {"x": 2})
103
104
105 def test_errors_if_not_enough_args():
106 def foo(a, b, c, d=1):
107 pass
108
109 with raises(TypeError):
110 convert_keyword_arguments(foo, (1, 2), {"d": 4})
111
112
113 def test_errors_on_extra_kwargs():
114 def foo(a):
115 pass
116
117 with raises(TypeError, match="keyword"):
118 convert_keyword_arguments(foo, (1,), {"b": 1})
119
120 with raises(TypeError, match="keyword"):
121 convert_keyword_arguments(foo, (1,), {"b": 1, "c": 2})
122
123
124 def test_positional_errors_if_too_many_args():
125 def foo(a):
126 pass
127
128 with raises(TypeError, match="too many positional arguments"):
129 convert_positional_arguments(foo, (1, 2), {})
130
131
132 def test_positional_errors_if_too_few_args():
133 def foo(a, b, c):
134 pass
135
136 with raises(TypeError):
137 convert_positional_arguments(foo, (1, 2), {})
138
139
140 def test_positional_does_not_error_if_extra_args_are_kwargs():
141 def foo(a, b, c):
142 pass
143
144 convert_positional_arguments(foo, (1, 2), {"c": 3})
145
146
147 def test_positional_errors_if_given_bad_kwargs():
148 def foo(a):
149 pass
150
151 with raises(TypeError, match="missing a required argument: 'a'"):
152 convert_positional_arguments(foo, (), {"b": 1})
153
154
155 def test_positional_errors_if_given_duplicate_kwargs():
156 def foo(a):
157 pass
158
159 with raises(TypeError, match="multiple values"):
160 convert_positional_arguments(foo, (2,), {"a": 1})
161
162
163 def test_names_of_functions_are_pretty():
164 assert (
165 get_pretty_function_description(test_names_of_functions_are_pretty)
166 == "test_names_of_functions_are_pretty"
167 )
168
169
170 class Foo:
171 @classmethod
172 def bar(cls):
173 pass
174
175 def baz(cls):
176 pass
177
178 def __repr__(self):
179 return "SoNotFoo()"
180
181
182 def test_class_names_are_not_included_in_class_method_prettiness():
183 assert get_pretty_function_description(Foo.bar) == "bar"
184
185
186 def test_repr_is_included_in_bound_method_prettiness():
187 assert get_pretty_function_description(Foo().baz) == "SoNotFoo().baz"
188
189
190 def test_class_is_not_included_in_unbound_method():
191 assert get_pretty_function_description(Foo.baz) == "baz"
192
193
194 def test_does_not_error_on_confused_sources():
195 def ed(f, *args):
196 return f
197
198 x = ed(
199 lambda x, y: (x * y).conjugate() == x.conjugate() * y.conjugate(),
200 complex,
201 complex,
202 )
203
204 get_pretty_function_description(x)
205
206
207 def test_digests_are_reasonably_unique():
208 assert function_digest(test_simple_conversion) != function_digest(
209 test_does_not_error_on_confused_sources
210 )
211
212
213 def test_digest_returns_the_same_value_for_two_calls():
214 assert function_digest(test_simple_conversion) == function_digest(
215 test_simple_conversion
216 )
217
218
219 def test_can_digest_a_built_in_function():
220 import math
221
222 assert function_digest(math.isnan) != function_digest(range)
223
224
225 def test_can_digest_a_unicode_lambda():
226 function_digest(lambda x: "☃" in str(x))
227
228
229 def test_can_digest_a_function_with_no_name():
230 def foo(x, y):
231 pass
232
233 function_digest(partial(foo, 1))
234
235
236 def test_arg_string_is_in_order():
237 def foo(c, a, b, f, a1):
238 pass
239
240 assert repr_call(foo, (1, 2, 3, 4, 5), {}) == "foo(c=1, a=2, b=3, f=4, a1=5)"
241 assert (
242 repr_call(foo, (1, 2), {"b": 3, "f": 4, "a1": 5})
243 == "foo(c=1, a=2, b=3, f=4, a1=5)"
244 )
245
246
247 def test_varkwargs_are_sorted_and_after_real_kwargs():
248 def foo(d, e, f, **kwargs):
249 pass
250
251 assert (
252 repr_call(foo, (), {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6})
253 == "foo(d=4, e=5, f=6, a=1, b=2, c=3)"
254 )
255
256
257 def test_varargs_come_without_equals():
258 def foo(a, *args):
259 pass
260
261 assert repr_call(foo, (1, 2, 3, 4), {}) == "foo(2, 3, 4, a=1)"
262
263
264 def test_can_mix_varargs_and_varkwargs():
265 def foo(*args, **kwargs):
266 pass
267
268 assert repr_call(foo, (1, 2, 3), {"c": 7}) == "foo(1, 2, 3, c=7)"
269
270
271 def test_arg_string_does_not_include_unprovided_defaults():
272 def foo(a, b, c=9, d=10):
273 pass
274
275 assert repr_call(foo, (1,), {"b": 1, "d": 11}) == "foo(a=1, b=1, d=11)"
276
277
278 def universal_acceptor(*args, **kwargs):
279 return args, kwargs
280
281
282 def has_one_arg(hello):
283 pass
284
285
286 def has_two_args(hello, world):
287 pass
288
289
290 def has_a_default(x, y, z=1):
291 pass
292
293
294 def has_varargs(*args):
295 pass
296
297
298 def has_kwargs(**kwargs):
299 pass
300
301
302 @pytest.mark.parametrize("f", [has_one_arg, has_two_args, has_varargs, has_kwargs])
303 def test_copying_preserves_signature(f):
304 af = get_signature(f)
305 t = define_function_signature("foo", "docstring", af)(universal_acceptor)
306 at = get_signature(t)
307 assert af == at
308
309
310 def test_name_does_not_clash_with_function_names():
311 def f():
312 pass
313
314 @define_function_signature("f", "A docstring for f", signature(f))
315 def g():
316 pass
317
318 g()
319
320
321 def test_copying_sets_name():
322 f = define_function_signature(
323 "hello_world", "A docstring for hello_world", signature(has_two_args)
324 )(universal_acceptor)
325 assert f.__name__ == "hello_world"
326
327
328 def test_copying_sets_docstring():
329 f = define_function_signature(
330 "foo", "A docstring for foo", signature(has_two_args)
331 )(universal_acceptor)
332 assert f.__doc__ == "A docstring for foo"
333
334
335 def test_uses_defaults():
336 f = define_function_signature(
337 "foo", "A docstring for foo", signature(has_a_default)
338 )(universal_acceptor)
339 assert f(3, 2) == ((3, 2, 1), {})
340
341
342 def test_uses_varargs():
343 f = define_function_signature("foo", "A docstring for foo", signature(has_varargs))(
344 universal_acceptor
345 )
346 assert f(1, 2) == ((1, 2), {})
347
348
349 DEFINE_FOO_FUNCTION = """
350 def foo(x):
351 return x
352 """
353
354
355 def test_exec_as_module_execs():
356 m = source_exec_as_module(DEFINE_FOO_FUNCTION)
357 assert m.foo(1) == 1
358
359
360 def test_exec_as_module_caches():
361 assert source_exec_as_module(DEFINE_FOO_FUNCTION) is source_exec_as_module(
362 DEFINE_FOO_FUNCTION
363 )
364
365
366 def test_exec_leaves_sys_path_unchanged():
367 old_path = deepcopy(sys.path)
368 source_exec_as_module("hello_world = 42")
369 assert sys.path == old_path
370
371
372 def test_define_function_signature_works_with_conflicts():
373 def accepts_everything(*args, **kwargs):
374 pass
375
376 define_function_signature(
377 "hello",
378 "A docstring for hello",
379 Signature(parameters=[Parameter("f", Parameter.POSITIONAL_OR_KEYWORD)]),
380 )(accepts_everything)(1)
381
382 define_function_signature(
383 "hello",
384 "A docstring for hello",
385 Signature(parameters=[Parameter("f", Parameter.VAR_POSITIONAL)]),
386 )(accepts_everything)(1)
387
388 define_function_signature(
389 "hello",
390 "A docstring for hello",
391 Signature(parameters=[Parameter("f", Parameter.VAR_KEYWORD)]),
392 )(accepts_everything)()
393
394 define_function_signature(
395 "hello",
396 "A docstring for hello",
397 Signature(
398 parameters=[
399 Parameter("f", Parameter.POSITIONAL_OR_KEYWORD),
400 Parameter("f_3", Parameter.POSITIONAL_OR_KEYWORD),
401 Parameter("f_1", Parameter.VAR_POSITIONAL),
402 Parameter("f_2", Parameter.VAR_KEYWORD),
403 ]
404 ),
405 )(accepts_everything)(1, 2)
406
407
408 def test_define_function_signature_validates_function_name():
409 define_function_signature("hello_world", None, Signature())
410 with raises(ValueError):
411 define_function_signature("hello world", None, Signature())
412
413
414 class Container:
415 def funcy(self):
416 pass
417
418
419 def test_can_proxy_functions_with_mixed_args_and_varargs():
420 def foo(a, *args):
421 return (a, args)
422
423 @proxies(foo)
424 def bar(*args, **kwargs):
425 return foo(*args, **kwargs)
426
427 assert bar(1, 2) == (1, (2,))
428
429
430 def test_can_delegate_to_a_function_with_no_positional_args():
431 def foo(a, b):
432 return (a, b)
433
434 @proxies(foo)
435 def bar(**kwargs):
436 return foo(**kwargs)
437
438 assert bar(2, 1) == (2, 1)
439
440
441 @pytest.mark.parametrize(
442 "func,args,expected",
443 [
444 (lambda: None, (), None),
445 (lambda a: a**2, (2,), 4),
446 (lambda *a: a, [1, 2, 3], (1, 2, 3)),
447 ],
448 )
449 def test_can_proxy_lambdas(func, args, expected):
450 @proxies(func)
451 def wrapped(*args, **kwargs):
452 return func(*args, **kwargs)
453
454 assert wrapped.__name__ == "<lambda>"
455 assert wrapped(*args) == expected
456
457
458 class Snowman:
459 def __repr__(self):
460 return "☃"
461
462
463 class BittySnowman:
464 def __repr__(self):
465 return "☃"
466
467
468 def test_can_handle_unicode_repr():
469 def foo(x):
470 pass
471
472 assert repr_call(foo, [Snowman()], {}) == "foo(x=☃)"
473 assert repr_call(foo, [], {"x": Snowman()}) == "foo(x=☃)"
474
475
476 class NoRepr:
477 pass
478
479
480 def test_can_handle_repr_on_type():
481 def foo(x):
482 pass
483
484 assert repr_call(foo, [Snowman], {}) == "foo(x=Snowman)"
485 assert repr_call(foo, [NoRepr], {}) == "foo(x=NoRepr)"
486
487
488 def test_can_handle_repr_of_none():
489 def foo(x):
490 pass
491
492 assert repr_call(foo, [None], {}) == "foo(x=None)"
493 assert repr_call(foo, [], {"x": None}) == "foo(x=None)"
494
495
496 def test_kwargs_appear_in_arg_string():
497 def varargs(*args, **kwargs):
498 pass
499
500 assert "x=1" in repr_call(varargs, (), {"x": 1})
501
502
503 def test_is_mock_with_negative_cases():
504 assert not is_mock(None)
505 assert not is_mock(1234)
506 assert not is_mock(is_mock)
507 assert not is_mock(BittySnowman())
508 assert not is_mock("foobar")
509 assert not is_mock(Mock(spec=BittySnowman))
510 assert not is_mock(MagicMock(spec=BittySnowman))
511
512
513 def test_is_mock_with_positive_cases():
514 assert is_mock(Mock())
515 assert is_mock(MagicMock())
516 assert is_mock(NonCallableMock())
517 assert is_mock(NonCallableMagicMock())
518
519
520 class Target:
521 def __init__(self, a, b):
522 pass
523
524 def method(self, a, b):
525 pass
526
527
528 @pytest.mark.parametrize("target", [Target, Target(1, 2).method])
529 @pytest.mark.parametrize(
530 "args,kwargs,expected",
531 [
532 ((), {}, set("ab")),
533 ((1,), {}, set("b")),
534 ((1, 2), {}, set()),
535 ((), {"a": 1}, set("b")),
536 ((), {"b": 2}, set("a")),
537 ((), {"a": 1, "b": 2}, set()),
538 ],
539 )
540 def test_required_args(target, args, kwargs, expected):
541 # Mostly checking that `self` (and only self) is correctly excluded
542 assert required_args(target, args, kwargs) == expected
543
544
545 def test_can_handle_unicode_identifier_in_same_line_as_lambda_def():
546 # fmt: off
547 pi = "π"; is_str_pi = lambda x: x == pi # noqa: E702
548 # fmt: on
549 assert get_pretty_function_description(is_str_pi) == "lambda x: x == pi"
550
551
552 def test_too_many_posargs_fails():
553 with pytest.raises(TypeError):
554 st.times(time.min, time.max, st.none(), st.none()).validate()
555
556
557 def test_overlapping_posarg_kwarg_fails():
558 with pytest.raises(TypeError):
559 st.times(time.min, time.max, st.none(), timezones=st.just(None)).validate()
560
561
562 def test_inline_given_handles_self():
563 # Regression test for https://github.com/HypothesisWorks/hypothesis/issues/961
564 class Cls:
565 def method(self, **kwargs):
566 assert isinstance(self, Cls)
567 assert kwargs["k"] is sentinel
568
569 sentinel = object()
570 given(k=st.just(sentinel))(Cls().method)()
571
572
573 def logged(f):
574 @wraps(f)
575 def wrapper(*a, **kw):
576 return f(*a, **kw)
577
578 return wrapper
579
580
581 class Bar:
582 @logged
583 def __init__(self, i: int):
584 pass
585
586
587 @given(st.builds(Bar))
588 def test_issue_2495_regression(_):
589 """See https://github.com/HypothesisWorks/hypothesis/issues/2495"""
590
591
592 @pytest.mark.skipif(
593 sys.version_info[:2] >= (3, 11),
594 reason="handled upstream in https://github.com/python/cpython/pull/92065",
595 )
596 def test_error_on_keyword_parameter_name():
597 def f(source):
598 pass
599
600 f.__signature__ = Signature(
601 parameters=[Parameter("from", Parameter.KEYWORD_ONLY)],
602 return_annotation=Parameter.empty,
603 )
604
605 with pytest.raises(ValueError, match="SyntaxError because `from` is a keyword"):
606 get_signature(f)
607
608
609 def test_param_is_called_within_func():
610 def f(any_name):
611 any_name()
612
613 assert is_first_param_referenced_in_function(f)
614
615
616 def test_param_is_called_within_subfunc():
617 def f(any_name):
618 def f2():
619 any_name()
620
621 assert is_first_param_referenced_in_function(f)
622
623
624 def test_param_is_not_called_within_func():
625 def f(any_name):
626 pass
627
628 assert not is_first_param_referenced_in_function(f)
629
630
631 def test_param_called_within_defaults_on_error():
632 # Create a function object for which we cannot retrieve the source.
633 f = compile("lambda: ...", "_.py", "eval")
634 assert is_first_param_referenced_in_function(f)
635
636
637 def _prep_source(*pairs):
638 return [
639 pytest.param(
640 dedent(x).strip(), dedent(y).strip().encode(), id=f"case-{i}", marks=marks
641 )
642 for i, (x, y, *marks) in enumerate(pairs)
643 ]
644
645
646 @pytest.mark.parametrize(
647 "src, clean",
648 _prep_source(
649 ("", ""),
650 ("def test(): pass", "def test(): pass"),
651 ("def invalid syntax", "def invalid syntax"),
652 ("def also invalid(", "def also invalid("),
653 (
654 """
655 @example(1)
656 @given(st.integers())
657 def test(x):
658 # line comment
659 assert x # end-of-line comment
660
661
662 "Had some blank lines above"
663 """,
664 """
665 def test(x):
666 assert x
667 "Had some blank lines above"
668 """,
669 ),
670 (
671 """
672 @dec
673 async def f():
674 pass
675 """,
676 """
677 async def f():
678 pass
679 """,
680 ),
681 ),
682 )
683 def test_clean_source(src, clean):
684 assert reflection._clean_source(src).splitlines() == clean.splitlines()
685
686
687 def test_overlong_repr_warns():
688 with pytest.warns(HypothesisWarning, match="overly large"):
689 repr(LazyStrategy(st.one_of, [st.none()] * 10000, {}))
690
691
692 def identity(x):
693 return x
694
695
696 class Identity:
697 def __call__(self, x):
698 return x
699
700 def instance_identity(self, x):
701 return x
702
703 def instance_self(self):
704 return self
705
706 @staticmethod
707 def static_identity(x):
708 return x
709
710 @classmethod
711 def class_identity(cls, x):
712 return x
713
714
715 @pytest.mark.parametrize(
716 "f",
717 [
718 lambda x: x,
719 identity,
720 Identity(),
721 Identity().instance_identity,
722 Identity.static_identity,
723 Identity.class_identity,
724 ],
725 )
726 def test_is_identity(f):
727 assert is_identity_function(f)
728
729
730 @example(Identity().instance_self)
731 @example(lambda x, y: x)
732 @example(lambda: None)
733 @given(st.functions(like=identity, returns=st.from_type(type).flatmap(st.from_type)))
734 def test_is_not_identity(f):
735 obj = object()
736 try:
737 assume(f(obj) is not obj) # not necessary but ...
738 except TypeError:
739 pass
740 assert not is_identity_function(f)
741
742
743 @pytest.mark.parametrize(
744 "f",
745 [
746 lambda x, y=None: x, # this one would be fairly easy to recognize
747 lambda x, y=None: y or x, # ... but the general case is impossible
748 ],
749 )
750 def test_is_unrecognized_identity(f):
751 assert not is_identity_function(f)
752
753
754 def test_cache_key_size_is_bounded():
755 # Modify co_consts because ("c" * 1000) may not be evaluated at compile time
756 f = lambda x="a" * 1000, *, y="b" * 1000: "c"
757 f.__code__ = f.__code__.replace(
758 co_consts=tuple(c * 1000 if c == "c" else c for c in f.__code__.co_consts)
759 )
760 assert len(repr(lambda_sources._function_key(f))) > 3000
761 assert len(repr(lambda_sources._function_key(f, bounded_size=True))) < 1000
762
763
764 def test_function_key_distinguishes_alpha_renames():
765 # these terms are equivalent under the lambda calculus, but their
766 # representations are not, so they should be cached differently.
767 assert lambda_sources._function_key(lambda x: x) != lambda_sources._function_key(
768 lambda y: y
769 )
770
771
772 def test_import():
773 import time as t
774
775 f = lambda: t.ctime()
776 assert get_pretty_function_description(f) == "lambda: t.ctime()"
777
778
779 @pytest.mark.parametrize("nop_on_f", [True, False])
780 def test_code_normalization(nop_on_f):
781 f = lambda x: x
782 g = lambda x: x
783 h = f if nop_on_f else g
784 assert lambda_sources._function_key(f) == lambda_sources._function_key(g)
785
786 # Append a NOP to one of the bytecodes
787 NOP_instr = bytes([lambda_sources._op.NOP, 0])
788 h.__code__ = h.__code__.replace(co_code=h.__code__.co_code + NOP_instr)
789 assert lambda_sources._function_key(f) != lambda_sources._function_key(g)
790
791 # ...and then normalize g to match f (adding or removing a NOP)
792 g.__code__ = lambda_sources._normalize_code(f, g)
793 assert lambda_sources._function_key(f) == lambda_sources._function_key(g)
794
795
796 @pytest.mark.parametrize(
797 "f, source",
798 [
799 (lambda x=1, *, y=2: (x, y), "lambda x=1, *, y=2: (x, y)"),
800 (lambda x=1, *, y: (x, y), "lambda x=1, *, y: (x, y)"),
801 (lambda x, *, y=2: (x, y), "lambda x, *, y=2: (x, y)"),
802 (lambda x, *, y: (x, y), "lambda x, *, y: (x, y)"),
803 (lambda *, y=2: (x, y), "lambda *, y=2: (x, y)"), # noqa: F821
804 (lambda *, y: (x, y), "lambda *, y: (x, y)"), # noqa: F821
805 (lambda x, /, y=1: (x, y), "lambda x, /, y=1: (x, y)"),
806 (lambda x, /, y: (x, y), "lambda x, /, y: (x, y)"),
807 (lambda x, /: (x, y), "lambda x, /: (x, y)"), # noqa: F821
808 (lambda x=1, /, y=2: (x, y), "lambda x=1, /, y=2: (x, y)"),
809 (lambda x=1, /: (x, y), "lambda x=1, /: (x, y)"), # noqa: F821
810 ],
811 )
812 def test_lambda_mimicry_with_arg_defaults(f, source):
813 assert get_pretty_function_description(f) == source