Skip to main content
 首页 » 编程设计

python之阅读文件中的 Nose 测试参数,尤其是@attr

2025年05月04日11zhwl

如果我调用一个测试脚本

nosetests -a tag1='one' 

有没有办法在我的脚本中打印 tag1 的用户输入?

@attr(tag1=['one', 'two', 'three', 'four']) 
def test_real_logic(self): 
    #how to print the user input here 

请您参考如下方法:

并非没有痛苦。 self.test_real_logic.tag1 应该给你附加到函数的所有属性。它们作为字典存储在测试函数的 __dict__ 属性中。 对于 test_real_logic.tag1,它将是 ['one', 'two', 'three', 'four'].

如果您不想硬编码函数名称,您可以尝试通过执行以下操作来提取字典:

import sys 
def get_attr_dict(cls): 
   # cls here is either unittest.TestCase or whatever stores your test 
   return getattr(cls, sys._getframe().f_back.f_code.co_name).__dict__ 

现在您必须遍历本地属性并将它们与系统参数进行匹配并打印常见的属性,类似于属性插件已经做的事情。或者您可以稍微修改现有的 attrib 插件方法 validateAttrib 以便它向属性列表添加一个匹配的属性,就像这样(在 Lib/site- packages/nose/plugins/attrib.py):

def validateAttrib(self, method, cls = None): 
    """Verify whether a method has the required attributes 
    The method is considered a match if it matches all attributes 
    for any attribute group. 
    .""" 
    # TODO: is there a need for case-sensitive value comparison? 
    any = False 
    for group in self.attribs: 
        match = True 
        for key, value in group: 
            attr = get_method_attr(method, cls, key) 
            if callable(value): 
                if not value(key, method, cls): 
                    match = False 
                    break 
            elif value is True: 
                # value must exist and be True 
                if not bool(attr): 
                    match = False 
                    break 
            elif value is False: 
                # value must not exist or be False 
                if bool(attr): 
                    match = False 
                    break 
            elif type(attr) in (list, tuple): 
                # value must be found in the list attribute 
                if not str(value).lower() in [str(x).lower() 
                                              for x in attr]: 
                    match = False 
                    break 
            else: 
                # value must match, convert to string and compare 
                if (value != attr 
                    and str(value).lower() != str(attr).lower()): 
                    match = False 
                    break 
        any = any or match 
        #remember match 
        if match: 
            matched_key = key 
            matched_value = value  
 
    if any: 
        method.__dict__['matched_key'] = matched_key 
        method.__dict__['matched_value'] = matched_value 
 
        # not True because we don't want to FORCE the selection of the 
        # item, only say that it is acceptable 
        return None 
    return False 

这样你的 self.test_real_logic 将有两个额外的属性 matched_key=tag1 和 matched_value=one ,你可以像 >tag1 属性。