python unittest:无法调用修饰的tes

2024-10-01 13:33:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个相当大的测试套件,我装饰了一些测试函数。现在我不能用./test.py MySqlTestCase.test_foo_double来调用它们,python3.2抱怨说:ValueError: no such test method in <class '__main__.MySqlTestCase'>: result。我的decorator代码如下所示:

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

试验方法:

^{pr2}$

Tags: nametestselfisdefcountdecoratorresult
3条回答

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

使用functools.wrap来修饰decorator应该可以解决您的问题。更多信息here。在

基于this帖子:

你可以这样做:

def decorator(test):
    def wrapper(self):
        # do something interesting
        test(self)
        # do something interesting
    wrapper.__name__ = test.__name__
    return wrapper

@functools.wrap方法相比,该解决方案有两个优点:

  • 不需要任何东西来导入
  • 创建decorator时不需要知道测试名称

由于这个解决方案的第二个特性,可以为许多测试创建装饰器。在

这有助于我:

from functools import wraps

。。。在

^{pr2}$

相关问题 更多 >