python - 在 Python 中使用 unittest 检查系统退出和错误日志
问题描述
是否可以检查程序是否停止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)程序是否以 a 停止SystemExit
和(b)消息
苹果出了点问题。
被记录下来。特别是,我想检查这两个条件,因为在我的真实脚本中,我有几个条件会提示sys.exit()
,并且我想测试程序停止时,它会因为我期望的原因而停止。
解决方案
只需将两个上下文管理器放在一起:
with self.assertLogs() as captured, self.assertRaises(SystemExit):
my_func("apple")
# assert on captured logs here
推荐阅读
- php - Laravel 记住令牌未清除 [5.7]
- php - 如何为 YoutubeAPI 使用 GoogleAPI access_token 和 refresh_token?
- linux - 在 linux (ubuntu) 上编译 QT 5.10.0 - 抱怨找不到 qmake 配置文件
- r - tmap R - 将主题图标题的字体从普通更改为斜体,但保持图例的字体普通
- azure-ad-b2c - 在 webtest 中获取 AAD B2C 访问令牌
- mongodb - 如何使用 Loopback.io 完全删除模型?
- arrays - 将值分配给内部包含数组的结构数组
- symfony - 如何在 symfony 中使用 vuejs
- javascript - 如何在值是数组的对象数组中映射?Javascript?
- matlab - matlab乳胶解释器中的粗体希腊字母