0

I want to set a conditional decorator to the setUpClass in python's unitest. I have tried the following (without a condition for now, to demonstrate the point):

import unittest

class conditional_decorator(object):
    def __call__(self, func):
        print ("Extra output")
        return func

class First(unittest.TestCase):

    @classmethod
    @conditional_decorator
    def setUpClass(cls):
        print ("setting up")

    def test1(self):
        pass


if __name__ == '__main__':
    unittest.main()

but I get an error

TypeError: object.__new__() takes no parameters

How can I solve this problem? Moreover, is there an easy way to 'combine' the two decorators for the setUpClass method?

Alex
  • 41,580
  • 88
  • 260
  • 469

2 Answers2

0

When you look at the traceback line it will tell you where your error occurred. My best guess, because I dont know the rest of your code, is that in the body of your code you left an extra parameter or added an extra comma.

As for two decorators that questioned was asked here:Can I combine two decorators into a single one in Python?

*Also remove Class from setUpClass because setUp is it's own function

Community
  • 1
  • 1
user1496368
  • 23
  • 1
  • 3
0

Just instantiate your conditional_decorator class first:

class First(unittest.TestCase):

    @classmethod
    @conditional_decorator() # Note the class is instantiated first.
    def setUpClass(cls):
    print ("setting up")

    def test1(self):
        pass

Or use a function instead of a class as your decorator:

def conditional_decorator(func):
    print ("Extra output")
    return func

class First(unittest.TestCase):

    @classmethod
    @conditional_decorator
    def setUpClass(cls):
        print ("setting up")

    def test1(self):
        pass


if __name__ == '__main__':
    unittest.main()

Now it works:

$ python my_test.py 
Extra output
setting up
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Maxim
  • 1,783
  • 2
  • 14
  • 24