Pytest's `caplog` returns empty text

25 views Asked by At

I was trying to test INFO-level log text during a function in a test suite.

My function was approximately (in main.py):

import logging

log = logging.getLogger()
log.setLevel(os.environ.get('LOGGING_LEVEL', 'INFO'))

def _get_item(var: str):
    item = other_function.get_item(var)
    return item

My test looked like (in tests/test_logging.py):

import logging
import main

def test__processing(caplog):
    caplog.set_level(logging.INFO, main.__name__)
    item = main._get_item('variable')
    assert 'log output expected from main._get_item' in caplog.text

Then, my test fails with the error:

FAILED tests/test_logging.py::test__processing - AssertionError: assert 'log output     expected from main._get_item' in ''

I can't quite figure out what I'm doing wrong here and why the caplog returns empty. How can I fix this?

I also tried:

with caplog.at_level(logging.INFO, main.name)      
    item = main._get_item('variable')      
    assert 'log output expected from main._get_item' in caplog.text

and I expected that it would pass.

1

There are 1 answers

0
Diego Torres Milano On

This is probably what you want to do

import os
import logging

log = logging.getLogger()
log.setLevel(os.environ.get('LOGGING_LEVEL', 'INFO'))

def get_item(v):
    log.info(v)

def _get_item(var: str):
    item = get_item(var)
    return item


def test__processing(caplog):
    caplog.set_level(logging.INFO, logger=__name__)
    item = _get_item('variable')
    assert 'variable' in caplog.text