如何在单元测试中自动生成测试用例号?
问题描述
如何自动生成单元测试中的测试用例数量?我的意思是类似于TEST_01、TEST_02、TEST_{生成编号}之类的内容。
import unittest
class TestSum(unittest.TestCase):
def test_01_sum(self):
self.assertEqual(sum([1, 2, 3]), 6, "Should be 6")
def test_02_sum_tuple(self):
self.assertEqual(sum((1, 2, 2)), 6, "Should be 6")
if name == '__main__':
unittest.main()
解决方案
要在运行时实现这一点,您实际上可以重命名测试类的测试方法:
def generate_test_numbers(test_class):
counter = 1
for method_name in dir(test_class):
if not method_name.startswith('test_N_'):
continue
method = getattr(test_class, method_name)
if not callable(method):
continue
new_method_name = method_name.replace('_N_', '_{:02d}_'.format(counter))
counter += 1
setattr(test_class, new_method_name, method)
delattr(test_class, method_name)
return test_class
您可以简单地从Main:
调用此函数generate_test_numbers(TestSum)
或者按照@VPfB的建议,将其用作类修饰符:
@generate_test_numbers
class TestSum(unittest.TestCase):
def test_N_sum(self):
self.assertEqual(sum([1, 2, 3]), 6, "Should be 6")
def test_N_sum_tuple(self):
self.assertEqual(sum((1, 2, 2)), 6, "Should be 6")
任何一个都将输出(带-v)
test_01_sum (__main__.TestSum) ... ok
test_02_sum_tuple (__main__.TestSum) ... FAIL
======================================================================
FAIL: test_02_sum_tuple (__main__.TestSum)
----------------------------------------------------------------------
Traceback (most recent call last):
File "q.py", line 8, in test_N_sum_tuple
self.assertEqual(sum((1, 2, 2)), 6, "Should be 6")
AssertionError: 5 != 6 : Should be 6
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=1)
相关文章