Python unit test unittest instance details, pythonunittest

Source: Internet
Author: User

Python unit test unittest instance details, pythonunittest

This example describes how to use unittest in python unit test. Share it with you for your reference. The specific analysis is as follows:

Unit testing, as a developer of any language, should be necessary, because when you come back to debug your complex program several months later, it is actually a very bad thing. Although you will be familiar with the content soon, modification and debugging will be a pain point. If you have problems after modifying the code, unit Testing can help us quickly and accurately locate the problem and the problematic modules and units. So this is a pleasant thing, because we know that other modifications or unmodified parts still work normally, the only problem we have at present is to solve the problem "guy ". So work will start easily and soon, because you already know a lot of information.
 
Unit Testing is naturally to test the function, the smallest testable module in the program. Because the unit testing object is a function, that is, you must have output results for the tested object, even abnormal output must be output so that the unit test module can capture the returned value and compare it with the expected value to determine whether the test is successful or not.
 
There are two ways to load unit tests: One is through unittest. main () is used to start the unit test module. One is to add it to the testsuite set and load all the tested objects, while testsuit stores the unit test cases, the usage of the two methods is listed below.

1.1 functions in the test module:

Tested modules:

#!/usr/bin/env python #encoding: utf-8 def sum( x, y):     return x+y def sub( x, y):     return x-y

Unit test module:

#! /Usr/bin/env python # encoding: UTF-8 import unittest import myclass mytest (unittest. testCase): # initialization work def setUp (self): pass # exit cleaning work def tearDown (self): pass # specific test cases, be sure to start with test def testsum (self): self. assertEqual (myclass. sum (1, 2), 2, 'test sum fail ') def testsub (self): self. assertEqual (myclass. sub (2, 1), 1, 'test sub fail ') if _ name _ =' _ main _ ': unittest. main ()

Test result: [F indicates a fail, and the vertices before F indicate a pass. If E exists, the program itself is abnormal]

.F======================================================================FAIL: testsum (__main__.mytest)----------------------------------------------------------------------Traceback (most recent call last): File "C:\Users\xiaowu\workspace\mypython\unitTest.py", line 19, in testsum  self.assertEqual(myclass.sum(1, 2), 2, 'test sum fail')AssertionError: test sum fail----------------------------------------------------------------------Ran 2 tests in 0.001s FAILED (failures=1)

1.2 functions in the test module class:

Tested modules:

#!/usr/bin/env python#encoding: utf-8class myclass:  def __init__(self):    pass  def sum(self, x, y):    return x+y  def sub(self, x, y):    return x-y

Unit test module:

#! /Usr/bin/env python # encoding: UTF-8 import unittest import myclass mytest (unittest. testCase): # initialization work def setUp (self): self. tclass = myclass. myclass () # instantiate the class in the tested Module # exit the cleaning work def tearDown (self): pass # the specific test case must start with test def testsum (self ): self. assertEqual (self. tclass. sum (1, 2), 3) if _ name _ = '_ main _': unittest. main ()

Running result:

.----------------------------------------------------------------------Ran 1 test in 0.000sOK

In this way, you can use the-v parameter to obtain more test results when executing a single test file. For example, mytest. py-v
 
2. Load the test suite

Well, before using the test suite for unit testing, I 'd like to take a look at the content of the unittest module and the approximate running mode. The unit test suite will be developed based on various situations.

First, check the members of The unittest module!

>>import unittest >>dir(unittest) ['FunctionTestCase', 'TestCase', 'TestLoader', 'TestProgram', 'TestResult', 'Tes tSuite', 'TextTestRunner', '_CmpToKey', '_TextTestResult', '_WritelnDecorator', '__all__', '__author__', '__builtins__', '__doc__', '__email__', '__file__', '__ metaclass__', '__name__', '__package__', '__unittest', '__version__', '_makeLoad er', '_strclass', 'defaultTestLoader', 'findTestCases', 'getTestCaseNames', 'mai n', 'makeSuite', 'os', 'sys', 'time', 'traceback', 'types']

