I was given a class decorator to generate automatically the number of a test case in unittest this is the decorator:
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
My problem is when I try to run the class decorator in my unittest file:
import unittest
from generator import generate_test_numbers
@generate_test_numbers
class TestStringMethods(unittest.TestCase):
def test_n_remove(self):
print("1")
def test_n_add(self):
print("2")
def test_n_c(self):
print("3")
def test_n_d(self):
print("4")
def test_n_e(self):
print("5")
def test_n_f(self):
print("6")
def test_n_g(self):
print("7")
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestStringMethods)
unittest.TextTestRunner(verbosity=2).run(suite)
I expect to get test_n_remove as the first test and not last:
test_01_add (__main__.TestStringMethods) ... 2
ok
test_02_c (__main__.TestStringMethods) ... 3
ok
test_03_d (__main__.TestStringMethods) ... 4
ok
test_04_e (__main__.TestStringMethods) ... 5
ok
test_05_f (__main__.TestStringMethods) ... 6
ok
test_06_g (__main__.TestStringMethods) ... 7
ok
test_07_remove (__main__.TestStringMethods) ... 1
ok