我第一次使用unittest
模块(因为我对Python很陌生),我发现自己一遍又一遍地执行相同的测试断言。我想将该代码拉出到一个公共函数中,但unittest
断言是TestCase
的方法(即self.assertTrue
)。我尝试使用闭包来构造每个TestCase
中为我执行断言的类方法。例如:
def _keys_in_dict_asserter(cls):
"""
A simple closure that creates an "assert keys in dict" function for each TestCase
"""
def cls_asserter(dictionary, *args):
for key in args:
cls.assertTrue(key in dictionary)
return cls_asserter
class TestFunctionUnderTest(TestCase):
# I want to create an asserter function as a class method using this
# class object. Python won't let me. Why?
@classmethod
keys_in_dict = _keys_in_dict_asserter(cls)
def test_returned_dict_contains_expected_items(self):
"""
Make sure the dict returned has all the keys expected by the caller under normal operation
"""
keys_in_dict(function_under_test())
但是,我不确定如何正确地写这个。帮助