One of the automated unit tests for Python (unittest use instance)

Source: Internet
Author: User

1 Test Case TestCase

The most basic component of a software test is the test case , which Pyunit uses the TestCase class to represent the test case and requires that all classes used to perform the test must inherit from the class. The test code implemented by the TestCase subclass should be self-contained, which means that the test case can run either individually or with other test case constituent collections.

TestCase is considered a running entity of the test unit in the Pyunit test framework, where Python programmers can derive custom test procedures and methods (test units), use command and composite design patterns, Multiple testcase can also be combined into a collection of test cases. Pyunit test framework when running a test case, the setup (), Runtest (), and teardown () methods defined by the TestCase subclass are executed sequentially, and the simplest test case simply overrides the Runtest () method to execute the specific test code. As shown in Example 4:

Static_single.pyimport unittest# performs the test class Widgettestcase (UnitTest. TestCase):    def runtest (self):        widget = widget ()        self.assertequal (Widget.getsize (), (40, 40))

To construct an instance of the above Widgettestcase class in the Pyunit test framework, the constructor should be called without any arguments:

TestCase = Widgettestcase ()

A test case typically tests only one method in a software module, using the Overwrite Runtest () method to construct a test case called a static method in Pyunit, and if multiple methods in the same software module are to be tested, it is often necessary to construct multiple classes that perform the test. As shown in Example 5:

The test case for the Static_multi.pyimport unittest# Test GetSize () method is Class Widgetsizetestcase (unittest. TestCase):    def runtest (self):        widget = widget ()        self.assertequal (Widget.getsize (), (40, 40)) # Test Resize () Method of the Test case class Widgetresizetestcase (UnitTest. TestCase):    def runtest (self):        widget = widget ()        widget.resize (+)        self.assertequal ( Widget.getsize (), (100, 100))

Using static methods, Python programmers have to write a test class for each method to be tested (the class executes the test by overwriting the Runtest () method) and generate a test object in each test class. When writing test cases for the same software module, many times the object under test has the same initial state, so Python programmers using the above method have to do the same initialization for the object under test in each testing class, which is often a time-consuming and tedious task.

A better solution is to use the dynamic method provided by Pyunit, and only write a test class to complete the test of the entire software module, so that the initialization of the object can be done in the setup () method, and the release of the resources can be done in the teardown () method, As shown in Example 6:

Dynamic.pyimport unittest# performs the test class Widgettestcase (UnitTest. TestCase):    def setUp (self):        Self.widget = Widgets ()    def tearDown (self):        self.widget.dispose ()        Self.widget = None    def testsize (self):        self.assertequal (Self.widget.getSize (), (max))    def testresize ( Self):        self.widget.resize (self.assertequal) (        self.widget.getSize (), (100, 100))

The biggest benefit of adopting a dynamic approach is that the test class has a very good structure, and all the code used to test a software module can be implemented in the same class. The dynamic method no longer overwrites the Runtest () method, but instead writes multiple test methods for the test class ( which, by habit, usually begins with test), must give the name of the test method when creating an instance of the TestCase subclass. To indicate to the Pyunit test framework which method in the test class should be called when the test case is run:

Sizetestcase = Widgettestcase ("testsize") Resizetestcase = Widgettestcase ("Testresize")
2 Test Case Set Testsuite

Complete unit testing rarely executes only one test case, and developers often need to write multiple test cases to perform a more complete test of a software feature, which is called a set of test cases, represented by the Testsuite class in Pyunit.

After you have created instances of some testcase subclasses as test cases, the next step is to use the Testsuit class to organize them. The Pyunit test framework allows Python programmers to define a global function called Suite () in the Unit test code and use it as a portal for the entire unit test, pyunit by invoking it to complete the entire test process.

Def suite ():    suite = UnitTest. TestSuite ()    suite.addtest (Widgettestcase ("Testsize"))    Suite.addtest (Widgettestcase ("Testresize"    )) Return Suite

You can also define a subclass of Testsuite directly and complete the addition of all the test cases in its initialization method (__INIT__):

Class Widgettestsuite (UnitTest. TestSuite):    def __init__ (self):        unittest. Testsuite.__init__ (self, map (widgettestcase,                                              ("Testsize",                                               "Testresize")))

This only requires one instance of the class to be returned in the Suite () method:

Def suite ():    return Widgettestsuite ()

