在 Python 中使用 unittest 检查系统退出和错误日志

Check for system exit and for error logs with unittest in Python

是否可以检查程序是否以 sys.exit() 停止并检查使用 logging 模块记录的消息?

例如,假设我在名为 func.py 的文件中有以下函数:

import logging
import sys

logging.basicConfig(level=logging.INFO,format='%(levelname)s:%(message)s')

def my_func(word):
    if word == "orange":
        logging.info("All is good with {}.".format(word))
    elif word == "apple":
        logging.error("Something went wrong with {}.".format(word))
        sys.exit()

现在,我已经创建了几个测试来检查我的函数的性能。我知道,要测试记录的消息——前提是程序完成了它的功能——我可以这样做:

import unittest
from func import *

class Test_errors_and_messages(unittest.TestCase):

    def test_logs(self):
        with self.assertLogs() as captured:
            my_func("orange")
        self.assertEqual(len(captured.records), 1)
        self.assertEqual(captured.records[0].getMessage(), "All is good with orange.")

如果我想检查程序是否按预期停止,我正在做类似的事情:

import unittest
from func import *

class Test_errors_and_messages(unittest.TestCase):

    def test_exit(self):
        with self.assertRaises(SystemExit):
            my_func("apple")

我的问题是:是否可以同时测试系统退出和记录的消息?换句话说,我想修改 test_exit() 测试以检查 (a) 程序以 SystemExit 停止,以及 (b) 消息

Something went wrong with apple.

已记录。特别是,我想检查这两个条件,因为在我的真实脚本中,我有几个条件会提示 sys.exit(),我想测试当程序停止时,它会因为我期望的原因而停止.

只需将两个上下文管理器放在一起即可:

with self.assertLogs() as captured, self.assertRaises(SystemExit):
    my_func("apple")
# assert on captured logs here