对于测试发现,utest_uu=False magic属性是如何工作的

2024-09-24 00:30:49 发布

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

因此,我尝试实现类似于unittesting框架的以下功能:

class BaseTest(T.TestCase):
    # Disables this test from being run
    __test__ = False

    def test_foo(self): pass


# However this test is picked up because it doesn't directly have __test__ set
class InheritingTest(BaseTest): pass

我觉得很奇怪:

^{pr2}$

这表示它没有使用metaclass在类型的构造中将__test__设置为{}。在

我试着浏览python库find . -name "*.py" | xargs grep '__test__',但似乎没有找到任何与此相关的内容。在

我解决这个问题的“猜测”方法是:

def is_class_tested(cls):
    return cls.__dict__.get('__test__', True)

但是我觉得这很脆弱。。。有没有一种更干净/更好的方法在所有情况下都有效?类有没有可能没有__dict__属性?在


Tags: 方法test功能框架isdefpassthis
2条回答

请证明,您使用的库在第140行的testify/test_discovery.py中执行以下操作:

    # it's not a list, it's not a bare module - let's see if it's an honest-to-god TestCaseBase
    elif isinstance(test_module, MetaTestCase) and (not '__test__' in test_module.__dict__ or bool(test_module.__test__)):
        ...
    # detect unittest test cases
    elif issubclass(test_module, unittest.TestCase) and (not '__test__' in test_module.__dict__ or bool(test_module.__test__)):

因此,换句话说,它正以一种更详细的方式执行“guess”方法所做的事情:它直接测试__test__在类__dict__中的存在性和值。在

一个类是否有可能没有一个\uu dict\uuu属性?我对这个问题的最初反应是否定的。这可能不是您所要求的,因为如果一个类的实例定义了__slots__,并且没有从已经存在__dict__的类继承,那么这个类的实例就可以不带__dict__。请参见Python Data Model description中的__slots__说明

编辑

as pointed out by @nneonneo, comments below about the double underscore are not correct becuase there are trailing underscores. The content is left in for historical reasons.

你所说的行为看起来很奇怪,我觉得很自然。@Owen询问了期望不同的代码是正确的,并感谢您发布了对Yelp/Testify的引用。该框架广泛使用了双下划线。在

Alex Martelli的SO answer on the double_underscore有助于阐明可能发生的事情,但最简单的答案是双下划线返回上面的结果,因为InheritingTest.__test__的点号符号通过常规的属性解析机制,但通过决定使用前导的双下划线,profice框架,保留了在类作用域访问它的权限,即使子类重写了它。在

从本质上讲,测试框架是神奇的野兽,__test__hear的使用在他们看来是恰当的。我查看了他们的文档,文档感觉很稀疏,所以使用__test__的根本感觉很危险(不管怎样,双下划线类型的信号都不会影响这个“class local”变量)。在

相关问题 更多 >