python unittest: can't call decorated test

前端 未结 4 973
广开言路
广开言路 2021-01-12 15:43

I have a pretty large test suite and I decorated some of the test_* functions. Now I can\'t call them by ./test.py MySqlTestCase.test_foo_double, python3.2 comp

相关标签:
4条回答
  • 2021-01-12 16:20

    I think the problem is that the decorated function doesn't have the same name and, also, it doesn't satisfy the pattern to be considered a test method.

    Using functools.wrap to decorate decorator should fix your problem. More information here.

    0 讨论(0)
  • 2021-01-12 16:22

    This is a simple way of solving this issue.

    from functools import wraps
    
    def your_decorator(func):
        @wraps(func)
        def wrapper(self):
            #Do Whatever
            return func(self)
        return wrapper
    
    class YourTest(APITestCase):
        @your_decorator
        def example(self):
            #Do your thing
    
    0 讨论(0)
  • 2021-01-12 16:23

    Based on this post:

    You can do it this way:

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

    This solution has two advantages over method with @functools.wrap:

    • doesn't need anything to import
    • doesn't need to know test name when decorator is created

    Thanks to the second feature of this solution, it is possible to create decorators for many tests.

    0 讨论(0)
  • 2021-01-12 16:30

    This help me:

    from functools import wraps
    

    ...

    @wraps(procedure_name)
    def decorator(test):
    
    0 讨论(0)
提交回复
热议问题