[e988c2]: / tests / integration / utils / test_traceback_utils.py

Download this file

61 lines (46 with data), 2.0 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import re
from pathlib import Path
import pytest
import ehrql
from ehrql.loaders import DefinitionError, load_module
from ehrql.tables import smoketest
FIXTURES = Path(__file__).parents[2] / "fixtures" / "bad_definition_files"
def test_traceback_starts_with_user_code():
filename = FIXTURES / "bad_import.py"
message = f'Traceback (most recent call last):\n File "{filename}"'
with pytest.raises(DefinitionError, match=re.escape(message)):
load_module(filename)
def test_traceback_ends_with_user_code():
filename = FIXTURES / "bad_types.py"
with pytest.raises(DefinitionError) as excinfo:
load_module(filename)
# We shouldn't have any references to ehrql code in the traceback
ehrql_root = str(Path(ehrql.__file__).parent)
assert not re.search(re.escape(ehrql_root), str(excinfo.value))
def test_references_to_failed_imports_from_ehrql_are_not_stripped_out():
filename = FIXTURES / "bad_import.py"
with pytest.raises(DefinitionError) as excinfo:
load_module(filename)
# We tried to import a name from `smoketest` which doesn't exist, though the module
# itself does. Therefore this module should be visible in the traceback.
assert re.search(re.escape(smoketest.__file__), str(excinfo.value))
def test_traceback_filtering_handles_relative_paths():
relative_filename = (FIXTURES / "bad_import.py").relative_to(Path.cwd())
message = r'Traceback \(most recent call last\):\n File ".*bad_import\.py"'
with pytest.raises(DefinitionError, match=message):
load_module(relative_filename)
def test_traceback_filtering_handles_syntax_errors():
filename = FIXTURES / "bad_syntax.py"
message = (
r"^"
f"Error loading file '{filename}':"
r"\s+"
f'File "{filename}", line 1'
r"\s+"
r"what even is a Python"
r"[\s\^]+"
r"SyntaxError: invalid syntax"
r"$"
)
with pytest.raises(DefinitionError, match=message):
load_module(filename)