失败后,Python单元测试将继续 [英] Python Unittests continue after failure
问题描述
在 unittest 中失败后继续测试的最佳方法是什么?
What's the best way of continuing tests after failure in unittest?
#!/usr/env/bin python2.7
import unittest
from fib import fib
class FibTests(unittest.TestCase):
def test_0(self):
self.assertEqual(fib(0), 0)
self.assertEqual(fib(1), 1)
self.assertEqual(fib(2), 1)
self.assertEqual(fib(5), 5)
self.assertEqual(fib(10), 55)
def test_1(self):
self.assertEqual(fib(0), 1)
def test_2(self):
self.assertEqual(fib(1), 0)
self.assertEqual(fib(5), 0)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(FibTests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
看一下test_2,它只会告诉我失败是1次,而不是2次.
Looking at test_2, it'll only tell me there's 1 failure instead of 2.
此外,我如何在结尾处说明结果:
Additionally, how can I collect the results at the end stating:
test_0 -- 0 failures
test_1 -- 1 failures
test_2 -- 2 failures
动机:
我正在尝试创建一个测试游戏.人们提交测试,如果他们失败了别人的程序,他们会得到分数;每次测试失败都是一分.提供这种功能的最简单方法是什么?
I'm trying to create a testing game. People submit tests and if they fail others' programs they get points; each test failure is one point. What's the easiest way of providing this type of capability?
推荐答案
您必须将每个测试用例分为不同的方法.为了更轻松地创建新测试/节省键入时间,您可以根据这样的输入自动生成测试用例
You have to separate each test case into different method. To make it easier to create new test / save typing time, you can auto-generate test case based on input like this
#!/usr/env/bin python2.7
import unittest
from fib import fib
class FibTests(unittest.TestCase):
pass
def test_gen(expected, actual):
def test_method(self):
return self.assertEqual(expected, actual)
return test_method
if __name__ == '__main__':
cases = ((fib(1), 1), (fib(2), 1), (fib(5), 5))
for index, case in enumerate(cases):
test_name = 'test_{0}'.format(index)
test = test_gen(case[1], case[0])
setattr(FibTests, test_name, test)
suite = unittest.TestLoader().loadTestsFromTestCase(FibTests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
这篇关于失败后,Python单元测试将继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!