【发布时间】:2011-07-07 18:01:52
【问题描述】:
当我为框架创建测试时,我开始注意到以下模式:
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
看起来我缺少一些关闭规则。我该如何解决这个问题?有更好的方法吗?
谢谢,
编辑:已修复。请参阅:the snippet。
【问题讨论】:
标签: python unit-testing metaclass