在Pytes中捕获Python日志记录输出

2024-04-19 19:10:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的项目上有一个点击命令应用程序副本. 我使用click7.0,Pytest 4.6.4。我有一个用户界面用于编写日志的接口。 我不知道为什么我不能在测试时捕捉到日志消息。在

这是我的项目结构

project/
    core/
        __init__.py
        app.py
        ui.py

    tests/
        __init__.py
        test_main.py

应用程序副本

^{pr2}$

用户界面

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

logger.addHandler(ch)


#interface which i use on my project
def info(msg=""):
    logger.info(msg)

def error(msg=""):
    logger.error(msg)

def warning(msg=""):
    logger.warning(msg)

def debug(msg=""):
    logger.debug(msg)

测试_主.py

from click.testing import CliRunner
from core.app import cli


def test_main():
    runner = CliRunner()
    result = runner.invoke(cli, ['main'])
    assert "hello world" in result.output

我之所以有错误是因为结果.输出是空字符串“”

def test_main():
        runner = CliRunner()
        result = runner.invoke(cli, ['main'])
>       assert "hello world" in result.output
E       AssertionError: assert 'hello world' in ''
E        +  where '' = <Result okay>.output

我做错了什么? 我还注意到,当我将处理程序移到接口函数时,测试将通过。我不理解这种行为。在

像这样的东西

用户界面

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

#interface which i use on my project
def info(msg=""):
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    logger.addHandler(ch)
    logger.info(msg)

请帮忙。在


Tags: pydebugimportinfoprojectmainloggingdef