python - Python Unittest 能否返回单个测试的结果代码?

标签 python python-unittest

我正在尝试使用 unittest 来自动化测试用例。但是,当测试通过或失败时,它会将结果写入控制台。有什么办法可以让 unittest 返回一些测试结果状态代码?这是因为我想在我的测试脚本中添加另一个函数来将测试结果记录到我们的数据库中。以编程方式评估测试通过或失败的最佳方法是什么?

最佳答案

这取决于您需要多少有关测试结果的信息。如果您只想知道使用 unittest.main 测试是否通过/失败:

"By default main calls sys.exit() with an exit code indicating success or failure of the tests run"



因此,检查测试脚本的返回值(0=通过,非 0=失败)就足以获得通过/失败的答案。

如果您需要有关测试的更多详细信息,可以跳过 unittest.main()调用并调用 TestRunner.run方法直接返回 TestResult 描述结果的对象。一个例子:
import unittest
from unittest import TextTestRunner

class TestExample(unittest.TestCase):

    def test_pass(self):
        self.assertEqual(1, 1, 'Expected 1 to equal 1')

    def test_fail(self):
        self.assertEqual(1, 2, 'uh-oh')

if __name__ == '__main__':
    test_suite = unittest.TestLoader().loadTestsFromTestCase(TestExample)
    test_result = TestRunner().run(test_suite)

...您现在可以检查 test_result变量以获取有关测试运行的更多详细信息:
>>> test_result.testsRun
2
>>> test_result.failures
[(<test_example.TestExample testMethod=test_fail>, 'Traceback (most recent call last):\n  File "test_example.py", line 9, in test_fail\n    self.assertEqual(1, 2, \'uh-oh\')\nAssertionError: uh-oh\n')]
>>> len(test_result.failures)
1
TestResult的属性记录在案 here ,并解释了运行测试运行器的示例和选项 here .

关于python - Python Unittest 能否返回单个测试的结果代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433333/

相关文章:

python - 如何有效地定义可变大小的 numpy 数组?

python - 如何将 Jupyter 中的 TensorFlow 2 模型的结果保存到文本文件?

python - 是否有一个常量在单元测试时为真,否则为假?

python unittest "X tests run"数字从哪里来?

python - 将 python mockito 与 python unittest 集成

python - 如何将函数应用于自身?

python - 将 Spacy 文档的一部分提取为新文档

django - 你如何对 Django RawQuerySets 进行单元测试

python3如何设置单元测试中通过的测试

python - “列表”对象在列表理解中不可调用