问题
how can I generate automatically the numbers of test cases in unittest? I mean something like test_01, test_02, test_{generate number}.
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()
回答1:
To achieve this at runtime, you can actually rename the test methods for your test class:
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
You can either simply call this function from main:
generate_test_numbers(TestSum)
or as @VPfB suggested it, use it as a class decorator:
@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")
Either will output (with -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)
来源:https://stackoverflow.com/questions/58246057/how-can-generate-automatically-test-case-number-in-unittest