Skip to content

Commit e518108

Browse files
committed
try/catch all of visitor
1 parent 05b5d6c commit e518108

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

hypothesis-python/src/hypothesis/internal/constants_ast.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -98,17 +98,17 @@ def constants_from_module(module: ModuleType) -> AbstractSet[ConstantT]:
9898
try:
9999
source = inspect.getsource(module)
100100
tree = ast.parse(source)
101+
visitor = ConstantVisitor()
102+
visitor.visit(tree)
101103
except Exception:
104+
# A bunch of things can go wrong here.
105+
# * `module` may have a missing or wrong source location
106+
# * ast.parse may fail on the source code
107+
# * NodeVisitor may hit a RecursionError (see many related issues on
108+
# e.g. libcst https://github.com/Instagram/LibCST/issues?q=recursion),
109+
# or a MemoryError (`"[1, " * 200 + "]" * 200`)
102110
return set()
103111

104-
visitor = ConstantVisitor()
105-
try:
106-
visitor.visit(tree)
107-
except RecursionError: # pragma: no cover
108-
# NodeVisitor has a recursive structure, and so deeply nested expressions
109-
# can hit the recursion limit. See the many related issues on e.g. libcst:
110-
# https://github.com/Instagram/LibCST/issues?q=recursion
111-
pass
112112
return visitor.constants
113113

114114

hypothesis-python/tests/cover/test_constants_ast.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
# obtain one at https://mozilla.org/MPL/2.0/.
1010

1111
import ast
12+
import inspect
1213
import subprocess
1314
import sys
1415
import textwrap
@@ -190,3 +191,15 @@ def test_constants_from_bad_module():
190191
)
191192
def test_local_modules_ignores_test_modules(path):
192193
assert not _is_local_module_file(path)
194+
195+
196+
def test_ignores_ast_parse_error(tmp_path):
197+
p = tmp_path / "errors_on_parse.py"
198+
p.write_text("[1, " * 200 + "]" * 200)
199+
module = ModuleType("<test_constants_from_module_large_string>")
200+
module.__file__ = str(p)
201+
202+
with pytest.raises(MemoryError):
203+
ast.parse(inspect.getsource(module))
204+
205+
assert constants_from_module(module) == set()

0 commit comments

Comments
 (0)