使用closu创建Python类方法

2024-06-26 12:59:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我是第一次使用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())

不过,我不知道该怎么写才对。帮忙吗?在


Tags: the方法inselfdeffunction断言unittest