How to use logging, pytest fixture and capsys?

后端 未结 3 574
灰色年华
灰色年华 2021-01-04 19:14

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

I have a fixture that creates a logger.

In my 1st test case, I do not use

相关标签:
3条回答
  • 2021-01-04 19:53

    Thanks a lot for your ideas!

    Reverse logger, capsys, make logger request the capsys fixture and use capfd do not change anything.

    I tried pytest-catchlog plugin and it works fine!

    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!
    

    In my original tests, I logged to stdout and stderr and captured them. This is an even better solution, as I do not need this tweak to check that my logs work fine.

    Well, now I just need to rework all my tests to use caplog, but this is my own business ;)

    The only thing left, now that I have a better solution, is to understand what is wrong in my original test case def test_logger_with_fixture(logger, capsys).

    0 讨论(0)
  • 2021-01-04 19:55

    As of pytest 3.3, the functionality of capturing log message was added to pytest core. This is supported by the caplog fixture:

    def test_baz(caplog):
        func_under_test()
        for record in caplog.records:
            assert record.levelname != 'CRITICAL'
        assert 'wally' not in caplog.text
    

    More information can be found at the documentation

    0 讨论(0)
  • 2021-01-04 20:07

    I'm guessing the logger gets created (via the fixture) before the capsys fixture is set up.

    Some ideas:

    • Use the pytest-catchlog plugin
    • Maybe reverse logger, capsys
    • Make logger request the capsys fixture
    • Use capfd which is more lowlevel capturing without altering sys
    0 讨论(0)
提交回复
热议问题