如何断言后跟 sys.exit() 的日志记录错误

问题描述

我在特定情况下使用 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?

解决方法

这是一种方法。

在您的测试模块中,您可以编写以下测试,其中 your_module 是定义实际代码的模块的名称,function() 是执行日志记录和调用 { {1}}。

sys.exit()

(如果你想缩短一点,你可以用record_tuples代替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. 。)

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