Exception for caplog fixture

314 views Asked by At

So I have a lot of (pytest) test that test logs with the caplog fixture, probably not done in the best way (as I'm realizing now). I used a ot of statements like caplog.records[0] and caplog.records[-1] but now I need to log something in a function that is called a lot through out my project and this messes up all my test where I currently didn't expect to have additional logs. Is there any way how I can tell caplog that it should not record this new specific log, without having to rewrite all usages of caplog?

I was thinking of something like writing a wrapper around the caplog fixture ...?

1

There are 1 answers

0
man zet On

I found a quite simple solution to this: I can just disable certain loggers by name with a simple fixture like this:

@pytest.fixture(scope='function')
def disable_logger():
    """
    you can use this fixture to disable certain loggers in your tests. for that you need to call the fixture with a
    list of str like: disable_logger(["your.path.to.your.logger"]).
    """
    _logger_names = []

    def func(names):
        if not isinstance(names, list) or any(not isinstance(s, str) for s in names):
            raise TypeError("disable_logger expects a list of str")
        _logger_names.extend(names)
        for name in _logger_names:
            logger = logging.getLogger(name)
            logger.disabled = True

    yield func

    for name in _logger_names:
        logger = logging.getLogger(name)
        logger.disabled = False