如果 setUpClass 抛出异常,如何使 python 单元测试失败 [英] How to fail a python unittest if the setUpClass throws exception

查看:34
本文介绍了如果 setUpClass 抛出异常,如何使 python 单元测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 python setUpClass 时遇到了一些问题.

I am having little trouble using the python setUpClass.

例如考虑以下情况

class MyTest(unittest.case.TestCase):

    @classmethod
    def setUpClass(cls):
        print "Test setup"
        try:
            1/0
        except:
            raise

    @classmethod
    def tearDownClass(cls):
        print "Test teardown"

几个问题

  1. 上面的代码是否是处理测试 setUpClass 异常的正确方法(通过引发它以便 python unittest 可以处理它),有 fail()、skip() 方法,但那些只能是由测试实例而不是测试类使用.

  1. Is the above code the right way to handle test setUpClass exceptions (by raising it so that the python unittest can take care of it), there are fail(), skip() methods, but those can only be used by test instances and not the test classes.

当出现setUpClass异常时,如何保证tearDownClass运行(unittest不运行,应该手动调用).

When there is a setUpClass exception, how can we ensure that tearDownClass runs (unittest doesn't run it, should we manualy call it).

推荐答案

你可以像 Jeff 指出的那样在异常上调用 tearDownClass,但你也可以实现 __del__(cls) 方法:

You can call tearDownClass on an exception as Jeff points it out, but you may also implements the __del__(cls) method :

import unittest

class MyTest(unittest.case.TestCase):

    @classmethod
    def setUpClass(cls):
        print "Test setup"
        try:
            1/0
        except:
            raise

    @classmethod
    def __del__(cls):
        print "Test teardown"

    def test_hello(cls):
        print "Hello"

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

将有以下输出:

Test setup
E
======================================================================
ERROR: setUpClass (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "my_test.py", line 8, in setUpClass
    1/0
ZeroDivisionError: integer division or modulo by zero

----------------------------------------------------------------------
Ran 0 tests in 0.000s

FAILED (errors=1)
Test teardown

注意:你应该知道 __del__ 方法将在程序执行结束时被调用,如果你有更多不止一个测试班.

Note : you should be aware that the __del__ method will be called at the end of the program execution, which is maybe not what you want if you have a more than one test class.

希望能帮到你

这篇关于如果 setUpClass 抛出异常,如何使 python 单元测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