设置失败时,如何清理Python Unitest?
假设我有以下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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在SetupClass方法中尝试一个尝试捕获,并直接调用除外的拆卸。
要求外部资源运行您的UNITDEST是不好的做法。如果这些资源不可用,您需要测试代码的一部分是否有一个奇怪的错误,您将无法快速运行它。尝试将集成测试与单位测试区分开。
you can put a try catch in the setUpClass method and call directly the tearDown in the except.
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.
您在其他地方保护资源的方式相同。
try-except
:清理可以像调用
cls.teardownclass()
中的中一样简单。 然后您可以调用servert(false)
或任何您喜欢尽早退出测试的方法。The same way you protect resources elsewhere.
try-except
:Cleanup could be as simple as calling
cls.tearDownClass()
in yourexcept
block. Then you can callassert(False)
or whatever method you prefer to exit the test early.我有一大堆测试助手功能,可以使用测试实例,并使用addCleanup清洁设置 /拆除线程,临时文件等,因此我也需要AddCleanup API来用于课堂级灯具。我重新完成了一些Unittest Docleanup功能来帮助我,并在课堂设置中使用模拟来修补AddCleanup()
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
同时,
addClassCleanup
类方法已添加到unittest.testcase
的确切目的: https://docs.python.org/3/library/library/unittest.html#unittest.test.testcase.testcase.addclasscleanupIn the meanwhile,
addClassCleanup
class method has been added tounittest.TestCase
for exactly that purpose: https://docs.python.org/3/library/unittest.html#unittest.TestCase.addClassCleanup