addCleanup的用例这里不介绍了,可以看我的另一编文章: python unittest框架中addCleanup函数详解
但如果有下面这种场景,还是会遗留大批理资源
在setUpClass注入各种先导资源,比如:
1、注入a
2、注入b
3、注入c
然后在teardownclass中清理
1、清理c
2、清理b
3、清理a
假设在注入b时出错了,那么在teardownclass中第一步就会出错
解决方法:
我们仿照addCleanup写一个这样的函数,如下
1、先在setupclass中定义一个列表
2、写SetupCleanup这样一个函数及doSetupCleanup函数,将列表倒序
3、将doSetupCleanup加入在tearDownClass中
代码如下:
@classmethod def setUpClass(cls): .... cls.setup_cleanup_list = [] ....
@classmethod def SetupCleanup(cls, func, *args, **kwargs): cls.setup_cleanup_list.append((func, args, kwargs)) @classmethod def doSetupcleanup(cls): try: for item in reversed(cls.setup_cleanup_list): function, args, kwargs = item for _ in range(3): try: function(*args, **kwargs) break except Exception as e: log.exception(e) finally: cls.setup_cleanup_list = []
@classmethod def tearDownClass(cls): cls.doSetupcleanup()