我想在python的unitest中为setUpClass
设置条件装饰器。我已尝试过以下内容(暂时没有条件,以证明这一点):
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()
但是我收到了错误
TypeError: object.__new__() takes no parameters
我该如何解决这个问题?此外,有一种简单的方法可以“组合”setUpClass
方法的两个装饰器吗?
答案 0 :(得分:0)
当您查看追溯线时,它会告诉您错误发生的位置。我最好的猜测,因为我不知道你的其余代码,是你的代码正文中你留下了一个额外的参数或添加了一个额外的逗号。
至于在这里被问到的两个装饰者:Can I combine two decorators into a single one in Python?
*同时从setUpClass中删除Class,因为setUp是它自己的函数
答案 1 :(得分:0)
首先实例化您的conditional_decorator
课程:
class First(unittest.TestCase):
@classmethod
@conditional_decorator() # Note the class is instantiated first.
def setUpClass(cls):
print ("setting up")
def test1(self):
pass
或者使用函数而不是类作为装饰器:
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()
现在可行:
$ python my_test.py
Extra output
setting up
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK