__test__ =假魔法属性如何用于测试发现

Ant*_*ile 12 python

所以我试图实现类似于单元测试框架如何执行以下操作:

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
Run Code Online (Sandbox Code Playgroud)

我觉得奇怪的一件事:

# >> InheritingTest.__test__
# False
Run Code Online (Sandbox Code Playgroud)

这将表明,我认为这是不使用元类设置 __test__True建筑的类型.

我尝试了通过python库,find . -name "*.py" | xargs grep '__test__'但似乎没有发现任何与此相关的内容.

我解决这个问题的"猜测"方法是执行以下操作:

def is_class_tested(cls):
    return cls.__dict__.get('__test__', True)
Run Code Online (Sandbox Code Playgroud)

然而,这对我来说感觉很脆弱......有没有更清洁/更好的方法来做到这一点在所有情况下都有效?班级是否有可能没有__dict__财产?

nne*_*neo 3

您正在使用的库 Testify 在testify/test_discovery.py第 140 行左右执行以下操作:

    # 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__)):
Run Code Online (Sandbox Code Playgroud)

因此,换句话说,它正在以稍微更详细的方式执行您的“猜测”方法的作用:它直接测试__test__类中的存在和值__dict__