4

当我为框架创建测试时,我开始注意到以下模式:

class SomeTestCase(unittest.TestCase):

    def test_feat_true(self):
        _test_feat(self, True)

    def test_feat_false(self):
        _test_feat(self, False)

    def _test_feat(self, arg):
        pass    # test logic goes here

所以我想用元类以编程test_feat_*方式为这些类型的测试类创建方法。换句话说,对于每个带有签名的私有方法,我想要创建两个带有签名和_test_{featname}(self, arg)的顶级可发现方法。test_{featname}_true(self)test_{featname}_false(self)

我想出了类似的东西:

#!/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}_{[false,true]}(self)
            for suffix, arg in (('false', False), ('true', True)):
                testable_name = 'test{0}{1}'.format(testname, suffix)
                attrs[testable_name] = lambda self: meth(self, arg)

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


class TestCase(unittest.TestCase):

    __metaclass__ = TestMaker

    def _test_this(self, arg):
        print 'this: ' + str(arg)

    def _test_that(self, arg):
        print 'that: ' + str(arg)


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

我期望一些输出,例如:

this: False
this: True
that: False
that: True

但我得到的是:

$ ./test_meta.py
that: True
.that: True
.that: True
.that: True
.
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

看起来我缺少一些关闭规则。我该如何解决这个问题?有更好的方法吗?

谢谢,

编辑:固定。请参阅:片段

4

2 回答 2

5

实际上,这是一个关闭问题:

改变

attrs[testable_name] = lambda self: meth(self, arg)

attrs[testable_name] = lambda self,meth=meth,arg=arg: meth(self, arg)

通过使用默认值,arg内部 lambda 绑定到arg循环的每次迭代期间设置的默认值。如果没有默认值,则在循环的所有迭代完成后arg取最后一个值。arg(同样适用于meth)。

于 2011-03-03T03:12:01.770 回答
1

而不是走元类路线,我会考虑使用鼻子测试生成器来处理这类事情:

http://somethingaboutorange.com/mrl/projects/nose/1.0.0/writing_tests.html#test-generators

测试生成器的缺点是它们是特定于鼻子的功能,因此您需要在 stdlib 之外引入依赖项。好处是我认为它们更容易编写和理解。

于 2011-03-03T02:39:19.667 回答