如何在setUpClass失败时清理Python UnitTest?

rhfm7lfc  于 2024-01-05  发布在  Python
关注(0)|答案(4)|浏览(178)

假设我有以下Python UnitTest:

  1. import unittest
  2. def Test(unittest.TestCase):
  3. @classmethod
  4. def setUpClass(cls):
  5. # Get some resources
  6. ...
  7. if error_occurred:
  8. assert(False)
  9. @classmethod
  10. def tearDownClass(cls):
  11. # release resources
  12. ...

字符串
如果setUpClass调用失败,则不会调用tearDownClass,因此资源永远不会释放。如果下一个测试需要资源,则在测试运行期间会出现问题。
当setUpClass调用失败时,有没有一种方法可以进行清理?

nqwrtyyt

nqwrtyyt1#

你可以在setUpClass方法中放置一个try catch,并直接调用except中的tearDown。

  1. def setUpClass(cls):
  2. try:
  3. # setUpClassInner()
  4. except Exception, e:
  5. cls.tearDownClass()
  6. raise # to still mark the test as failed.

字符串
需要外部资源来运行单元测试是不好的做法。如果这些资源不可用,而你需要测试代码的一部分,以发现奇怪的错误,你将无法快速运行它。尝试区分集成测试和单元测试。

tyky79it

tyky79it2#

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

  1. def setUpClass(cls):
  2. # ... acquire resources
  3. try:
  4. # ... some call that may fail
  5. except SomeError, e:
  6. # cleanup here

字符串
测试可以简单到在except块中调用cls.tearDownClass()。* 然后 * 您可以调用assert(False)或任何您喜欢的方法来提前退出测试。

isr3a4wc

isr3a4wc3#

我有一大堆测试助手函数,它们接受一个测试示例,并使用addfocus来干净地设置/拆除线程、临时文件等,所以我也需要addfocus API来为类级别的fixtures工作。

  1. import unittest
  2. import logging
  3. import mock
  4. LOGGER = logging.getLogger(__name__)
  5. class ClassCleanupTestCase(unittest.TestCase):
  6. _class_cleanups = []
  7. @classmethod
  8. def setUpClassWithCleanup(cls):
  9. def cleanup_fn():
  10. """Do some cleanup!"""
  11. # Do something that requires cleanup
  12. cls.addCleanup(cleanup_fn)
  13. @classmethod
  14. def addCleanupClass(cls, function, *args, **kwargs):
  15. cls._class_cleanups.append((function, args, kwargs))
  16. @classmethod
  17. def doCleanupsClass(cls):
  18. results = []
  19. while cls._class_cleanups:
  20. function, args, kwargs = cls._class_cleanups.pop()
  21. try:
  22. function(*args, **kwargs)
  23. except Exceptions:
  24. LOGGER.exception('Exception calling class cleanup function')
  25. results.append(sys.exc_info())
  26. if results:
  27. LOGGER.error('Exception(s) raised during class cleanup, re-raising '
  28. 'first exception.')
  29. raise results[0]
  30. @classmethod
  31. def setUpClass(cls):
  32. try:
  33. with mock.patch.object(cls, 'addCleanup') as cls_addCleanup:
  34. cls_addCleanup.side_effect = cls.addCleanupClass
  35. cls.setUpClassWithCleanup()
  36. except Exception:
  37. cls.doCleanupsClass()
  38. raise
  39. @classmethod
  40. def tearDownClass(cls):
  41. cls.doCleanupsClass()

字符串

展开查看全部
xv8emn3q

xv8emn3q4#

与此同时,addClassCleanup类方法已被添加到unittest.TestCase中,正是为了达到这个目的:https://docs.python.org/3/library/unittest.html#unittest.TestCase.addClassCleanup

相关问题