diff options
author | Ran Benita <ran@unusedvar.com> | 2020-09-12 22:28:19 +0300 |
---|---|---|
committer | Ran Benita <ran@unusedvar.com> | 2020-09-12 23:05:08 +0300 |
commit | d18cb961cfc57b9b433e67ece546c22f468a07fa (patch) | |
tree | 4547d747fbd7e53eb42d47ad7e33cb0bcaeb9e9d /src/_pytest/assertion | |
parent | 35350e11cd227ff74fdfdcc856dad10b74fda80b (diff) | |
download | pytest-d18cb961cfc57b9b433e67ece546c22f468a07fa.tar.gz |
assertion/rewrite: fix internal error on collection error due to decorated function
For decorated functions, the lineno of the FunctionDef AST node points
to the `def` line, not to the first decorator line. On the other hand,
in code objects, the `co_firstlineno` points to the first decorator
line.
Assertion rewriting inserts some imports to code it rewrites. The
imports are inserted at the lineno of the first statement in the AST. In
turn, the code object compiled from the rewritten AST uses the lineno of
the first statement (which is the first inserted import).
This means that given a module like this,
```py
@foo
@bar
def baz(): pass
```
the lineno of the code object without assertion rewriting
(`--assertion=plain`) is 1, but with assertion rewriting it is 3.
And *this* causes some issues for the exception repr when e.g. the
decorator line is invalid and raises during collection. The code becomes
confused and crashes with
INTERNALERROR> File "_pytest/_code/code.py", line 638, in get_source
INTERNALERROR> lines.append(space_prefix + source.lines[line_index].strip())
INTERNALERROR> IndexError: list index out of range
Fix it by special casing decorators. Maybe there are other cases like
this but off hand I can't think of another Python construct where the
lineno of the item would be after its first line, and this is the only
such issue we have had reported.
Diffstat (limited to 'src/_pytest/assertion')
-rw-r--r-- | src/_pytest/assertion/rewrite.py | 7 |
1 files changed, 6 insertions, 1 deletions
diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index 3a7c5f6f2..5ff578245 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -695,7 +695,12 @@ class AssertionRewriter(ast.NodeVisitor): else: break pos += 1 - lineno = item.lineno + # Special case: for a decorated function, set the lineno to that of the + # first decorator, not the `def`. Issue #4984. + if isinstance(item, ast.FunctionDef) and item.decorator_list: + lineno = item.decorator_list[0].lineno + else: + lineno = item.lineno imports = [ ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases ] |