1) doctest
Using doctest is similar to a command line attempt. It is easy to use as follows:
CopyCode The Code is as follows: def F (n ):
"""
>>> F (1)
1
>>> F (2)
2
"""
Print (N)
If _ name _ = '_ main __':
Import doctest
Doctest. testmod ()
It should be simple enough. Another method of doctest. testfile (filename) is to put the command line method in the file for testing.
2) unittest
Unittest has a long history and can be traced back to the 70 or 80 s of the last century. Similar implementations are available in C ++ and Java. The implementation in python is very simple.
The main implementation method of unittest in python is testcase and testsuite. The usage is still an example.Copy codeThe Code is as follows: From widget import widget
Import unittest
# Test execution class
Class widgettestcase (unittest. testcase ):
Def setup (Self ):
Self. widget = widget ()
Def teardown (Self ):
Self. widget. Dispose ()
Self. widget = none
Def testsize (Self ):
Self. assertequal (self. widget. getsize (), (40, 40 ))
Def testresize (Self ):
Self. widget. Resize (100,100)
Self. assertequal (self. widget. getsize (), (100,100 ))
# Test
If _ name _ = "_ main __":
# Construct a Test Set
Suite = unittest. testsuite ()
Suite. addtest (widgettestcase ("testsize "))
Suite. addtest (widgettestcase ("testresize "))
# Run the test
Runner = unittest. texttestrunner ()
Runner. Run (suite)
simply put, 1> construct a testcase (test case). Setup and teardown are responsible for preprocessing and aftercare. 2> construct a test set and add test cases. 3> test methods are required. In python, there are n multiple test functions, mainly including:
testcase. assert _ (expr [, MSG])
testcase. failunless (expr [, MSG])
testcase. asserttrue (expr [, MSG])
testcase. assertequal (first, second [, MSG])
testcase. failunlessequal (first, second [, MSG])
testcase. assertnotequal (first, second [, MSG])
testcase. failifequal (first, second [, MSG])
testcase. assertalmostequal (first, second [, places [, MSG])
testcase. failunlessalmostequal (first, second [, places [, MSG])
testcase. assertnotalmostequal (first, second [, places [, MSG])
testcase. failifalmostequal (first, second [, places [, MSG])
testcase. assertraises (exception, callable ,...)
testcase. failunlessraises (exception, callable ,...)
testcase. failif (expr [, MSG])
testcase. assertfalse (expr [, MSG])
testcase. fail ([MSG])