"Python" unittest-3

Source: Internet
Author: User
Tags shuffle

One, @unittest. Skip ("Skipping this case") # unconditionally ignore the test method

Second, @unittest. SkipIf (A > 5, "condition is not satisfied!") #如果变量a > 5, the test method is ignored

Third, @unittest. skipunless ("Linux"), "requires Linux") # Ignore this test method unless the platform that executes the test case is a Linux platform. Win32 is Windows

Iv. Test Set

1. UnitTest itself includes the following methods:

[' Functiontestcase ', ' TestCase ', ' testloader ', ' testprogram ', ' TestResult ',
' TestSuite ', ' texttestrunner ', ' _cmptokey ', ' _texttestresult ', ' _writelndecorator ',
' Defaulttestloader ', ' findtestcases ', ' gettestcasenames ', ' main ', ' Makesuite ']

2. Meaning of each method

' Functiontestcase ': A function test case, which gives a function as an argument, returns a TestCase instance, and an optional parameter has a Set-up,tear-down method
' TestCase ': The basic class for all test cases, give the name of a test method, and return a test case instance
' Testloader ': The test case loader, which includes multiple methods for loading test cases. Return a test suite
 Loadtestsfrommodule (self, module)--Gets the test case suite based on the given module instance
Loadtestsfromname (self, name, Module=none)
--To get a suite of test cases based on a given string, a string can be a module name, a test class name, a test method name in a test class, or a callable instance object
This instance object returns a test case or a test suite
Loadtestsfromnames (self, names, Module=none)--the same function as above, except that a list of strings is accepted
Loadtestsfromtestcase (self, testcaseclass)--gets all of the test methods and returns a test suite based on the given test class
' Testprogram ': The command line is called by the unit test to execute a test case. In fact, the Unittest.main () method executes this command,
While this class instance is loaded by default as the test object that is currently executing,
Prototypes for __init__ (self, module= ' __main__ ', Defaulttest=none, Argv=none, Testrunner=xx, testloader=xx)
where module= ' __main__ ' is the default load itself
' TestResult ': The result of a test case saves an instance, usually with a test framework call
' TestSuite ': Organizes instances of test cases, supports the addition and deletion of test cases, and ultimately passes them to Testrunner for test execution
' Texttestrunner ': an instance of the test case execution, where text means to display the test results in textual form. Displays the test name, which is the completed test result, and adds the-v parameter when the unit test script is executed
' Defaulttestloader ': Actually, it's testloader.
' findtestcases ', ' Gettestcasenames ': This 2 doesn't have to be explained.
' main ': Actually, it's testprogram.
' Makesuite ': Typically called by the Unit Test framework to produce an instance of a Testsuite object

V. SUMMARY of UNIT tests

At this point, we know. In fact, the logic of the entire unit testing framework comes out. In three steps: The first step testloader the corresponding test cases according to the parameters passed in, that is, corresponding to the specific test method, and then makesuite all the test cases are assembled into testsuite, and finally Testsiute passed to Testrunner for execution. And we usually execute the Unittest.main (), in fact, is the Unittest.testprogram method, its function is the above analysis of the three steps, in the first step of its incoming parameters are its own module __main__; In the second step, the test methods in all the test classes in the module are extracted, and a test suite is generated, and the test suite is passed to Testrunner for specific testing. Finally, we give a complete unit test organization code, put the code in the Unit test case file in the same directory after the execution of the script, you can execute all the test case files.

Six, test set parameter configuration

1, the verbosity parameter can control the output error report detail degree, by default 1 , if set to 0 , do not output the execution result of each use case, that is, there is no 1th row in the result above, if set to 2 , output detailed execution result

2. Add stream in the parameter, can output report to file: Can output txt report with Texttestrunner, and can output HTML report with Htmltestrunner.

  #练习: Import randomimport unittestimport sys class testsequencefunctions (unittest. TestCase):    A = 1     def setUp (self):        SELF.SEQ = list (range) &NB sp;    @unittest. Skip ("Skipping") # Unconditional Ignore this test method     def test_shuffle (self):        Random.shuffle (SELF.SEQ)         Self.seq.sort ()         Self.assertequal ( SELF.SEQ, List (range))         self.assertraises (TypeError, Random.shuffle, (1, 2, 3))       If variable a > 5, the test method is ignored     @unittest. SkipIf (A > 5, "condition is not satisfied!")     def test_choice (self):        element = Random.choice (self.seq)       &NBS P Self.asserttrue (element in Self.seq)      # unless the platform that executes the test case is a Linux platform, the test method is ignored   Win32 is windows    @unittest. Skipunless (Sys.platform.startswith ("Linux"), "requires Linux")     def test_sample (self):        #期望抛出什么样的error         with self.assertraises (Value Error):            Random.sample (SELF.SEQ)         for element in ran Dom.sample (SELF.SEQ, 5):            self.asserttrue (element in Self.seq)   if __ name__ = = ' __main__ ':    # unittest.main ()     #使用测试集的方法执行     #装载测试用例 (this sentence is equivalent to suite = [testseq Uencefunctions ("Test_shuffle"),testsequencefunctions  ("Test_choice"), Testsequencefunctions ("Test_sample") ])     Suite = UnitTest. Testloader (). Loadtestsfromtestcase (testsequencefunctions)      #使用测试套件并打包测试用例     Suite = UnitTest. TestSuite (Suite)        #保存unittest的测试输入日志到文件     log_name= "E:\\test4\\log.txt"     #verbosity =2 refers to the level of detail of the output of the test result     #stream = f is the output of the result to a file f    with open (Log_name, "w+") as f:  & nbsp   &NBSP Result=unittest. Texttestrunner (stream = F,verbosity = 2). Run (Suite)     #unittest. Texttestrunner (verbosity = 2). Run (Suite)   #生成测试报告     print "testsrun:%s"%result.testsrun    Print "failures:%s"%len (result.failures)     print "errors:%s"%len (result.errors)     print " skipped:%s "%len (result.skipped)

Python unittest-3

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.