首页 > 解决方案 > When is unittest.addCleanup() executed?

问题描述

I have some doubt with respect to addCleanup() --

  1. When addCleanup() will be executed, only when there is a failure in any steps or it will be executed in normal scenarios too (when there is no failure)?
  2. If there is some failure in test, tearDown() will be called but if some steps in tearDown() fails, can we add addCleanup() in tearDown() to call some function which can do a proper cleanup?

标签: pythonpython-unittest

解决方案


添加一个要在 tearDown() 之后调用的函数以清理测试期间使用的资源。函数的调用顺序与添加顺序相反(LIFO)。

它们被添加时使用传递给 addCleanup() 的任何参数和关键字参数调用。如果 setUp() 失败,意味着 tearDown() 没有被调用,那么任何添加的清理函数仍然会被调用。

addCleanup (function, *args, **kwargs)

推荐阅读