We can see that there are not many members, including:

['FunctionTestCase', 'TestCase', 'TestLoader', 'TestProgram', 'TestResult', 'TestSuite','TextTestRunner', '_CmpToKey', '_TextTestResult', '_WritelnDecorator', 'defaultTestLoader','findTestCases', 'getTestCaseNames', 'main', 'makeSuite']

Okay. Let's take a look at what it is.

>>memblist = ['FunctionTestCase', 'TestCase', 'TestLoader', 'TestProgram', 'TestResult',\ 'TestSuite','TextTestRunner', 'defaultTestLoader','findTestCases', 'getTestCaseNames', \ 'main', 'makeSuite'] >>for memb in memblist: .. cur = getattr(unittest, memb) .. print help(cur)

'Functiontestase': function test case. A function is used as a parameter to return a testcase instance. The optional parameters include the set-up and tear-down methods.
'Testbase': basic class of all test cases. A test case instance is returned when the name of a test method is given.
'Testloader ': Test Case loader, which includes multiple methods for loading test cases. Returns a test suite
LoadTestsFromModule (self, module) -- obtains the test case suite Based on the given module instance.
LoadTestsFromName (self, name, module = None)
-- Obtain the test case suite Based on the given string. The string can be the module name, test class name, test method name in the test class, or an instance object that can be called
This instance object returns a test case or test suite
LoadTestsFromNames (self, names, module = None) -- same as the above function, only accept the string list
LoadTestsFromTestCase (self, testCaseClass) -- obtains all test methods based on the given test class and returns a test suite
'Testproject': Call Method for unit test on the command line. It is used to execute a test case. In fact, the unittest. main () method executes this command,
In this instance, the currently executed instance is loaded as the test object by default,
Prototype: _ init _ (self, module = '_ main _', defaultTest = None, argv = None, testRunner = xx, testLoader = xx)
Module = '_ main _' indicates loading itself by default.
'Testresult': The test case result is saved as an instance, which is usually called by the test framework.
'Testsuite ': Organizes test case instances, supports adding and deleting test cases, and is finally passed to testRunner for testing and execution.
'Texttestrunner ': The instance for executing the test case. Text indicates that the test result is displayed in Text format. Display the test name, that is, the completed test result. The-v parameter is added when the unit test script is executed.
'Defaulttestloader ': TestLoader.
'Findtestcases', 'gettestcasenames ': No need to explain the two.
'Main': TestProgram.
'Makesuite ': generally called by the unit test framework, used to produce instances of testsuite objects.
 
So far, we know. In fact, the logic of the unit test framework has come out. Three steps: Step 1: testloader obtains the corresponding test case based on the input parameters, that is, corresponding to the specific test method,
Then, makesuite assembles all test cases into testsuite, and finally passes testsiute to testrunner for execution.
The unittest. main () is actually unittest. the testprom method is executed in the preceding three steps. In the first step, the input parameter is its own module _ main __;
In step 2, extract the test methods from all the test classes in the module and generate the test suite. Then, pass the test suite to testrunner for specific testing.

Finally, a complete unit test organization code is provided. Put the code in the same directory of the unit test case file and execute the script to execute all the test case files.

[The test case file must start with test, for example, testxxx. py. Of course, this file is a unit test file]

#! /Usr/bin/env python # encoding: UTF-8 # This code is derived from pythonimport unittestimport myclassimport reimport osimport sysdef testAllinCurrent (): path = OS. path. abspath (OS. path. dirname (sys. argv [0]) files = OS. listdir (path) test = re. compile ("test \. py {1} quot;, re. IGNORECASE) files = filter (test. search, files) filenameToModuleName = lambda f: OS. path. splitext (f) [0] moduleNames = map (filenameToModuleName, files) modules = map (_ import __, moduleNames) load = unittest. defaultTestLoader. loadTestsFromModule return unittest. testSuite (map (load, modules) if _ name _ = "_ main _": unittest. main (defaultTest = "regressionTest ")

I hope this article will help you with Python programming.

Related Article

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.