我是第一次使用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())
不过,我不知道该怎么写才对。帮忙吗?在
目前没有回答
相关问题 更多 >
编程相关推荐