是否可以检查程序是否停止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()
Run Code Online (Sandbox Code Playgroud)
现在,我创建了几个测试来检查我的函数的性能。我知道,要测试记录的消息(假设程序完成其功能),我可以执行以下操作:
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.")
Run Code Online (Sandbox Code Playgroud)
如果我想检查程序是否按预期停止,我正在做类似的事情:
import unittest
from func import *
class Test_errors_and_messages(unittest.TestCase):
def test_exit(self):
with self.assertRaises(SystemExit):
my_func("apple")
Run Code Online (Sandbox Code Playgroud)
我的问题是:是否可以测试系统退出和同时记录的消息?换句话说,我想修改测试test_exit()来检查(a)程序是否以 a 停止SystemExit,(b)消息
苹果出了点问题。 …