Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog/14436.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed ``KeyError`` from the ``caplog`` fixture when a plugin accesses
``caplog.text`` during teardown report creation.
6 changes: 4 additions & 2 deletions src/_pytest/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,8 @@ class LogCaptureFixture:
def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None:
check_ispytest(_ispytest)
self._item = item
self._handler = item.stash[caplog_handler_key]
self._records = item.stash[caplog_records_key]
self._initial_handler_level: int | None = None
# Dict of log name -> log level.
self._initial_logger_levels: dict[str | None, int] = {}
Expand All @@ -446,7 +448,7 @@ def _finalize(self) -> None:
@property
def handler(self) -> LogCaptureHandler:
"""Get the logging handler used by the fixture."""
return self._item.stash[caplog_handler_key]
return self._handler

def get_records(
self, when: Literal["setup", "call", "teardown"]
Expand All @@ -461,7 +463,7 @@ def get_records(

.. versionadded:: 3.4
"""
return self._item.stash[caplog_records_key].get(when, [])
return self._records.get(when, [])

@property
def text(self) -> str:
Expand Down
28 changes: 28 additions & 0 deletions testing/logging/test_fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,3 +508,31 @@ def test_that_fails(request, caplog):
["*Print message*", "*INFO log message*", "*WARNING log message*"]
)
assert result.ret == 1


def test_caplog_text_access_from_teardown_makereport(pytester: Pytester) -> None:
"""Regression test for #14436."""
pytester.makeconftest(
"""
def pytest_runtest_makereport(item, call):
if call.when == "teardown" and "caplog" in item.funcargs:
caplog = item.funcargs["caplog"]
caplog.text
assert [r.getMessage() for r in caplog.get_records("call")] == [
"call log"
]
"""
)
pytester.makepyfile(
"""
import logging

def test_uses_caplog(caplog):
caplog.set_level(logging.INFO)
logging.info("call log")
"""
)

result = pytester.runpytest()
result.assert_outcomes(passed=1)
result.stdout.no_fnmatch_line("*KeyError*")
Loading