python unittest:不能调用修饰测试


问题内容

我有一个相当大的测试套件,并且装饰了一些test_ *函数。现在我无法用./test.py MySqlTestCase.test_foo_doublepython3.2来称呼他们,他们抱怨说:ValueError: no such test method in <class '__main__.MySqlTestCase'>: result。我的装饰器代码如下所示:

def procedure_test(procedure_name, arguments_count, returns):

    '''Decorator for procedure tests, that simplifies testing whether procedure
    with given name is available, whether it has given number of arguments
    and returns given value.'''

    def decorator(test):
        def result(self):
            procedure = self.db.procedures[self.case(procedure_name)]
            self.assertEqual(len(procedure.arguments), arguments_count)
            self.assertEqual(procedure.returns, 
                             None if returns is None else self.case(returns))
            test(self, procedure)
        return result
    return decorator

和测试方法:

@procedure_test('foo_double', 0, 'integer')
def test_foo_double(self, procedure):
    self.assertEqual(procedure.database, self.db)
    self.assertEqual(procedure.sql, 'RETURN 2 * value')
    self.assertArguments(procedure, [('value', 'int4')])

问题答案:

我认为问题在于修饰的函数没有相同的名称,并且不满足被视为测试方法的模式。

使用functools.wrap装饰decorator应该可以解决您的问题。更多信息在这里