How to use logging, fittings and pytest capsips?

I am trying to execute unit-test some algorithm that uses a logging library.

I have a tool that creates a registrar.

In my 1st test case, I do not use this device and use print to enter standard output. This test case passes .

In my second test case, I use this tool, but not as described in the pytest document. I just call the related function in my test to get the logger. Then I use the logger to enter standard output. This test case passes .

In my third test case, I use this tool as described in the pytest document. The device is passed as an argument to the test function. Then I use the logger to enter standard output. This test case does not work ! It does not find anything in stdout. But the error message says my log is in the captured stdout call.

What am I doing wrong?

import pytest

import logging
import sys

@pytest.fixture()
def logger():

    logger = logging.getLogger('Some.Logger')
    logger.setLevel(logging.INFO)
    stdout = logging.StreamHandler(sys.stdout)
    logger.addHandler(stdout)

    return logger

def test_print(capsys):

    print 'Bouyaka!'

    stdout, stderr = capsys.readouterr()
    assert 'Bouyaka!' in stdout

    # passes

def test_logger_without_fixture(capsys):

    logger().info('Bouyaka!')

    stdout, stderr = capsys.readouterr()
    assert 'Bouyaka!' in stdout

    # passes

def test_logger_with_fixture(logger, capsys):

    logger.info('Bouyaka!')

    stdout, stderr = capsys.readouterr()
    assert 'Bouyaka!' in stdout

    # fails with this error:
    # >       assert 'Bouyaka!' in stdout
    # E       assert 'Bouyaka!' in ''
    #
    # tests/test_logging.py:21: AssertionError
    # ---- Captured stdout call ----
    # Bouyaka!

No change if I reorder the test cases.

+4
source share
2 answers

Thanks so much for your ideas!

Reverse logger, capsys, make loggerrequest the device capsysand use capfdnothing to change.

pytest-catchlog , !

import pytest

import logging

@pytest.fixture()
def logger():

    logger = logging.getLogger('Some.Logger')
    logger.setLevel(logging.INFO)

    return logger

def test_logger_with_fixture(logger, caplog):

    logger.info('Bouyaka!')

    assert 'Bouyaka!' in caplog.text

    # passes!

stdout stderr . , , , .

, , caplog, ;)

, , , , - , def test_logger_with_fixture(logger, capsys).

+5

, ( ) capsys.

:

+4

Source: https://habr.com/ru/post/1649185/


All Articles