1) doctest
Using Doctest is a similar approach to command-line attempts, and the usage is simple, as follows
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 easy enough, and there's another way doctest.testfile (filename) is to put the command line in the file for testing.
2) UnitTest
UnitTest has a long history, the earliest can be traced back to the 780 's, C++,java also have similar implementations, Python implementation is very simple.
The main way UnitTest is implemented in Python is testcase,testsuite. Use or an example to get started.
The code is 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 Sets
Suite = UnitTest. TestSuite ()
Suite.addtest (Widgettestcase ("Testsize"))
Suite.addtest (Widgettestcase ("Testresize"))
# Perform Tests
Runner = UnitTest. Texttestrunner ()
Runner.run (Suite)
Simply put,,1> constructs testcase (test cases), where setup and teardown are responsible for preprocessing and aftercare. 2> constructs the test set, adds the use case 3> executes the test to explain is the test method, in Python has n many test function, mainly has:
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])