Почему caplog.text пуст, хотя функция, которую я тестирую, записывает в журнал? - PullRequest
3 голосов
/ 23 января 2020

Я пытаюсь использовать pytest, чтобы проверить, записывает ли моя функция ожидаемый текст, такой как адресуемый этот вопрос (эквивалент pyunit будет assertLogs ). Следуя документации pytest , я передаю прибор caplog тестеру. Документация гласит:

Наконец, все журналы, отправляемые регистратору во время тестового прогона, становятся доступными на приборе в виде экземпляров logging.LogRecord и окончательного текста журнала.

Модуль, который я тестирую:

import logging
logger = logging.getLogger(__name__)

def foo():
    logger.info("Quinoa")

Тестер:

def test_foo(caplog):
    from mwe16 import foo
    foo()
    assert "Quinoa" in caplog.text

Я ожидаю, что этот тест пройдёт. Однако выполнение теста с pytest test_mwe16.py показывает сбой теста из-за того, что caplog.text пусто:

============================= test session starts ==============================
platform linux -- Python 3.7.3, pytest-5.3.0, py-1.8.0, pluggy-0.13.0
rootdir: /tmp
plugins: mock-1.12.1, cov-2.8.1
collected 1 item

test_mwe16.py F                                                          [100%]

=================================== FAILURES ===================================
___________________________________ test_foo ___________________________________

caplog = <_pytest.logging.LogCaptureFixture object at 0x7fa86853e8d0>

    def test_foo(caplog):
        from mwe16 import foo
        foo()
>       assert "Quinoa" in caplog.text
E       AssertionError: assert 'Quinoa' in ''
E        +  where '' = <_pytest.logging.LogCaptureFixture object at 0x7fa86853e8d0>.text

test_mwe16.py:4: AssertionError
============================== 1 failed in 0.06s ===============================

Почему caplog.text пусто, несмотря на foo() отправку текста в регистратор? Как использовать pytest, чтобы caplog.text захватывал зарегистрированный текст или иным образом проверял, что текст записывается в журнал?

Ответы [ 2 ]

1 голос
/ 23 января 2020

Документация здесь неясна. Из метода проб и ошибок, несмотря на то, что текст «все журналы, отправленные в регистратор во время тестового прогона, становятся доступными», по-прежнему записывает только журналы с определенными уровнями журналов. Чтобы фактически захватывал все журналы, необходимо установить уровень журнала для захваченных сообщений журнала, используя caplog.set_level или диспетчер контекста caplog.at_level, чтобы тестовый модуль становится:

import logging
def test_foo(caplog):
    from mwe16 import foo
    with caplog.at_level(logging.DEBUG):
        foo()
    assert "Quinoa" in caplog.text

Теперь тест проходит:

============================= test session starts ==============================
platform linux -- Python 3.7.3, pytest-5.3.0, py-1.8.0, pluggy-0.13.0
rootdir: /tmp
plugins: mock-1.12.1, cov-2.8.1
collected 1 item

test_mwe16.py .                                                          [100%]

============================== 1 passed in 0.04s ===============================
0 голосов
/ 18 марта 2020

У меня та же проблема, несмотря на то, что log_level все еще caplog пусто.

def test_user_type_event(caplog):
    from handler import lambda_handler

    caplog.set_level(logging.DEBUG)
    with open("mounts/events/user_insert_event.json") as f:
        user_type_event = json.load(f)

    lambda_handler(event=user_type_event, context=object())

    assert(len(caplog.records) > 0)

output

[CPython36:setup:stdout] =================================== FAILURES ===================================
[CPython36:setup:stdout] __________________ test_ambda_handler_user_type_event ___________________
[CPython36:setup:stdout] 
[CPython36:setup:stdout] caplog = <_pytest.logging.LogCaptureFixture object at 0x7fb13644a0f0>
[CPython36:setup:stdout] 
[CPython36:setup:stdout]     def test_lambda_handler_user_type_event(caplog):
[CPython36:setup:stdout]         from handler import lambda_handler
[CPython36:setup:stdout]     
[CPython36:setup:stdout]         caplog.set_level(logging.DEBUG)
[CPython36:setup:stdout]         with open("mounts/events/user_insert_event.json") as f:
[CPython36:setup:stdout]             user_type_event = json.load(f)
[CPython36:setup:stdout]         lambda_handler(event=user_type_event, context=object())
[CPython36:setup:stdout]     
[CPython36:setup:stdout] >       assert(len(caplog.records) > 0)
[CPython36:setup:stdout] E       assert 0 > 0
[CPython36:setup:stdout] E        +  where 0 = len([])
[CPython36:setup:stdout] E        +    where [] = <_pytest.logging.LogCaptureFixture object at 0x7fb13644a0f0>.records
[CPython36:setup:stdout] 
[CPython36:setup:stdout] test/test_handler.py:64: AssertionError

Есть еще какие-нибудь предложения? @ Геррит

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...