nose,unittest.TestCase和 metaclass:未发现自动生成的 test_* 方法

14 投票
1 回答
2097 浏览
提问于 2025-04-16 12:53

这是一个关于 unittest 和元类:自动生成 test_* 方法 的后续问题:

对于这个(修正过的)unittest.TestCase 布局:

#!/usr/bin/env python

import unittest


class TestMaker(type):

    def __new__(cls, name, bases, attrs):
        callables = dict([
            (meth_name, meth) for (meth_name, meth) in attrs.items() if
            meth_name.startswith('_test')
        ])

        for meth_name, meth in callables.items():
            assert callable(meth)
            _, _, testname = meth_name.partition('_test')

            # inject methods: test{testname}_v4,6(self)
            for suffix, arg in (('_false', False), ('_true', True)):
                testable_name = 'test{0}{1}'.format(testname, suffix)
                testable = lambda self, func=meth, arg=arg: func(self, arg)
                attrs[testable_name] = testable

        return type.__new__(cls, name, bases, attrs)


class TestCase(unittest.TestCase):

    __metaclass__ = TestMaker

    def test_normal(self):
        print 'Hello from ' + self.id()

    def _test_this(self, arg):
        print '[{0}] this: {1}'.format(self.id(), str(arg))

    def _test_that(self, arg):
        print '[{0}] that: {1}'.format(self.id(), str(arg))


if __name__ == '__main__':
    unittest.main()

这个布局在 stdlib 的框架下是可以正常工作的。预期的输出和实际输出如下:

C:\Users\santa4nt\Desktop>C:\Python27\python.exe test_meta.py
Hello from __main__.TestCase.test_normal
.[__main__.TestCase.test_that_false] that: False
.[__main__.TestCase.test_that_true] that: True
.[__main__.TestCase.test_this_false] this: False
.[__main__.TestCase.test_this_true] this: True
.
----------------------------------------------------------------------
Ran 5 tests in 0.015s

OK

但是,因为我实际上使用的是 nose,所以这个方法似乎不适用。我的输出结果是:

C:\Users\santa4nt\Desktop>C:\Python27\python.exe C:\Python27\Scripts\nosetests test_meta.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

简而言之,元类生成的 test_* 方法没有在 nose 中注册。有没有人能帮我解释一下这个问题?

谢谢,

1 个回答

19

经过一番调查,我发现Python的标准库中的unittest和nose库的加载器及选择器的源代码,nose库会覆盖unittest.TestLoader.getTestCaseNames,使用它自己的一套选择器(带有插件点)。

nose的选择器会查看方法的method.__name__,来匹配特定的正则表达式、黑白名单以及插件的决策。

在我的情况下,动态生成的函数的testable.__name__ == '<lambda>',这并不符合nose选择器的任何标准。

要解决这个问题,

        # inject methods: test{testname}_v4,6(self)
        for suffix, arg in (('_false', False), ('_true', True)):
            testable_name = 'test{0}{1}'.format(testname, suffix)
            testable = lambda self, arg=arg: meth(self, arg)
            testable.__name__ = testable_name    # XXX: the fix
            attrs[testable_name] = testable

结果果然是:

(sandbox-2.7)bash-3.2$ nosetests -vv 
test_normal (test_testgen.TestCase) ... ok
test_that_false (test_testgen.TestCase) ... ok
test_that_true (test_testgen.TestCase) ... ok
test_this_false (test_testgen.TestCase) ... ok
test_this_true (test_testgen.TestCase) ... ok

----------------------------------------------------------------------
Ran 5 tests in 0.005s

OK

撰写回答