1) doctest
Using Doctest is a similar way to command-line attempts, and the usage is simple, as follows
Copy Code code 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, and there is another way to doctest.testfile (filename), which is to put the command line in the file for testing.
2) UnitTest
UnitTest has a long history, the earliest dating back to the 780 's, C++,java has a similar implementation, Python implementation is very simple.
The main way to implement UnitTest in Python is testcase,testsuite. Use is still an example of starting.
Copy Code code as follows:
From widget Import widget
Import UnitTest
# classes that perform tests
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 Test Set
Suite = UnitTest. TestSuite ()
Suite.addtest (Widgettestcase ("Testsize"))
Suite.addtest (Widgettestcase ("Testresize"))
# Perform Tests
Runner = UnitTest. Texttestrunner ()
Runner.run (Suite)
Simply say,1> constructs testcase (test case), in which the setup and teardown are responsible for preprocessing and aftercare work. 2> constructs a test set, adds a use case 3> test methods are required to perform tests, and in Python there are more than n test functions, mainly:
Testcase.assert_ (expr[, MSG])
Testcase.failunless (expr[, MSG])
Testcase.asserttrue (expr[, MSG])
Testcase.assertequal (A, second[, MSG])
Testcase.failunlessequal (A, second[, MSG])
Testcase.assertnotequal (A, second[, MSG])
Testcase.failifequal (A, second[, MSG])
Testcase.assertalmostequal (A, second[, places[, MSG])
Testcase.failunlessalmostequal (A, second[, places[, MSG])
Testcase.assertnotalmostequal (A, second[, places[, MSG])
Testcase.failifalmostequal (A, second[, places[, MSG])
Testcase.assertraises (Exception, callable, ...)
Testcase.failunlessraises (Exception, callable, ...)
Testcase.failif (expr[, MSG])
Testcase.assertfalse (expr[, MSG])
Testcase.fail ([MSG])