我有一个 Python 2.7方法,它有时会调用
sys.exit(1)
是否有可能进行单元测试,以验证在满足正确的条件时调用这行代码?
是的。 sys.exit提高 SystemExit,所以你可以用 assertRaises检查它:
sys.exit
SystemExit
assertRaises
with self.assertRaises(SystemExit): your_method()
SystemExit的实例有一个属性 code,它被设置为建议的退出状态,而 assertRaises返回的上下文管理器有一个被捕获的异常实例 exception,因此检查退出状态很容易:
code
exception
with self.assertRaises(SystemExit) as cm: your_method() self.assertEqual(cm.exception.code, 1)
Sys.exit 文档 :
从 Python 退出。这是通过引发 SystemExit异常来实现的... 有可能在外部级别拦截退出尝试。
这是一个完整的工作示例。尽管有 帕维尔的回答很棒,它花了我一段时间来弄明白这一点,所以我把它包括在这里,希望它将有所帮助。
import unittest from glf.logtype.grinder.mapping_reader import MapReader INCOMPLETE_MAPPING_FILE="test/data/incomplete.http.mapping" class TestMapReader(unittest.TestCase): def test_get_tx_names_incomplete_mapping_file(self): map_reader = MapReader() with self.assertRaises(SystemExit) as cm: tx_names = map_reader.get_tx_names(INCOMPLETE_MAPPING_FILE) self.assertEqual(cm.exception.code, 1)
作为 帕维尔的回答很棒的附加说明,您还可以检查特定的状态(如果它们是在您正在测试的函数中提供的)。例如,如果 your_method()包含以下 sys.exit("Error"),就可以专门测试“ Error”:
your_method()
sys.exit("Error")
with self.assertRaises(SystemExit) as cm: your_method() self.assertEqual(cm.exception, "Error")
我在 Python 单元测试文档的“异常测试”搜索中找到了你问题的答案。使用您的示例,单元测试如下所示:
self.assertRaises(SystemExit, your_function, argument 1, argument 2)
记住要包含测试函数所需的所有参数。