loguru icon indicating copy to clipboard operation
loguru copied to clipboard

pytest logger stdout sink

Open ixenion opened this issue 1 year ago • 1 comments

Hey, what's up!

How did you manage to conduct sink=sys.stdout test like in your tests/test_add_sinks.py:

@repetitions
def test_stderr_sink(rep, capsys):
    log(sys.stderr, rep)
    out, err = capsys.readouterr()
    assert out == ""
    assert err == expected * rep

?

Because when I create my own test function:

from loguru import logger
def test_stdout_sink(capsys) -> None:
    # By default logger already writes to stdout
    # So Im not setting anything here.
    message = f"Hello"
    logger.info(message)
    out, err = capsys.readouterr()
    assert message in out

I got accert error:

accert "Hello" == ""

For some reason I cant catch logger stdout with capsys. "out" is just empty string.

What should I set to make it work?

Also there is pytest-loguru project, and what he does is add caplog.handler like so:

magic_handler_id = \
        logger.add(sink=caplog.handler, level=0)
message = f"Test info message"
logger.info(message)
assert message in caplog.text

And it passes :) . The fun is that he don't test sys.stdout with this approach.

ixenion avatar Aug 31 '24 09:08 ixenion

Hi @ixenion.

The problem with your test is that, at the time the test function is called, the logger is already configured with the sys.stdout default sink. Therefore, although capsys will replace sys.stdout for testing purpose, the logger won't perceive this change. The logger will write to an outdated reference of sys.stdout, and capsys won't capture the logs.

As a workaround, you actually need to call logger.add(sys.stdout) within your test (despite your comment in code stating the opposite, sorry :) ):

from loguru import logger

def test_stdout_sink(capsys) -> None:
    logger.add(sys.stdout)
    message = f"Hello"
    logger.info(message)
    out, err = capsys.readouterr()
    assert message in out

This is actually done in the log() function of my own tests: https://github.com/Delgan/loguru/blob/80f05fd2635a9f728565585fed02bed7c2be968a/tests/test_add_sinks.py#L17-L23

Delgan avatar Sep 22 '24 20:09 Delgan