Skip to content

Add a set_filter() context manager to the caplog fixture #11610

@jenstroeger

Description

@jenstroeger

What's the problem this feature will solve?

I need to test a custom filter for logging, and currently I use one of the following two approaches:

def test_filter(caplog: pytest.LogCaptureFixture) -> None:
    caplog.set_level(logging.INFO)

    logger = logging.getLogger(__name__)  # This test module's logger.
    filter_ = SchnufteCustomFilter()
    logger.addFilter(filter_)

    # Run tests.
    assert len(caplog.record_tuples) == 1
    assert caplog.record_tuples[0] == ("test_custom_filter", 20, "Schnufte!")

    logger.removeFilter(filter_)

or

def test_filter(caplog: pytest.LogCaptureFixture) -> None:
    caplog.set_level(logging.INFO)

    filter_ = SchnufteCustomFilter()
    caplog.handler.addFilter(filter_)

    # Run tests.
    assert len(caplog.record_tuples) == 1
    assert caplog.record_tuples[0] == ("test_custom_filter", 20, "Schnufte!")     

    caplog.handler.removeFilter(filter_)

Describe the solution you'd like

Similar to the at_level() context manager I think it would be useful to wrap the second of the above filter setups into a custom context manager, that I can then call like so:

def test_filter(caplog: pytest.LogCaptureFixture) -> None:
    caplog.set_level(logging.INFO)

    filter_ = SchnufteCustomFilter()
    with caplog.set_filter(filter_):  # use_filter() or with_filter() or ...
        # Run tests.
        assert len(caplog.record_tuples) == 1
        assert caplog.record_tuples[0] == ("test_custom_filter", 20, "Schnufte!")     

Alternative Solutions

See above’s examples, I guess.

Additional context

I’m happy to give a PR a shot: I suppose the change would be adding a method to the LogCaptureFixture, for example:

@final
class LogCaptureFixture:

    @contextmanager
    def set_filter(filter_: logging.Filter) -> Generator[None, None, None]:  # Type needs to be aligned with _FilterType from stdlib/typeshed.
        self.handler.addFilter(filter_)
        try:
            yield
        finally:
            self.handler.removeFilter(filter_)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions