Skip to content

Commit 5f5a27d

Browse files
committed
add hook to catch StashKey errors on teardown
1 parent 73e767c commit 5f5a27d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

tests/conftest.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,38 @@ def pytest_collection_modifyitems(items, *args, **kwargs):
212212
item.add_marker("fast")
213213

214214

215+
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
216+
def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo):
217+
# The tmp_path fixture frequently throws errors like:
218+
# - KeyError: <_pytest.stash.StashKey object at 0x79ba385fe1a0>
219+
# in its teardown. This causes pytest to mark the test as failed even though we have zero control over this behaviour.
220+
# So we log/swallow that particular error here rather than raising it
221+
222+
# we only care about tests that used the tmp_path fixture
223+
if "tmp_path" not in getattr(item, "fixturenames", []):
224+
return
225+
226+
outcome = yield
227+
228+
result: pytest.TestReport = outcome.get_result()
229+
230+
if result.when != "teardown":
231+
return
232+
233+
# If we specifically failed with a StashKey error in teardown, mark the test as passed
234+
if result.failed:
235+
exception = call.excinfo
236+
if (
237+
exception
238+
and isinstance(exception.value, KeyError)
239+
and "_pytest.stash.StashKey" in repr(exception)
240+
):
241+
result.outcome = "passed"
242+
item.add_report_section(
243+
"teardown", "stderr", f"Ignored tmp_path teardown error: {exception}"
244+
)
245+
246+
215247
# Ignore all local config files
216248
@pytest.fixture(scope="session", autouse=True)
217249
def ignore_local_config_files():

0 commit comments

Comments
 (0)