简体   繁体   English

如何在unittest中的setUpClass上设置条件修饰符?

[英]How can I set conditional decorators on setUpClass in unittest?

I want to set a conditional decorator to the setUpClass in python's unitest. 我想在python的unitest中为setUpClass设置一个条件装饰器。 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? 此外,有没有一种简单的方法可以为setUpClass方法“组合”两个装饰器?

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? 至于在这里被问到的两个装饰器: 我可以在Python中将两个装饰器组合成一个吗?

*Also remove Class from setUpClass because setUp is it's own function *还从setUpClass中删除Class,因为setUp是它自己的函数

Just instantiate your conditional_decorator class first: 只需首先实例化您的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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM