Debian Codegraph @

hypothesis-python/tests/cover/test_constants_ast.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 inspect
13 import subprocess
14 import sys
15 import textwrap
16 from types import ModuleType
17
18 import pytest
19
20 from hypothesis import example, given, note, settings, strategies as st
21 from hypothesis.internal.compat import PYPY
22 from hypothesis.internal.constants_ast import (
23 Constants,
24 ConstantVisitor,
25 TooManyConstants,
26 _constants_file_str,
27 _constants_from_source,
28 constants_from_module,
29 is_local_module_file,
30 )
31
32 from tests.common.utils import skipif_emscripten, skipif_threading
33
34 constant_ints = st.integers(max_value=-101) | st.integers(min_value=101)
35 constant_floats = st.floats(allow_nan=False, allow_infinity=False)
36 constant_bytes = st.binary(min_size=1, max_size=50)
37 constant_strings = st.text(min_size=1, max_size=10).filter(lambda s: not s.isspace())
38 constants = constant_ints | constant_floats | constant_bytes | constant_strings
39
40 constants_classes = st.builds(
41 Constants,
42 integers=st.sets(constant_ints),
43 floats=st.sets(constant_floats),
44 bytes=st.sets(constant_bytes),
45 strings=st.sets(constant_strings),
46 )
47
48
49 def constants_from_ast(tree):
50 visitor = ConstantVisitor(limit=True)
51 visitor.visit(tree)
52 return visitor.constants
53
54
55 def test_constants_set_from_type_invalid():
56 with pytest.raises(ValueError):
57 Constants().set_for_type("not_a_type")
58
59
60 @given(st.integers())
61 def test_constants_contains(n):
62 assert n in Constants(integers={n})
63
64
65 @given(constants_classes)
66 def test_constants_not_equal_to_set(constants):
67 assert constants != set()
68 assert constants != set(constants)
69
70
71 @pytest.mark.parametrize(
72 "source, expected",
73 [
74 (
75 """
76 a1 = 142
77 a2 = 3.14
78 a3 = 'test1'
79 a4 = b'test2'
80 a5 = (101, 102)
81 a6 = frozenset([103])
82 """,
83 {142, 3.14, 101, 102, 103, "test1", b"test2"},
84 ),
85 (
86 "a = (101, (102, 103), frozenset([104, 105]))",
87 {101, 102, 103, 104, 105},
88 ),
89 ("a = {'b': 101}", {"b", 101}),
90 ("a = [101]", {101}),
91 ("a = +142", {142}),
92 ("a = 101 + 102", {101, 102}),
93 ("a = ~ 142", {142}),
94 # the following cases are ignored:
95 # * booleans
96 # * math.inf and math.nan (not constants, but we don't want to collect them
97 # even if they were)
98 # * f-strings
99 # * long strings
100 # * pure-whitespace strings
101 # * standalone string expressions (strings not assigned to a variable).
102 # This covers docstrings of all kinds.
103 # * small integers
104 # * the empty bytestring b""
105 ("a = True", set()),
106 ("a = False", set()),
107 ("a = not False", set()),
108 ("a = 1e999", set()),
109 ("a = math.inf", set()),
110 ("a = math.nan", set()),
111 ('a = f"test {x}"', set()),
112 (f'a = "{"b" * 100}"', set()),
113 ('a = ""', set()),
114 ('a = " "', set()),
115 ('a = "\\n \\n \\n"', set()),
116 ("'test'", set()),
117 ("'test with \\n newlines'", set()),
118 ("a = 10", set()),
119 ("a = -1", set()),
120 ("a = b''", set()),
121 ],
122 )
123 def test_constants_from_ast(source, expected):
124 source = textwrap.dedent(source)
125 tree = ast.parse(source)
126 assert set(constants_from_ast(tree)) == expected
127
128
129 @given(st.integers(max_value=-101))
130 def test_parses_negatives(n):
131 assert constants_from_ast(ast.parse(f"a = {n}")) == Constants(integers={n})
132
133
134 @given(st.tuples(constants))
135 def test_tuple_constants(value):
136 tree = ast.parse(str(value))
137 assert set(constants_from_ast(tree)) == set(value)
138
139
140 @given(st.frozensets(constants))
141 def test_frozenset_constants(value):
142 tree = ast.parse(str(value))
143 assert set(constants_from_ast(tree)) == set(value)
144
145
146 @skipif_threading
147 @skipif_emscripten
148 @pytest.mark.xfail(
149 condition=settings.get_current_profile_name() != "ci",
150 strict=False,
151 reason="Requires clean environment",
152 )
153 def test_constants_from_running_file(tmp_path):
154 p = tmp_path / "my_constants.py"
155 p.write_text(
156 textwrap.dedent(
157 """
158 import sys
159 # stdlib
160 import json
161 # third-party
162 import pytest
163 import hypothesis
164 from hypothesis.internal.constants_ast import (
165 is_local_module_file,
166 constants_from_module,
167 Constants
168 )
169
170 # these modules are in fact detected as local if they are installed
171 # as editable (as is common for contributors). Prevent the ast constant
172 # logic from picking up on them
173 for module in sys.modules.copy():
174 if module.startswith("hypofuzz"):
175 del sys.modules[module]
176
177 constants = Constants()
178 for module in sys.modules.values():
179 if getattr(module, "__file__", None) is not None and is_local_module_file(
180 module.__file__
181 ):
182 constants |= constants_from_module(module)
183
184 expected = Constants(
185 strings={'float', 'string', 'bytes', 'integer', 'test', 'hypofuzz', '__file__'},
186 floats={3.14},
187 bytes={b'test'},
188 integers={142, 101, 102, 103, 104},
189 )
190 assert constants == expected, set(constants).symmetric_difference(set(expected))
191
192 # local
193 a = 142
194 b = "test"
195 c = True
196 d = 3.14
197 e = b"test"
198 f = (101, 102)
199 g = frozenset([103, 104])
200 """,
201 ),
202 encoding="utf-8",
203 )
204 # this test doubles as a regression test for
205 # https://github.com/HypothesisWorks/hypothesis/issues/4375. Fail on comparisons
206 # between bytes and str.
207 subprocess.check_call([sys.executable, "-bb", str(p)])
208
209
210 def test_constants_from_bad_module():
211 # covering test for the except branch
212 module = ModuleType("nonexistent")
213 assert constants_from_module(module) == Constants()
214
215
216 @pytest.mark.parametrize(
217 "path",
218 [
219 "/path/to/tests/module",
220 "/path/to/test/module",
221 "/a/test_file.py",
222 "/a/file_test.py",
223 ],
224 )
225 def test_local_modules_ignores_test_modules(path):
226 assert not is_local_module_file(path)
227
228
229 @skipif_threading
230 @pytest.mark.skipif(PYPY, reason="no memory error on pypy")
231 def test_ignores_ast_parse_error(tmp_path):
232 p = tmp_path / "errors_on_parse.py"
233 p.write_text("[1, " * 200 + "]" * 200, encoding="utf-8")
234 module = ModuleType("<test_ignores_ast_parse_error>")
235 module.__file__ = str(p)
236
237 source = inspect.getsource(module)
238 with pytest.raises(MemoryError):
239 ast.parse(source)
240
241 assert constants_from_module(module) == Constants()
242
243
244 @example(
245 constants=Constants(
246 integers={-101, 101},
247 floats={101.0},
248 bytes=set(),
249 strings=set(),
250 ),
251 )
252 @example(
253 constants=Constants(
254 integers={-101, 100},
255 floats={-101.0, 101.0},
256 bytes={b"-101.0", b"101.0"},
257 strings={"-101.0", "101.0"},
258 ),
259 )
260 @given(constants_classes)
261 def test_constant_visitor_roundtrips_string(constants):
262 # our files in storage_directory("constants") rely on this roundtrip
263 visitor = ConstantVisitor(limit=True)
264
265 s = _constants_file_str(constants)
266 visitor.visit(ast.parse(s))
267
268 note(f"{constants=}")
269 note(f"{visitor.constants=}")
270 assert visitor.constants == constants
271
272
273 def test_too_many_constants():
274 visitor = ConstantVisitor(limit=True)
275 # start at n=1000 to avoid ConstantVisitor ignoring small integers
276 s = "; ".join(
277 f"n = {i}" for i in range(1000, 1000 + ConstantVisitor.CONSTANTS_LIMIT + 1)
278 )
279 # visitor should raise on too many constants
280 with pytest.raises(TooManyConstants):
281 visitor.visit(ast.parse(s))
282
283 # and also _constants_from_source should return empty on too many constants
284 assert _constants_from_source(s, limit=True) == Constants()
285
286 # but it parses fine with limit=False
287 visitor = ConstantVisitor(limit=False)
288 visitor.visit(ast.parse(s))
289 assert _constants_from_source(s, limit=False) == Constants(
290 integers=set(range(1000, 1000 + ConstantVisitor.CONSTANTS_LIMIT + 1))
291 )
292
293
294 @skipif_threading # concurrent writes to the same file
295 def test_module_too_large(tmp_path):
296 constant = 11231783
297
298 p = tmp_path / "large_file.py"
299 content = f"a = {constant}\n\n" + "#" * (512 * 1024 + 1)
300 p.write_text(content, encoding="utf-8")
301
302 module = ModuleType("large_module")
303 module.__file__ = str(p)
304 assert constants_from_module(module) == Constants()
305 assert constants_from_module(module, limit=False) == Constants(integers={constant})