Next to a docleanups note, the introduction of another very useful function: Addcleanup
Or the usual, look at the Official document description:
Addcleanup (function, *args, ** version 2.7.
Chinese explanation:
Add a cleanup method after the teardown () method is executed for each test case, and the added function is executed in last in, first out (LIFO) order, plus parameters.
Of course, if the setup () method fails, the Teardown () method is not executed and the function added in Addcleanup () is not executed naturally.
In fact, in the actual use, will not write multiple functions in.
So what is the application scenario?
The scenario is this: the normal test case is that, after you create the resource, you need to delete the resource in the use case, or to clean the resource in teardown, it is quite inconvenient to write the function directly in the use case after Addcleanup, after teardown use case, Addcleanup will be called again to remove resources, reduce the amount of code and omit deletion
Look at a simple example.
#Coding:utf-8" "Created on August 31, 2016 @author:huzq" "ImportUnitTestclassmy (unittest. TestCase):defdelf (self,a):PrintadefsetUp (self):Print "setUp" deftest_1 (self):" "i dont konw" "a='1111' Print "test_1"cleanups= ('bbbbb',) Self.addcleanup (self.delf, cleanups [0])defTearDown (self):Print 'This is TearDown' #def docleanups (self): #print "This is cleanups" deftest_2 (self):Print "test_2"@classmethoddefTeardownclass (CLS):Print "teardown ...." if __name__=="__main__": Test=UnitTest. TestSuite () Test.addtest (My ('test_1')) Test.addtest (My ('test_2')) Runner=UnitTest. Texttestrunner () runner.run (test)
The results of the operation are as follows:
.. ----------------------------------------------------------------------in are tearDownbbbbb is teardownteardown ....
Look at the red part, the effect of addcleanup.
I am fortunate to see a lot of foreigners open-source framework, in the code to use a large number of addcleanup functions. We can learn from
addcleanup function in Python unittest framework