【问题标题】:How to assert logging error which is followed by a sys.exit()如何断言后跟 sys.exit() 的日志记录错误
【发布时间】:2021-08-21 22:59:09
【问题描述】:

我正在使用 Python 的日志记录模块在特定情况下生成 ERROR 消息,然后是 sys.exit()。

if platform is None:  
    logging.error(f'No platform provided!')
    sys.exit()

Continue do other stuff

现在我正在使用 pytest 对特定的错误消息进行单元测试。但是 sys.exit() 语句会导致 pytest 由于 SystemExit 事件而检测到错误,即使错误消息通过了测试。

模拟 sys.exit 会使其余代码正在运行(“继续做其他事情”),这会导致其他问题。

我尝试了以下方法:

LOGGER = logging.getLogger(__name__)

platform = None
data.set_platform(platform, logging=LOGGER)
assert "No platform provided!" in caplog.text

这个问题类似:How to assert both UserWarning and SystemExit in pytest,但它以不同的方式引发错误。

如何让 pytest 忽略 SystemExit?

【问题讨论】:

    标签: python logging pytest systemexit


    【解决方案1】:

    这是一种方法。

    在您的测试模块中,您可以编写以下测试,其中your_module 是定义实际代码的模块的名称,function() 是执行日志记录并调用sys.exit() 的函数。

    import logging
    from unittest import mock
    from your_module import function
    
    def test_function(caplog):
        with pytest.raises(SystemExit):
            function()
    
        log_record = caplog.records[0]
        assert log_record.levelno == logging.ERROR
        assert log_record.message == "No platform provided!"
        assert log_record.lineno == 8   # Replace with the line no. in which log is actually called in the main code.
    

    (如果您想稍微缩短一点,可以使用record_tuples 而不是records。)

    编辑:使用caplog 而不是模拟日志模块。

    【讨论】:

    • 谢谢,但我无法完成这项工作。 mock.patch 语句出错:'ModuleNotFoundError: No module named 'your_module.logging'; 'your_module' is not a package.(其中我已将 your_module 替换为我的模块名称)。
    • 这是因为pytest 找不到your_module。对于如何解决这个问题,您有几个选择。最简单的一种是将your_module.pytest_your_module.py(包含测试的文件)放在同一个目录中。概述了其他一些选项hereherehere
    • 顺便说一句,您可以使用caplog 夹具来验证记录的错误而不是修补。
    • 谢谢你,@hoefling,太棒了!感谢您让我知道caplog
    猜你喜欢
    • 2012-09-14
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多