设置失败时,如何清理Python Unitest?

发布于 2025-01-22 13:51:48 字数 426 浏览 2 评论 0原文

假设我有以下python Unittest:

import unittest

def Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Get some resources
        ...

        if error_occurred:
            assert(False)

    @classmethod
    def tearDownClass(cls):
        # release resources
        ...

如果设置级呼叫失败,则不会调用拆除式级别,因此资源永远不会发布。如果下一个测试需要资源,则在测试过程中是一个问题。

当SetupClass调用失败时,有没有办法进行清理?

Say I have the following Python UnitTest:

import unittest

def Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Get some resources
        ...

        if error_occurred:
            assert(False)

    @classmethod
    def tearDownClass(cls):
        # release resources
        ...

If the setUpClass call fails, the tearDownClass is not called so the resources are never released. This is a problem during a test run if the resources are required by the next test.

Is there a way to do a clean up when the setUpClass call fails?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

千寻… 2025-01-29 13:51:48

您可以在SetupClass方法中尝试一个尝试捕获,并直接调用除外的拆卸。

def setUpClass(cls):
     try: 
         # setUpClassInner()
     except Exception, e:
        cls.tearDownClass()
        raise # to still mark the test as failed.

要求外部资源运行您的UNITDEST是不好的做法。如果这些资源不可用,您需要测试代码的一部分是否有一个奇怪的错误,您将无法快速运行它。尝试将集成测试与单位测试区分开。

you can put a try catch in the setUpClass method and call directly the tearDown in the except.

def setUpClass(cls):
     try: 
         # setUpClassInner()
     except Exception, e:
        cls.tearDownClass()
        raise # to still mark the test as failed.

Requiring external resources to run your unittest is bad practice. If those resources are not available and you need to test part of your code for a strange bug you will not be able to quickly run it. Try to differentiate Integration tests from Unit Tests.

明明#如月 2025-01-29 13:51:48

您在其他地方保护资源的方式相同。 try-except

def setUpClass(cls):
    # ... acquire resources 
    try:
        # ... some call that may fail
    except SomeError, e:
        # cleanup here

清理可以像调用cls.teardownclass()中的中一样简单。 然后您可以调用servert(false)或任何您喜欢尽早退出测试的方法。

The same way you protect resources elsewhere. try-except:

def setUpClass(cls):
    # ... acquire resources 
    try:
        # ... some call that may fail
    except SomeError, e:
        # cleanup here

Cleanup could be as simple as calling cls.tearDownClass() in your except block. Then you can call assert(False) or whatever method you prefer to exit the test early.

禾厶谷欠 2025-01-29 13:51:48

我有一大堆测试助手功能,可以使用测试实例,并使用addCleanup清洁设置 /拆除线程,临时文件等,因此我也需要AddCleanup API来用于课堂级灯具。我重新完成了一些Unittest Docleanup功能来帮助我,并在课堂设置中使用模拟来修补AddCleanup()

import unittest
import logging
import mock

LOGGER = logging.getLogger(__name__)

class ClassCleanupTestCase(unittest.TestCase):
    _class_cleanups = []

    @classmethod
    def setUpClassWithCleanup(cls):
        def cleanup_fn():
            """Do some cleanup!"""
        # Do something that requires cleanup
        cls.addCleanup(cleanup_fn)

    @classmethod
    def addCleanupClass(cls, function, *args, **kwargs):
        cls._class_cleanups.append((function, args, kwargs))

    @classmethod
    def doCleanupsClass(cls):
        results = []
        while cls._class_cleanups:
            function, args, kwargs = cls._class_cleanups.pop()
            try:
                function(*args, **kwargs)
            except Exceptions:
                LOGGER.exception('Exception calling class cleanup function')
                results.append(sys.exc_info())

        if results:
            LOGGER.error('Exception(s) raised during class cleanup, re-raising '
                         'first exception.')
            raise results[0]

    @classmethod
    def setUpClass(cls):
        try:
            with mock.patch.object(cls, 'addCleanup') as cls_addCleanup:
                cls_addCleanup.side_effect = cls.addCleanupClass
                cls.setUpClassWithCleanup()
        except Exception:
            cls.doCleanupsClass()
            raise

    @classmethod
    def tearDownClass(cls):
        cls.doCleanupsClass()

I have a whole bunch of test helper functions that take a test instance and use addCleanup to cleanly setup / tear down threads, temp files etc, so I needed the addCleanup API to work for class level fixtures too. I reimplemented a bit of the unittest doCleanup functionality to help me, and used mock to patch addCleanup() during class setup

import unittest
import logging
import mock

LOGGER = logging.getLogger(__name__)

class ClassCleanupTestCase(unittest.TestCase):
    _class_cleanups = []

    @classmethod
    def setUpClassWithCleanup(cls):
        def cleanup_fn():
            """Do some cleanup!"""
        # Do something that requires cleanup
        cls.addCleanup(cleanup_fn)

    @classmethod
    def addCleanupClass(cls, function, *args, **kwargs):
        cls._class_cleanups.append((function, args, kwargs))

    @classmethod
    def doCleanupsClass(cls):
        results = []
        while cls._class_cleanups:
            function, args, kwargs = cls._class_cleanups.pop()
            try:
                function(*args, **kwargs)
            except Exceptions:
                LOGGER.exception('Exception calling class cleanup function')
                results.append(sys.exc_info())

        if results:
            LOGGER.error('Exception(s) raised during class cleanup, re-raising '
                         'first exception.')
            raise results[0]

    @classmethod
    def setUpClass(cls):
        try:
            with mock.patch.object(cls, 'addCleanup') as cls_addCleanup:
                cls_addCleanup.side_effect = cls.addCleanupClass
                cls.setUpClassWithCleanup()
        except Exception:
            cls.doCleanupsClass()
            raise

    @classmethod
    def tearDownClass(cls):
        cls.doCleanupsClass()
无所的.畏惧 2025-01-29 13:51:48

同时,addClassCleanup类方法已添加到unittest.testcase的确切目的: https://docs.python.org/3/library/library/unittest.html#unittest.test.testcase.testcase.addclasscleanup

In the meanwhile, addClassCleanup class method has been added to unittest.TestCase for exactly that purpose: https://docs.python.org/3/library/unittest.html#unittest.TestCase.addClassCleanup

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文