Skip to content

Commit

Permalink
Fix crash with NameError through decorator during collection (#243)
Browse files Browse the repository at this point in the history
This was a quick hack/fix, without knowing what I was doing, could need more tests likely.
  • Loading branch information
blueyed committed Mar 13, 2020
1 parent acbe665 commit a7dfc6f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
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 *",
]
)

0 comments on commit a7dfc6f

Please sign in to comment.