【问题标题】:Python unittest report passed testPython unittest 报告通过测试
【发布时间】:2013-05-21 21:20:38
【问题描述】:

您好,我在“test.py”下有一个如下测试模块:

class TestBasic(unittest.TestCase):
    def setUp(self):
        # set up in here

class TestA(TestBasic):
    def test_one(self):
        self.assertEqual(1,1)

    def test_two(self):
        self.assertEqual(2,1)

if __name__ == "__main__":
    unittest.main()

这很好用,但我需要一种方法来打印通过的测试,例如我可以将输出打印到控制台:

test_one: PASSED
test_two: FAILED

现在变了,我可以在 self.assertEqual() 之后添加一个打印语句,这将是一个通过的测试,我可以打印它,但我需要从不同的模块运行测试,比如说“ test_reporter.py" 我有这样的东西:

import test
suite = unittest.TestLoader().loadTestsFromModule(test)
results = unittest.TextTestRunner(verbosity=0).run(suite)

此时有结果是我建立报告的时候。

欢迎大家提出建议

谢谢!!

【问题讨论】:

  • 将详细程度更改为 2,您将看到每个案例的输出
  • 你为什么不把它作为答案发布?

标签: python unit-testing python-unittest


【解决方案1】:

就像Corey's comment 提到的那样,如果你设置verbosity=2 unittest 将打印每次测试运行的结果。

results = unittest.TextTestRunner(verbosity=2).run(suite)

如果您想要更多的灵活性 - 因为您正在创建套件并使用测试运行器,所以您可能会 - 我建议您查看 Twisted Trial。它扩展了 Python 的 unittest 模块并提供了更多的断言和报告功能。

编写您的测试将完全相同(除了子类 twisted.trial.unittest.TestCase 与 python 的 unittest),因此您的工作流程不会改变。您仍然可以使用您的 TestLoader,但您将拥有更多 TestReporters http://twistedmatrix.com/documents/11.1.0/api/twisted.trial.reporter.html 的选项。

例如,默认的 TestReporter 是 TreeReporter,它返回以下输出:

【讨论】:

  • 你好,我试过你的解决方案,效果很好,问题是通过的测试没有显示[OK],失败的测试显示[FAIL]有什么想法吗?
  • 如果你想让输出看起来像截图,你需要安装Twisted Trial,然后使用trial test_file.py而不是python -m unittest运行它
  • 是的,我错过了从 twisted.trial.unittest.TestCase 继承的子类,现在可以使用了,谢谢
猜你喜欢
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-04
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多