Debian Codegraph @

hypothesis-python/tests/cover/test_observability.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 base64
12 import contextlib
13 import json
14 import math
15 import textwrap
16 import threading
17 import warnings
18 from collections import defaultdict
19 from contextlib import nullcontext
20
21 import pytest
22
23 import hypothesis.internal.observability
24 from hypothesis import (
25 assume,
26 event,
27 example,
28 given,
29 note,
30 seed,
31 settings,
32 strategies as st,
33 target,
34 )
35 from hypothesis.database import InMemoryExampleDatabase
36 from hypothesis.internal.compat import PYPY
37 from hypothesis.internal.conjecture.choice import ChoiceNode, choices_key
38 from hypothesis.internal.conjecture.data import Span
39 from hypothesis.internal.coverage import IN_COVERAGE_TESTS
40 from hypothesis.internal.floats import SIGNALING_NAN, float_to_int, int_to_float
41 from hypothesis.internal.intervalsets import IntervalSet
42 from hypothesis.internal.observability import (
43 TESTCASE_CALLBACKS,
44 InfoObservation,
45 TestCaseObservation,
46 add_observability_callback,
47 choices_to_json,
48 nodes_to_json,
49 observability_enabled,
50 remove_observability_callback,
51 with_observability_callback,
52 )
53 from hypothesis.stateful import (
54 RuleBasedStateMachine,
55 invariant,
56 rule,
57 run_state_machine_as_test,
58 )
59 from hypothesis.strategies._internal.utils import to_jsonable
60
61 from tests.common.utils import (
62 Why,
63 capture_observations,
64 checks_deprecated_behaviour,
65 run_concurrently,
66 skipif_threading,
67 xfail_on_crosshair,
68 )
69 from tests.conjecture.common import choices, integer_constr, nodes
70
71
72 @seed("deterministic so we don't miss some combination of features")
73 @example(l=[1], a=0, x=4, data=None)
74 # explicitly set max_examples=100 to override our lower example limit for coverage tests.
75 @settings(database=InMemoryExampleDatabase(), deadline=None, max_examples=100)
76 @given(st.lists(st.integers()), st.integers(), st.integers(), st.data())
77 def do_it_all(l, a, x, data):
78 event(f"{x%2=}")
79 target(x % 5, label="x%5")
80 assume(a % 9)
81 assume(len(l) > 0)
82 if data:
83 data.draw(st.text("abcdef", min_size=a % 3), label="interactive")
84 1 / ((x or 1) % 7)
85
86
87 @xfail_on_crosshair(Why.other, strict=False) # flakey BackendCannotProceed ??
88 @skipif_threading # captures observations from other threads
89 def test_observability():
90 with capture_observations() as ls:
91 with pytest.raises(ZeroDivisionError):
92 do_it_all()
93 with pytest.raises(ZeroDivisionError):
94 do_it_all()
95
96 infos = [t for t in ls if t.type == "info"]
97 assert len(infos) == 2
98 assert {t.title for t in infos} == {"Hypothesis Statistics"}
99
100 testcases = [t for t in ls if t.type == "test_case"]
101 assert len(testcases) > 50
102 assert {t.property for t in testcases} == {do_it_all.__name__}
103 assert len({t.run_start for t in testcases}) == 2
104 assert {t.status for t in testcases} == {"gave_up", "passed", "failed"}
105 for t in testcases:
106 if t.status != "gave_up":
107 assert t.timing
108 assert ("interactive" in t.arguments) == (
109 "generate:interactive" in t.timing
110 )
111
112
113 @xfail_on_crosshair(Why.other)
114 def test_capture_unnamed_arguments():
115 @given(st.integers(), st.floats(), st.data())
116 def f(v1, v2, data):
117 data.draw(st.booleans())
118
119 with capture_observations() as observations:
120 f()
121
122 test_cases = [tc for tc in observations if tc.type == "test_case"]
123 for test_case in test_cases:
124 assert list(test_case.arguments.keys()) == [
125 "v1",
126 "v2",
127 "data",
128 "Draw 1",
129 ], test_case
130
131
132 @pytest.mark.skipif(
133 PYPY or IN_COVERAGE_TESTS, reason="coverage requires sys.settrace pre-3.12"
134 )
135 def test_failure_includes_explain_phase_comments():
136 @given(st.integers(), st.integers())
137 @settings(database=None)
138 def test_fails(x, y):
139 if x:
140 raise AssertionError
141
142 with capture_observations() as observations, pytest.raises(AssertionError):
143 test_fails()
144
145 test_cases = [tc for tc in observations if tc.type == "test_case"]
146 # only the last test case observation, once we've finished shrinking it,
147 # will include explain phase comments.
148 #
149 # Note that the output does *not* include `Explanation:` comments. See
150 # https://github.com/HypothesisWorks/hypothesis/pull/4399#discussion_r2101559648
151 expected = textwrap.dedent(
152 r"""
153 test_fails(
154 x=1,
155 y=0, # or any other generated value
156 )
157 """
158 ).strip()
159 assert test_cases[-1].representation == expected
160
161
162 def test_failure_includes_notes():
163 @given(st.data())
164 @settings(database=None)
165 def test_fails_with_note(data):
166 note("not included 1")
167 data.draw(st.booleans())
168 note("not included 2")
169 raise AssertionError
170
171 with capture_observations() as observations, pytest.raises(AssertionError):
172 test_fails_with_note()
173
174 expected = textwrap.dedent(
175 """
176 test_fails_with_note(
177 data=data(...),
178 )
179 Draw 1: False
180 """
181 ).strip()
182 test_cases = [tc for tc in observations if tc.type == "test_case"]
183 assert test_cases[-1].representation == expected
184
185
186 def test_normal_representation_includes_draws():
187 @given(st.data())
188 def f(data):
189 b1 = data.draw(st.booleans())
190 note("not included")
191 b2 = data.draw(st.booleans(), label="second")
192 assume(b1 and b2)
193
194 with capture_observations() as observations:
195 f()
196
197 crosshair = settings.get_current_profile_name() == "crosshair"
198 expected = textwrap.dedent(
199 f"""
200 f(
201 data={'<symbolic>' if crosshair else 'data(...)'},
202 )
203 Draw 1: True
204 Draw 2 (second): True
205 """
206 ).strip()
207 test_cases = [
208 tc for tc in observations if tc.type == "test_case" and tc.status == "passed"
209 ]
210 assert test_cases
211 # TODO crosshair has a soundness bug with assume. remove branch when fixed
212 # https://github.com/pschanely/hypothesis-crosshair/issues/34
213 if not crosshair:
214 assert {tc.representation for tc in test_cases} == {expected}
215
216
217 @xfail_on_crosshair(Why.other)
218 def test_capture_named_arguments():
219 @given(named1=st.integers(), named2=st.floats(), data=st.data())
220 def f(named1, named2, data):
221 data.draw(st.booleans())
222
223 with capture_observations() as observations:
224 f()
225
226 test_cases = [tc for tc in observations if tc.type == "test_case"]
227 for test_case in test_cases:
228 assert list(test_case.arguments.keys()) == [
229 "named1",
230 "named2",
231 "data",
232 "Draw 1",
233 ], test_case
234
235
236 def test_assume_has_status_reason():
237 @given(st.booleans())
238 def f(b):
239 assume(b)
240
241 with capture_observations() as ls:
242 f()
243
244 gave_ups = [t for t in ls if t.type == "test_case" and t.status == "gave_up"]
245 for gave_up in gave_ups:
246 assert gave_up.status_reason.startswith("failed to satisfy assume() in f")
247
248
249 @pytest.mark.skipif(
250 PYPY or IN_COVERAGE_TESTS, reason="coverage requires sys.settrace pre-3.12"
251 )
252 def test_minimal_failing_observation():
253 @given(st.integers(), st.integers())
254 @settings(database=None)
255 def test_fails(x, y):
256 if x:
257 raise AssertionError
258
259 with capture_observations() as observations, pytest.raises(AssertionError):
260 test_fails()
261
262 observation = [tc for tc in observations if tc.type == "test_case"][-1]
263 expected_representation = textwrap.dedent(
264 r"""
265 test_fails(
266 x=1,
267 y=0, # or any other generated value
268 )
269 """
270 ).strip()
271
272 assert observation.type == "test_case"
273 assert observation.property == "test_fails"
274 assert observation.status == "failed"
275 assert "AssertionError" in observation.status_reason
276 assert set(observation.timing.keys()) == {
277 "execute:test",
278 "overall:gc",
279 "generate:x",
280 "generate:y",
281 }
282 assert observation.coverage is None
283 assert observation.features == {}
284 assert observation.how_generated == "minimal failing example"
285 assert "AssertionError" in observation.metadata.traceback
286 assert "test_fails" in observation.metadata.traceback
287 assert observation.metadata.reproduction_decorator.startswith("@reproduce_failure")
288 assert observation.representation == expected_representation
289 assert observation.arguments == {"x": 1, "y": 0}
290
291
292 @pytest.mark.skipif(
293 PYPY or IN_COVERAGE_TESTS, reason="coverage requires sys.settrace pre-3.12"
294 )
295 def test_all_failing_observations_have_reproduction_decorator():
296 @given(st.integers())
297 def test_fails(x):
298 raise AssertionError
299
300 with capture_observations() as observations, pytest.raises(AssertionError):
301 test_fails()
302
303 # all failed test case observations should have reprodution_decorator
304 for observation in [
305 tc for tc in observations if tc.type == "test_case" and tc.status == "failed"
306 ]:
307 decorator = observation.metadata.reproduction_decorator
308 assert decorator is not None
309 assert decorator.startswith("@reproduce_failure")
310
311
312 @settings(max_examples=20, stateful_step_count=5)
313 class UltraSimpleMachine(RuleBasedStateMachine):
314 value = 0
315
316 @rule()
317 def inc(self):
318 self.value += 1
319
320 @rule()
321 def dec(self):
322 self.value -= 1
323
324 @invariant()
325 def limits(self):
326 assert abs(self.value) <= 100
327
328
329 @xfail_on_crosshair(Why.other, strict=False)
330 def test_observability_captures_stateful_reprs():
331 with capture_observations() as ls:
332 run_state_machine_as_test(UltraSimpleMachine)
333
334 for x in ls:
335 if x.type != "test_case" or x.status == "gave_up":
336 continue
337 r = x.representation
338 assert "state.limits()" in r
339 assert "state.inc()" in r or "state.dec()" in r # or both
340
341 t = x.timing
342 assert "execute:invariant:limits" in t
343 has_inc = "generate:rule:inc" in t and "execute:rule:inc" in t
344 has_dec = "generate:rule:dec" in t and "execute:rule:dec" in t
345 assert has_inc or has_dec
346
347
348 # BytestringProvider.draw_boolean divides [0, 127] as False and [128, 255]
349 # as True
350 @pytest.mark.parametrize(
351 "buffer, expected_status",
352 [
353 # Status.OVERRUN
354 (b"", "gave_up"),
355 # Status.INVALID
356 (b"\x00" + bytes([255]), "gave_up"),
357 # Status.VALID
358 (b"\x00\x00", "passed"),
359 # Status.INTERESTING
360 (bytes([255]) + b"\x00", "failed"),
361 ],
362 )
363 def test_fuzz_one_input_status(buffer, expected_status):
364 @given(st.booleans(), st.booleans())
365 def test_fails(should_fail, should_fail_assume):
366 if should_fail:
367 raise AssertionError
368 if should_fail_assume:
369 assume(False)
370
371 with (
372 capture_observations() as ls,
373 pytest.raises(AssertionError) if expected_status == "failed" else nullcontext(),
374 ):
375 test_fails.hypothesis.fuzz_one_input(buffer)
376 assert len(ls) == 1
377 assert ls[0].status == expected_status
378 assert ls[0].how_generated == "fuzz_one_input"
379
380
381 def _decode_choice(value):
382 if isinstance(value, list):
383 if value[0] == "integer":
384 # large integers get cast to string, stored as ["integer", str(value)]
385 assert isinstance(value[1], str)
386 return int(value[1])
387 elif value[0] == "bytes":
388 assert isinstance(value[1], str)
389 return base64.b64decode(value[1])
390 elif value[0] == "float":
391 assert isinstance(value[1], int)
392 choice = int_to_float(value[1])
393 assert math.isnan(choice)
394 return choice
395 else:
396 return value[1]
397
398 return value
399
400
401 def _decode_choices(data):
402 return [_decode_choice(value) for value in data]
403
404
405 def _decode_nodes(data):
406 return [
407 ChoiceNode(
408 type=node["type"],
409 value=_decode_choice(node["value"]),
410 constraints=_decode_constraints(node["type"], node["constraints"]),
411 was_forced=node["was_forced"],
412 )
413 for node in data
414 ]
415
416
417 def _decode_constraints(choice_type, data):
418 if choice_type == "integer":
419 return {
420 "min_value": _decode_choice(data["min_value"]),
421 "max_value": _decode_choice(data["max_value"]),
422 "weights": (
423 None
424 if data["weights"] is None
425 else {_decode_choice(k): v for k, v in data["weights"]}
426 ),
427 "shrink_towards": _decode_choice(data["shrink_towards"]),
428 }
429 elif choice_type == "float":
430 return {
431 "min_value": _decode_choice(data["min_value"]),
432 "max_value": _decode_choice(data["max_value"]),
433 "allow_nan": data["allow_nan"],
434 "smallest_nonzero_magnitude": data["smallest_nonzero_magnitude"],
435 }
436 elif choice_type == "string":
437 return {
438 "intervals": IntervalSet(tuple(data["intervals"])),
439 "min_size": _decode_choice(data["min_size"]),
440 "max_size": _decode_choice(data["max_size"]),
441 }
442 elif choice_type == "bytes":
443 return {
444 "min_size": _decode_choice(data["min_size"]),
445 "max_size": _decode_choice(data["max_size"]),
446 }
447 elif choice_type == "boolean":
448 return {"p": data["p"]}
449 else:
450 raise ValueError(f"unknown choice type {choice_type}")
451
452
453 def _has_surrogate(choice):
454 return isinstance(choice, str) and any(0xD800 <= ord(c) <= 0xDFFF for c in choice)
455
456
457 @example([0.0])
458 @example([-0.0])
459 @example([SIGNALING_NAN])
460 @example([math.nan])
461 @example([math.inf])
462 @example([-math.inf])
463 # json.{loads, dumps} does not roundtrip for surrogate pairs; they are combined
464 # into the single code point by json.loads:
465 # json.loads(json.dumps("\udbf4\udc00")) == '\U0010d000'
466 #
467 # Ignore this case with an `assume`, and add an explicit example to ensure we
468 # continue to do so.
469 @example(["\udbf4\udc00"])
470 @given(st.lists(choices()))
471 def test_choices_json_roundtrips(choices):
472 assume(not any(_has_surrogate(choice) for choice in choices))
473 choices2 = _decode_choices(json.loads(json.dumps(choices_to_json(choices))))
474 assert choices_key(choices) == choices_key(choices2)
475
476
477 @given(st.lists(nodes()))
478 def test_nodes_json_roundtrips(nodes):
479 assume(
480 not any(
481 _has_surrogate(node.value)
482 or any(_has_surrogate(value) for value in node.constraints.values())
483 for node in nodes
484 )
485 )
486 nodes2 = _decode_nodes(json.loads(json.dumps(nodes_to_json(nodes))))
487 assert nodes == nodes2
488
489
490 @pytest.mark.parametrize(
491 "choice, expected",
492 [
493 (math.nan, ["float", float_to_int(math.nan)]),
494 (SIGNALING_NAN, ["float", float_to_int(SIGNALING_NAN)]),
495 (1, 1),
496 (-1, -1),
497 (2**63 + 1, ["integer", str(2**63 + 1)]),
498 (-(2**63 + 1), ["integer", str(-(2**63 + 1))]),
499 (1.0, 1.0),
500 (-0.0, -0.0),
501 (0.0, 0.0),
502 (True, True),
503 (False, False),
504 (b"a", ["bytes", "YQ=="]),
505 ],
506 )
507 def test_choices_to_json_explicit(choice, expected):
508 assert choices_to_json([choice]) == [expected]
509
510
511 @pytest.mark.parametrize(
512 "choice_node, expected",
513 [
514 (
515 ChoiceNode(
516 type="integer",
517 value=2**63 + 1,
518 constraints=integer_constr(),
519 was_forced=False,
520 ),
521 {
522 "type": "integer",
523 "value": ["integer", str(2**63 + 1)],
524 "constraints": integer_constr(),
525 "was_forced": False,
526 },
527 ),
528 ],
529 )
530 def test_choice_nodes_to_json_explicit(choice_node, expected):
531 assert nodes_to_json([choice_node]) == [expected]
532
533
534 def test_metadata_to_json():
535 # this is mostly a covering test than testing anything particular about
536 # ObservationMetadata.
537 @given(st.integers())
538 def f(n):
539 pass
540
541 with capture_observations(choices=True) as observations:
542 f()
543
544 observations = [obs for obs in observations if obs.type == "test_case"]
545 for observation in observations:
546 assert set(
547 to_jsonable(observation.metadata, avoid_realization=False).keys()
548 ) == {
549 "traceback",
550 "reproduction_decorator",
551 "predicates",
552 "backend",
553 "sys.argv",
554 "os.getpid()",
555 "imported_at",
556 "data_status",
557 "phase",
558 "interesting_origin",
559 "choice_nodes",
560 "choice_spans",
561 }
562 assert observation.metadata.choice_nodes is not None
563
564 for span in observation.metadata.choice_spans:
565 assert isinstance(span, Span)
566 assert 0 <= span.start <= len(observation.metadata.choice_nodes)
567 assert 0 <= span.end <= len(observation.metadata.choice_nodes)
568
569
570 @contextlib.contextmanager
571 def restore_callbacks():
572 callbacks = hypothesis.internal.observability._callbacks.copy()
573 callbacks_all = hypothesis.internal.observability._callbacks_all_threads.copy()
574 try:
575 yield
576 finally:
577 hypothesis.internal.observability._callbacks = callbacks
578 hypothesis.internal.observability._callbacks_all_threads = callbacks_all
579
580
581 @contextlib.contextmanager
582 def with_collect_coverage(*, value: bool):
583 original_value = hypothesis.internal.observability.OBSERVABILITY_COLLECT_COVERAGE
584 hypothesis.internal.observability.OBSERVABILITY_COLLECT_COVERAGE = value
585 try:
586 yield
587 finally:
588 hypothesis.internal.observability.OBSERVABILITY_COLLECT_COVERAGE = (
589 original_value
590 )
591
592
593 def _callbacks():
594 # respect changes from the restore_callbacks context manager by re-accessing
595 # its namespace, instead of keeping
596 # `from hypothesis.internal.observability import _callbacks` around
597 return hypothesis.internal.observability._callbacks
598
599
600 @skipif_threading
601 def test_observability_callbacks():
602 def f(observation):
603 pass
604
605 def g(observation):
606 pass
607
608 thread_id = threading.get_ident()
609
610 with restore_callbacks():
611 assert not observability_enabled()
612
613 add_observability_callback(f)
614 assert _callbacks() == {thread_id: [f]}
615 assert observability_enabled()
616
617 add_observability_callback(g)
618 assert _callbacks() == {thread_id: [f, g]}
619 assert observability_enabled()
620
621 remove_observability_callback(g)
622 assert _callbacks() == {thread_id: [f]}
623 assert observability_enabled()
624
625 remove_observability_callback(g)
626 assert _callbacks() == {thread_id: [f]}
627 assert observability_enabled()
628
629 remove_observability_callback(f)
630 assert _callbacks() == {}
631 assert not observability_enabled()
632
633
634 @skipif_threading
635 def test_observability_callbacks_all_threads():
636 thread_id = threading.get_ident()
637
638 def f(observation, thread_id):
639 pass
640
641 with restore_callbacks():
642 assert not observability_enabled()
643
644 add_observability_callback(f, all_threads=True)
645 assert hypothesis.internal.observability._callbacks_all_threads == [f]
646 assert _callbacks() == {}
647 assert observability_enabled()
648
649 add_observability_callback(f)
650 assert hypothesis.internal.observability._callbacks_all_threads == [f]
651 assert _callbacks() == {thread_id: [f]}
652 assert observability_enabled()
653
654 # remove_observability_callback removes it both from per-thread and
655 # all_threads. The semantics of duplicated callbacks is weird enough
656 # that I don't want to commit to anything here, so I'm leaving this as
657 # somewhat undefined behavior, and recommending that users simply not
658 # register a callback both normally and for all threads.
659 remove_observability_callback(f)
660 assert hypothesis.internal.observability._callbacks_all_threads == []
661 assert _callbacks() == {}
662 assert not observability_enabled()
663
664
665 @checks_deprecated_behaviour
666 def test_testcase_callbacks_deprecation_bool():
667 bool(TESTCASE_CALLBACKS)
668
669
670 @checks_deprecated_behaviour
671 def test_testcase_callbacks_deprecation_append():
672 with restore_callbacks():
673 TESTCASE_CALLBACKS.append(lambda x: None)
674
675
676 @checks_deprecated_behaviour
677 def test_testcase_callbacks_deprecation_remove():
678 with restore_callbacks():
679 TESTCASE_CALLBACKS.remove(lambda x: None)
680
681
682 def test_testcase_callbacks():
683 def f(observation):
684 pass
685
686 def g(observation):
687 pass
688
689 thread_id = threading.get_ident()
690
691 with restore_callbacks(), warnings.catch_warnings():
692 # ignore TESTCASE_CALLBACKS deprecation warnings
693 warnings.simplefilter("ignore")
694
695 assert not bool(TESTCASE_CALLBACKS)
696 add_observability_callback(f)
697 assert _callbacks() == {thread_id: [f]}
698
699 assert bool(TESTCASE_CALLBACKS)
700 add_observability_callback(g)
701 assert _callbacks() == {thread_id: [f, g]}
702
703 assert bool(TESTCASE_CALLBACKS)
704 remove_observability_callback(g)
705 assert _callbacks() == {thread_id: [f]}
706
707 assert bool(TESTCASE_CALLBACKS)
708 remove_observability_callback(f)
709 assert _callbacks() == {}
710
711 assert not bool(TESTCASE_CALLBACKS)
712
713
714 def test_only_receives_callbacks_from_this_thread():
715 @given(st.integers())
716 def g(n):
717 pass
718
719 def test():
720 count_observations = 0
721
722 def callback(observation):
723 nonlocal count_observations
724 count_observations += 1
725
726 add_observability_callback(callback)
727
728 with warnings.catch_warnings():
729 g()
730
731 # one per example, plus one for the overall run
732 assert count_observations == settings().max_examples + 1
733
734 with (
735 restore_callbacks(),
736 # Observability tries to record coverage, but we don't currently
737 # support concurrent coverage collection, and issue a warning instead.
738 #
739 # I tried to fix this with:
740 #
741 # warnings.filterwarnings(
742 # "ignore", message=r".*tool id \d+ is already taken by tool scrutineer.*"
743 # )
744 #
745 # but that had a race condition somehow and sometimes still didn't work?? The
746 # warnings module is not thread-safe until 3.14, I think.
747 with_collect_coverage(value=False),
748 ):
749 run_concurrently(test, n=5)
750
751
752 def test_all_threads_callback():
753 n_threads = 5
754
755 # thread_id: count
756 calls = defaultdict(int)
757
758 def global_callback(observation, thread_id):
759 assert isinstance(observation, (TestCaseObservation, InfoObservation))
760 assert isinstance(thread_id, int)
761
762 calls[thread_id] += 1
763
764 @given(st.integers())
765 def f(n):
766 pass
767
768 with (
769 with_collect_coverage(value=False),
770 with_observability_callback(global_callback, all_threads=True),
771 ):
772 run_concurrently(f, n=n_threads)
773
774 assert len(calls) == n_threads
775 assert all(count == (settings().max_examples + 1) for count in calls.values())