If all the test methods in the class used for the test are open with test, the Python programmer can even construct a testsuite with the Makesuite () method provided by the Pyunit module:

Def suite ():    return Unittest.makesuite (widgettestcase, "test")

In the Pyunit test framework, the Testsuite class can be seen as a container for the TestCase class to organize multiple test cases so that multiple test cases can be automatically completed in one test. In fact, Testsuite can contain testsuite in addition to TestCase, which can form a larger set of test cases:

Suite1 = mysuite1. Thetestsuite () Suite2 = Mysuite2. Thetestsuite () alltests = UnitTest. TestSuite ((suite1, Suite2))
3 Implementation Testing

There is only one final goal for writing test cases (TestCase) and organizing them into test case sets (TestSuite): To implement the tests and get the final results. Pyunit uses the Testrunner class as the basic execution environment for test cases to drive the entire unit test process. Instead of using the Testrunner class directly, the Python developer uses its subclass Texttestrunner to complete the test and display the test results as text:

Runner = UnitTest. Texttestrunner () Runner.run (suite)

Examples of using Testrunner to implement tests are shown in Example 7,

Text_runner.pyfrom Widget Import Widgetimport unittest# performs the test class Widgettestcase (UnitTest. TestCase):    def setUp (self):        Self.widget = Widgets ()    def tearDown (self):        self.widget.dispose ()        Self.widget = None    def testsize (self):        self.assertequal (Self.widget.getSize (), (max))    def testresize ( Self):        self.widget.resize (+)                self.assertequal (Self.widget.getSize (), (+))        # test if __name_ _ = = "__main__":    # Constructs test set    suite = UnitTest. TestSuite ()    suite.addtest (Widgettestcase ("Testsize"))    Suite.addtest (Widgettestcase ("Testresize"))        # Execute Test    runner = UnitTest. Texttestrunner ()    Runner.run (Suite)

The running result should look like this, indicating that 2 test cases were executed, and both passed the test:

.. ----------------------------------------------------------------------Ran 2 tests in 0.000sOK

If the data is modified and the error is simulated, the following results will be obtained:

. F==========================================fail:testresize (__main__. Widgettestcase)----------------------------------------------------------------------Traceback (most recent call Last):  File ' text_runner.py ', line testresize    self.assertequal (Self.widget.getSize (), (max.))  File "/usr/lib/python2.2/unittest.py", line 286, in Failunlessequal    raise Self.failureexception,/assertionerror: (+)! = (2)----------------------------------------------------------------------Ran, tests in 0.001sFAILED (Failures=1)

By default, Texttestrunner outputs the results to sys.stderr, but if you pass a file object to the constructor when you create an instance of the Texttestrunner class, the output is redirected to the file. Using the Texttestrunner class is a good choice when driving unit tests in a python interactive environment.

The Pyunit module defines a global method called Main, which makes it easy to turn a unit test module into a test script that can be run directly, and the main () method uses the Testloader class to search all the test methods contained in the module and automatically executes them. If a Python programmer is able to name all the test methods by convention (beginning with test), simply add the following lines of code to the end of the test module:

if __name__ = = "__main__":    Unittest.main ()

An example of using the main () method to implement the test is shown in Example 8:

Main_runner.pyfrom Widget Import Widgetimport unittest# performs the test class Widgettestcase (UnitTest. TestCase):    def setUp (self):        Self.widget = Widgets ()    def tearDown (self):        self.widget.dispose ()        Self.widget = None    def testsize (self):        self.assertequal (Self.widget.getSize (), (max))    def testresize ( Self):        self.widget.resize (+)        self.assertequal (Self.widget.getSize (), (+))   # test if __name_ _ = = "__main__":    Unittest.main ()

In order to make unit tests more affinity, a graphical interface test script unittestgui.py is provided in the Pyunit package, and after copying it to the current directory, you can execute the following command to launch the Test tool, on Main_ All test cases in the runner.py script are tested:

Python unittestgui.py Main_runner
Iv. Summary

Testing is the key to ensuring the quality of the software, and the new software development approach requires programmers to write test cases before writing the code, and to continually conduct unit tests during the software development process to minimize the emergence of bugs. Software Unit Testing is the cornerstone of the XP approach, and the test framework provides a uniform specification for the programmer to Unit test, and Python programmers can use Pyunit as the automated unit Testing framework in the software development process.

One of the automated unit tests for Python (unittest use instance)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.