Skip to content

raises: Fix KeyError when caplog handler is missing#14488

Closed
V1SHAL421 wants to merge 4 commits into
pytest-dev:mainfrom
V1SHAL421:fix/caplog-handler-missing-key-error
Closed

raises: Fix KeyError when caplog handler is missing#14488
V1SHAL421 wants to merge 4 commits into
pytest-dev:mainfrom
V1SHAL421:fix/caplog-handler-missing-key-error

Conversation

@V1SHAL421
Copy link
Copy Markdown
Contributor

@V1SHAL421 V1SHAL421 commented May 16, 2026

Summary

Closes #14436

Raise a descriptive RuntimeError instead of an opaque KeyError when accessing caplog.handler before it has been initialised.

Problem

Accessing caplog.handler when the handler has not been set up raised a confusing KeyError with a raw StashKey object address:

This gives users no useful information about what went wrong.

Solution

Modified LogCaptureFixture.handler to use .get() on the stash and raise a descriptive RuntimeError if the handler is None:

@property
def handler(self) -> LogCaptureHandler:
    """Get the logging handler used by the fixture."""
    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

Test Cases

Test that accessing caplog.handler after manually removing it from the stash raises a RuntimeError with a descriptive message:

def test_caplog_missing_handler_raises_error(caplog):
    del caplog._item.stash[caplog_handler_key]

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

@psf-chronographer psf-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label May 16, 2026
@V1SHAL421 V1SHAL421 changed the title Fix KeyError when caplog handler is missing raises: Fix KeyError when caplog handler is missing May 16, 2026
@The-Compiler
Copy link
Copy Markdown
Member

This doesn't actually fix the underlying bug, which is a situation that should never happen in the first place, so I don't see the point in just painting over it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

caplog fixture raises KeyError

2 participants