Debian Codegraph @

scripts/fuzz.py

raw
1 """Property-based tests for Black.
2
3 By Zac Hatfield-Dodds, based on my Hypothesmith tool for source code
4 generation. You can run this file with `python`, `pytest`, or (soon)
5 a coverage-guided fuzzer I'm working on.
6 """
7
8 import hypothesmith
9 from hypothesis import HealthCheck, given, settings
10 from hypothesis import strategies as st
11
12 import black
13
14
15 # This test uses the Hypothesis and Hypothesmith libraries to generate random
16 # syntactically-valid Python source code and run Black in odd modes.
17 @settings(
18 max_examples=1000, # roughly 1k tests/minute, or half that under coverage
19 derandomize=True, # deterministic mode to avoid CI flakiness
20 deadline=None, # ignore Hypothesis' health checks; we already know that
21 suppress_health_check=list(HealthCheck), # this is slow and filter-heavy.
22 )
23 @given(
24 # Note that while Hypothesmith might generate code unlike that written by
25 # humans, it's a general test that should pass for any *valid* source code.
26 # (so e.g. running it against code scraped of the internet might also help)
27 src_contents=hypothesmith.from_grammar() | hypothesmith.from_node(),
28 # Using randomly-varied modes helps us to exercise less common code paths.
29 mode=st.builds(
30 black.FileMode,
31 line_length=st.just(88) | st.integers(0, 200),
32 string_normalization=st.booleans(),
33 preview=st.booleans(),
34 is_pyi=st.booleans(),
35 magic_trailing_comma=st.booleans(),
36 ),
37 )
38 def test_idempotent_any_syntactically_valid_python(
39 src_contents: str, mode: black.FileMode
40 ) -> None:
41 # Before starting, let's confirm that the input string is valid Python:
42 compile(src_contents, "<string>", "exec") # else the bug is in hypothesmith
43
44 # Then format the code...
45 dst_contents = black.format_str(src_contents, mode=mode)
46
47 # And check that we got equivalent and stable output.
48 black.assert_equivalent(src_contents, dst_contents)
49 black.assert_stable(src_contents, dst_contents, mode=mode)
50
51 # Future test: check that pure-python and mypyc versions of black
52 # give identical output for identical input?
53
54
55 if __name__ == "__main__":
56 # Run tests, including shrinking and reporting any known failures.
57 test_idempotent_any_syntactically_valid_python()
58
59 # If Atheris is available, run coverage-guided fuzzing.
60 # (if you want only bounded fuzzing, just use `pytest fuzz.py`)
61 try:
62 import sys
63
64 import atheris
65 except ImportError:
66 pass
67 else:
68 test = test_idempotent_any_syntactically_valid_python
69 atheris.Setup(
70 sys.argv,
71 test.hypothesis.fuzz_one_input, # type: ignore[attr-defined]
72 )
73 atheris.Fuzz()