Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash with NameError through decorator during collection #243

Merged
merged 2 commits into from
Mar 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,12 +244,14 @@ def getsource(self, astcache=None) -> Optional["Source"]:
astnode = astcache.get(key, None)
start = self.getfirstlinesource()
try:
astnode, _, end = getstatementrange_ast(
astnode, ast_start, end = getstatementrange_ast(
self.lineno, source, astnode=astnode
)
except SyntaxError:
end = self.lineno + 1
else:
if ast_start - 1 < start:
start = ast_start
if key is not None:
astcache[key] = astnode
return source[start:end]
Expand Down
2 changes: 2 additions & 0 deletions src/_pytest/_code/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,8 @@ def get_statement_startend2(lineno: int, node: ast.AST) -> Tuple[int, Optional[i
# AST's line numbers start indexing at 1
values = [] # type: List[int]
for x in ast.walk(node):
if isinstance(x, (ast.FunctionDef)):
values.extend(deco.lineno - 1 for deco in x.decorator_list)
if isinstance(x, (ast.stmt, ast.ExceptHandler)):
values.append(x.lineno - 1)
for name in ("finalbody", "orelse"):
Expand Down
20 changes: 20 additions & 0 deletions testing/code/test_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,23 @@ def test_not_raise_exception_with_mixed_encoding(self, tw_mock) -> None:
tw_mock.lines[0]
== r"unicode_string = São Paulo, utf8_string = b'S\xc3\xa3o Paulo'"
)


def test_nameerror_with_decorator(testdir):
# TODO: unittest with Code (additionally)?!
source = """
@nameerror_deco1
def test():
pass
"""
p1 = testdir.makepyfile(source)
result = testdir.runpytest(str(p1), "-rf")
result.stdout.fnmatch_lines(
[
"*_ ERROR collecting test_nameerror_with_decorator.py _*",
"test_nameerror_with_decorator.py:1: in <module>",
" @nameerror_deco1",
"E NameError: name 'nameerror_deco1' is not defined",
"*= 1 error in *",
]
)