Skip to content

Commit 3e81cb2

Browse files
committed
runner: fix tracebacks for failed collectors getting longer and longer
Refs pytest-dev#12204 (comment)
1 parent 0b91d5e commit 3e81cb2

File tree

3 files changed

+50
-4
lines changed

3 files changed

+50
-4
lines changed

changelog/12204.bugfix.rst

+3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
Fix a regression in pytest 8.0 where tracebacks get longer and longer when multiple tests fail due to a shared higher-scope fixture which raised.
22

3+
Also fix a similar regression in pytest 5.4 for collectors which raise during setup.
4+
35
The fix necessitated internal changes which may affect some plugins:
46
- ``FixtureDef.cached_result[2]`` is now a tuple ``(exc, tb)`` instead of ``exc``.
7+
- ``SetupState.stack`` failures are now a tuple ``(exc, tb)`` instead of ``exc``.

src/_pytest/runner.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import dataclasses
66
import os
77
import sys
8+
import types
89
from typing import Callable
910
from typing import cast
1011
from typing import Dict
@@ -488,8 +489,13 @@ def __init__(self) -> None:
488489
Tuple[
489490
# Node's finalizers.
490491
List[Callable[[], object]],
491-
# Node's exception, if its setup raised.
492-
Optional[Union[OutcomeException, Exception]],
492+
# Node's exception and original traceback, if its setup raised.
493+
Optional[
494+
Tuple[
495+
Union[OutcomeException, Exception],
496+
Optional[types.TracebackType],
497+
]
498+
],
493499
],
494500
] = {}
495501

@@ -502,7 +508,7 @@ def setup(self, item: Item) -> None:
502508
for col, (finalizers, exc) in self.stack.items():
503509
assert col in needed_collectors, "previous item was not torn down properly"
504510
if exc:
505-
raise exc
511+
raise exc[0].with_traceback(exc[1])
506512

507513
for col in needed_collectors[len(self.stack) :]:
508514
assert col not in self.stack
@@ -511,7 +517,7 @@ def setup(self, item: Item) -> None:
511517
try:
512518
col.setup()
513519
except TEST_OUTCOME as exc:
514-
self.stack[col] = (self.stack[col][0], exc)
520+
self.stack[col] = (self.stack[col][0], (exc, exc.__traceback__))
515521
raise
516522

517523
def addfinalizer(self, finalizer: Callable[[], object], node: Node) -> None:

testing/test_runner.py

+37
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,43 @@ def raiser(exc):
142142
assert isinstance(func.exceptions[0], TypeError) # type: ignore
143143
assert isinstance(func.exceptions[1], ValueError) # type: ignore
144144

145+
def test_cached_exception_doesnt_get_longer(self, pytester: Pytester) -> None:
146+
"""Regression test for #12204 (the "BTW" case)."""
147+
pytester.makepyfile(test="")
148+
# If the collector.setup() raises, all collected items error with this
149+
# exception.
150+
pytester.makeconftest(
151+
"""
152+
import pytest
153+
154+
class MyItem(pytest.Item):
155+
def runtest(self) -> None: pass
156+
157+
class MyBadCollector(pytest.Collector):
158+
def collect(self):
159+
return [
160+
MyItem.from_parent(self, name="one"),
161+
MyItem.from_parent(self, name="two"),
162+
MyItem.from_parent(self, name="three"),
163+
]
164+
165+
def setup(self):
166+
1 / 0
167+
168+
def pytest_collect_file(file_path, parent):
169+
if file_path.name == "test.py":
170+
return MyBadCollector.from_parent(parent, name='bad')
171+
"""
172+
)
173+
174+
result = pytester.runpytest_inprocess("--tb=native")
175+
assert result.ret == ExitCode.TESTS_FAILED
176+
failures = result.reprec.getfailures() # type: ignore[attr-defined]
177+
assert len(failures) == 3
178+
lines1 = failures[1].longrepr.reprtraceback.reprentries[0].lines
179+
lines2 = failures[2].longrepr.reprtraceback.reprentries[0].lines
180+
assert len(lines1) == len(lines2)
181+
145182

146183
class BaseFunctionalTests:
147184
def test_passfunction(self, pytester: Pytester) -> None:

0 commit comments

Comments
 (0)