Python Decorators: usage in unit testing

Run Settings
LanguagePython
Language Version
Run Command
from unittest import TestCase from decorators import test_cases, add_tests from functions_to_test import f1, f2, f3 import unittest test_input = [ [ f1, [1], 2 ], [ f2, [2], 3 ], [ f3, [1, 2], False ] ] class TestSuit(TestCase): def test_f1(self): a = 1 self.assertEqual(f1(a), 2) TestSuit = add_tests(test_cases(test_input))(TestSuit) unittest.main()
def add_tests(generator): def class_decorator(cls): """Add tests to `cls` generated by `generator()`.""" for test_func, func, input, output in generator: test = lambda self, i=input, o=output, f=test_func, func=func: f(self, func, i, o) test.__name__ = "test_%s(%r, %r)" % (func.__name__, input, output) setattr(cls, test.__name__, test) print("added:", cls, test.__name__, test) return cls return class_decorator def test_cases(parameters): def t(self, func_to_test, data, result): self.assertEqual(func_to_test(*data), result) for function, input, output in parameters: yield t, function, input, output
def f1(a): return a*2 def f2(b): return b+1 def f3(a, b): return a>b
Editor Settings
Theme
Key bindings
Full width
Lines