如何在setUpClass中使python单元测试失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14768135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:22:47  来源:igfitidea点击:

How to fail a python unittest in setUpClass?

pythonunit-testingpython-2.7

提问by Alex

I am doing some unittests with python and some pre-test checks in setUpClass. How can I throw a unitest-failwithin the setUpClass, as the following simple example:

我正在用 python 进行一些单元测试,并在setUpClass. 我如何可以抛出一个unitest-fail内的setUpClass,如下面的简单的例子:

class MyTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):    
        unittest.TestCase.fail("Test")

    def test1(self):
        pass

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

gives the error TypeError: unbound method fail() must be called with TestCase instance as first argument (got str instance instead).

给出错误TypeError: unbound method fail() must be called with TestCase instance as first argument (got str instance instead)

I understand the error I get as fail is a instance method, and I don't have an instance of MyClassyet. Using an instance on-the-fly like

我明白我得到的错误是一个实例方法,我还没有一个实例MyClass。即时使用实例,例如

unittest.TestCase().fail("Test")

also does not work, as unittest.TestCaseitself has no tests. Any ideas how to fail all tests in MyClass, when some condition in setUpClassis not met?

也不起作用,因为unittest.TestCase它本身没有测试。MyClasssetUpClass不满足中的某些条件时,任何想法如何使 中的所有测试失败?

Followup question: Is there a way to see the tests in setUpClass?

后续问题:有没有办法在 中查看测试setUpClass

采纳答案by Raufio

self.fail("test")put into your setUp instance method fails all the tests

self.fail("test")放入您的 setUp 实例方法未通过所有测试

I think the easiest way to do this at the class level is to make a class variable so something like:

我认为在类级别执行此操作的最简单方法是创建一个类变量,例如:

@classmethod
def setUpClass(cls):
   cls.flag = False

def setUp(self):
   if self.flag:
       self.fail("conditions not met")

Hope this is what you want.

希望这是你想要的。

回答by Greg

Using a simple assert should work

使用简单的断言应该可以工作

assert False, "I mean for this to fail"