-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Closed
Description
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_)miki5799
Metadata
Metadata
Assignees
Labels
No labels