Skip to content
Closed
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
1 change: 1 addition & 0 deletions changelog/14488.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Raise a descriptive :class:`RuntimeError` instead of a :class:`KeyError` when accessing ``caplog.handler`` before it has been initialized.
5 changes: 4 additions & 1 deletion src/_pytest/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,10 @@ def _finalize(self) -> None:
@property
def handler(self) -> LogCaptureHandler:
"""Get the logging handler used by the fixture."""
return self._item.stash[caplog_handler_key]
handler = self._item.stash.get(caplog_handler_key, None)
if handler is None:
raise RuntimeError("caplog handler was not initialized for this test item")
return handler

def get_records(
self, when: Literal["setup", "call", "teardown"]
Expand Down
8 changes: 8 additions & 0 deletions testing/logging/test_fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from collections.abc import Iterator
import logging

from _pytest.logging import caplog_handler_key
from _pytest.logging import caplog_records_key
from _pytest.pytester import Pytester
import pytest
Expand Down Expand Up @@ -508,3 +509,10 @@ def test_that_fails(request, caplog):
["*Print message*", "*INFO log message*", "*WARNING log message*"]
)
assert result.ret == 1


def test_caplog_missing_handler_raises_error(caplog: pytest.LogCaptureFixture) -> None:
del caplog._item.stash[caplog_handler_key]

with pytest.raises(RuntimeError, match="caplog handler was not initialized"):
_ = caplog.handler
Loading