Python Learning note 9-unit test UnitTest

Source: Internet
Author: User

Python has a self-contained unit test framework that is the UnitTest module, which is used for unit testing, which encapsulates some of the result methods returned by the checksum and some initialization operations before the use cases are executed.

Before you say UnitTest, say a few concepts:

TestCase is also a test case

TestSuite Multiple test cases are assembled together, that is TestSuite

Testloader is used to load testcase into Testsuite.

Testrunner is to execute a test case, the results of the test are saved to the TestResult instance, including how many test cases were run, how much success, how many failed, etc.

Write a simple unit test case below

Import unittestfrom beautifulreport Import Beautifulreportdef calc (x, y): Return x+yclass Testcalc (unittest. TestCase): def test_pass_case (self): #用例一定要以test开头 print (' This through use case ') Res=calc Self.assertequa    L (3,res) def setup (self): #执行每个用例前的操作 print (' I'm setUp. ') def tearDown (self): #执行每个用例后的操作 print (' I am TearDown ') @classmethod def setupclass (CLS): print (' I am SETUPCLA    SS ') @classmethod def teardownclass (CLS): print (' I am teardownclass ') def test_a (self): print (' a ') def test_fail_case (self): print (' This is a failed test case ') Res=calc (9,8) self.assertequal (98,res) if __name__== ' __ma In__ ': #unittest. Main () #单独执行这个类中的case # suite=unittest. TestSuite () # suite.addtests (unittest. Testloader (). Loadtestsfromtestcase (Testcalc)) # runner = UnitTest. Texttestrunner (verbosity=2) # Runner.run (suite) Suite = UnitTest. TestSuite () suite.addtests (Unittest.makesuite (testcalc)) #这个类里面的所有测试案例 Result=beautiFulreport (Suite) result.report (filename= ' Test report ', description= ' description ', log_path= '. ') 

Some common assertions are:

        Assertequal (A, b)     a = = B              assertnotequal (A, b)     A! = B              asserttrue (x)     bool (x) is True              Assertfalse (x)     BOOL (x) is False              assertisnone (x)     x is None             assertisnotnone (x)     x are not none           Assertin (A, B)     A in B            Assertnotin (A, b)     a not in B

How to generate a test report, you need to add another module, Htmltestrunner, this module needs to install itself, using the execution of test cases will generate an HTML test report, there will be the results of each test case execution, the code is as follows:

        Import Htmltestrunner Import UnitTest class MyTest (unittest. TestCase): #继承unittest. TestCase def tearDown (self): #每个测试用例执行之后做操作 print (' 111 ') def setUp (sel f): #每个测试用例执行之前做操作 print (22222) def test_run (self): # Self.asserte Qual (self.assertis) #测试用例 def test_run2 (self): # Self.ass Ertequal (self.assertis) #测试用例 def test_run3 (self): # self . Assertequal (Self.assertis) #测试用例 def test_run1 (self): #            Self.assertequal (Self.assertis) #测试用例 if __name__ = = ' __main__ ': Test_suite = UnitTest. TestSuite () #创建一个测试集合 test_suite.addtest (MyTest (' test_run1 ')) #测试套件中添加测试用例 #test_suite. Addtest (unittes T.makesuite (MyTest)) #使用makeSuite方法添加所有的测试方法 fp = open (' res.html ', ' WB ') #打开一个保存结果的html文件 runner = HTMLTestRunner.H            Tmltestrunner (stream=fp,title= ' API test Report ', description= ' test case ') #生成执行用例的对象 Runner.run (test_suite) #执行测试套件

If we have a lot of modules, each module is written under a lot of Python files, each python file has a test case, how to put the use case in this directory is executed, we must first find all the Python files in this directory, and then find the inside of the test cases, executed, The code is as follows:

        Import Unittest,htmltestrunner        suite = unittest. TestSuite () #创建测试套件        all_cases = Unittest.defaultTestLoader.discover ('. ', ' test_*.py ')        # Locate all the test cases in the Python file that begin with test in a directory in the        all_cases:            suite.addtests (case) #把所有的测试用例添加进来        fp = open (' Res.html ', ' WB ')        runner = Htmltestrunner.htmltestrunner (stream=fp,title= ' all_tests ', description= ' all test Cases ')        Runner.run (Suite)        #运行测试

When we continue to integrate in the future, to let the code run automatically, we will use Jenkins, but the results of the test report is HTML format, Jenkins do not know, in the Jenkins inside the display does not come out. Then we have to produce some Jenkins know the test report, Jenkins know the XML format of the report, then we produce the XML format, we need to use a new module, Xmlrunner, install the direct pip install Xmlrunner can be, the code is as follows:

Import Unittestimport xmlrunner# Imports This module class My (UnitTest. TestCase):     def test1 (self,a,b,c):        self.assertequal (a+b,c) if __name__== ' __main__ ':    test_suite = UnitTest. TestSuite ()    test_suite.addtest (Unittest.makesuite (My))    runner = Xmlrunner. Xmltestrunner (output= ' report ') #指定报告放的目录    runner.run (test_suite)

Then we run, we can see that in the report directory has produced the XML format of the reports, but also automatically added the date

  

  

  

  

  

Python Learning note 9-unit test UnitTest

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.