Usage of the python unittest Module
Source code to be tested:Widget. py
#! /Usr/bin/ENV python </P> <p> class Widget: <br/> def _ init _ (self, size = (40, 40 )): <br/> self. _ size = size </P> <p> def getsize (Self): <br/> return self. _ size </P> <p> def resize (self, width, height): <br/> If width = 0 or height <0: <br/> raise valueerror, "illegal size" <br/> self. _ size = (width, height) </P> <p> def dispose (Self): <br/> pass
TestCodeClass:Widget_unittest.py
#! /Usr/bin/ENV python </P> <p> Import sys <br/> Import unittest <br/> from widget import widget </P> <p> class widgettestcase (unittest. testcase): <br/> def setup (Self): <br/> self. widget = widget () </P> <p> def teardown (Self): <br/> self. widget = none </P> <p> def testsize (Self): <br/> self. assertequal (self. widget. getsize (), (40, 40) </P> <p> def testresize (Self): <br/> self. widget. resize (20, 30) <br/> self. asser Tequal (self. widget. getsize (), (20, 30) </P> <p> def Suite (): <br/> suite = unittest. testsuite () <br/> suite. addtest (widgettestcase ("testsize") <br/> suite. addtest (widgettestcase ("testresize") <br/> return suite </P> <p> If _ name _ = "_ main __": <br/> unittest. texttestrunner (). run (Suite () <br/> # If you use ide To execute test script in an external console, <br/> # uncomment following code line. <br /># While true <br/> # If raw_input ("Type Y or Y to close! ") In (" Y "," Y "): SYS. Exit (0)
Running result:Python widget_unittest.py
[Work@db-testing-com06-vm3.db01.baidu.com test] $ Python widget_unittest.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000 s
OK
Dynamic methods no longer overwrite the runtest () method, but write multiple test methods for the test class (according to habits, these methods usually start with test ), when creating an instance of the testcase subclass, you must provide the name of the test method to indicate which method of the test class should be called when running the test case for the pyunit test framework.
If all the test methods of the class used for testing are enabled as testProgramYou can even use the makesuite () method provided by the pyunit module to construct a testsuite:
Def Suite ():
Return unittest. makesuite (widgettestcase, "test ")