Search code examples
pythonpython-unittestpython-decoratorsparameterized-unit-testnose-parameterized

Apply different decorators based on a condition


I'm using unittest and nose-parametarized, and want to apply different decorators to a test based on a condition.

I have a test and I want to skip unittest.skip the test or execute it @parameterized.expand(args)based on the arguments passed to args.

I think I need to have another decorator which applies proper decorator to the test , but now sure how.

pseudo code could be something like this :

@validate_data(args)
    def test(args):
    ...

where @validate_data(args) is a decorator which applies unittest.skip if args ==None or @parameterized.expand(args)otherwise

Any comments/suggestions is appreciated.


Solution

  • A decorator can also be called as a function. @decorator is equivalent to decorator(func) and @decorator(args) to decorator(args)(func). So you could return the value of those function returns conditionally in your decorator. Here is an example below:

    def parameterized_or_skip(args=None):
        if args:
            return parameterized.expand(args)
        return unittest.skip(reason='No args')
    
    ...
    
    @parameterized_or_skip(args)
    def my_testcase(self, a, b):
        pass