Hot to use pytest capture logging.debug

Question:

This is a test example from pytest document, and I change print to logging.warning.

import logging


def test_myoutput(capsys):  # or use "capfd" for fd-level
    print("hello")
    logging.warning("world")
    captured = capsys.readouterr()
    assert captured.out == "hellon"
    assert captured.out == "worldn"
    print("next")
    captured = capsys.readouterr()
    assert captured.out == "nextn"

This test fails with:

========================================================================================== FAILURES ===========================================================================================
________________________________________________________________________________________ test_myoutput ________________________________________________________________________________________

capsys = <_pytest.capture.CaptureFixture object at 0x7fd80ac3b0d0>

    def test_myoutput(capsys):  # or use "capfd" for fd-level
        print("hello")
        logging.warning("world")
        captured = capsys.readouterr()
        assert captured.out == "hellon"
>       assert captured.out == "worldn"
E       AssertionError: assert 'hellon' == 'worldn'
E         - world
E         + hello

test.py:9: AssertionError
-------------------------------------------------------------------------------------- Captured log call --------------------------------------------------------------------------------------
WARNING  root:test.py:6 world

So how can I capture logging.warning or logging.debug in pytest?

Asked By: PaleNeutron

||

Answers:

It is documented, no? Apparently, pytest does it itself. https://docs.pytest.org/en/7.1.x/how-to/logging.html

Answered By: bortzmeyer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.