Python Unit Test

Source: Internet
Author: User
Tags italic font

One, Unit test

Unit tests are used to test the correctness of a module, a function, or a class.

Load of unit tests: Start the test module of the unit test by Unittest.main (), add to the Testsuite collection and load all the tested objects, and testsuit is the use case for unit tests.

Additional viewing module contents and usage code are as follows:

Import UnitTest
Import Htmltestrunner
From Beautifulreport import Beautifulreport
Memblist1 = Dir (unittest) # See what members are in the module
For memb in Memblist1: #查看具体成员的用法
cur = getattr (UNITTEST,MEMB)
Print (Help (cur))

Memblist = Dir (htmltestrunner) # See what members are in the module
For memb in Memblist: #查看具体成员的用法
cur = getattr (HTMLTESTRUNNER,MEMB)
Print (Help (cur))

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.

The logic of the entire unit testing framework is divided into three steps: The first step is to obtain the corresponding test case according to the Testloader parameters, that is, corresponding to the specific test method,
Makesuite then assembles all the test cases into testsuite, and finally passes testsiute to Testrunner for execution.
And we usually execute the Unittest.main (), in fact, is the Unittest.testprom 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.

Common assertions:

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 is not None
Assertin (A, B) A in B
Assertnotin (A, b) a not in B
Instance:
 Import unittest 
def calc (x, y): #被测模块

Return x+y

class Testcalc (unittest. TestCase): #单元测试模块
def test_pass_case (self):
"" This is the test case passed by '
print (' This through use case ')
res = Calc
self.assertequal (3,res)
Self.assertnotequal (2,res) #返回的结果不一样
def test_fail_case (self ):
' This is a failed test case '
print (' This is a failed use case ')
res = Calc (1, 2)
Self.assertequal (5, RES)
If __name__ = = ' __main__ ':
Unittest.main () #他会帮你运行当前这个python里面所有的测试用例.
Note: The method that begins with test is the test method, and the method that does not start with test is not considered a test method and is not executed at the time of the test. The order in which the use cases are executed is the
output in alphabetical order: "F denotes a fail, the point before F indicates a pass, and an e indicates the program itself exception"

F.
======================================================================
Fail:test_fail_case (__main__. TESTCALC)
This is a failed test case
----------------------------------------------------------------------
Traceback (most recent):
File "c:/users/lidal/pycharmprojects/llq-code/day7/exercise. Py", line +, in Test_fail_case
Self.assertequal (5, RES)
Assertionerror:5! = 3

----------------------------------------------------------------------
Ran 2 Tests in 0.000s

FAILED (Failures=1)

Two, setUp and TearDown

Both the SetUp () and TearDown () methods are executed separately before and after each call to a test method

setUp()and tearDown() How is it used? Assuming your test needs to start a database, you can connect to the setUp() database in the method and close the database in the tearDown() method so that you do not have to repeat the same code in each test method:

 class Testcalc (unittest. TestCase): #单元测试模块 
def test_pass_case (self):
"" This is the test case passed by '
print (' This through use case ')
res = Calc
self.assertequal (3,res)
Self.assertnotequal (2,res) #返回的结果不一样
def test_fail_case (self ):
' This is a failed test case '
print (' This is a failed use case ')
res = Calc (1, 2)
Self.assertequal (5, RES)
def test_a:
Print (' hahahaha ')
def setUp (self):
print (' SetUp.. ')
# Each use case executes before it is run
def TearDown ( Self):
# Every use case executes after it is run
pri NT (' TearDown. ')
three, SetupClass and Teardownclass
The two methods of SetupClass () and Teardownclass () are executed once before and after all use cases are executed
Here's how to use it:
@Classmethod
Def setupclass (CLS):
print ( ' I am setupclass")

@classmethod
" Span style= "color: #000080; Font-weight:bold ">def teardownclass (cls):
print ( Span style= "color: #008080; Font-weight:bold "> I am teardownclass")

Four, output the test report in HTML format
A, you need to install the Htmltestrunner module (you need to manually import to)
Import Htmltestrunner
if __name__ = =' __main__ ':
Suite = UnitTest. TestSuite ()#Define a test suite
# suite.addtest (Testcalc (' test_pass_case '))
# suite.addtest (Testcalc (' test_a '))
# suite.addtest (Testcalc (' Test_fail_case ')) #For a single add case
Suite.addtests (Unittest.makesuite (TESTCALC))#All the test cases inside this class
f =Open# Open a test report file
Runner = Htmltestrunner.htmltestrunner (stream=f,title= description=< Span style= "color: #008080; Font-weight:bold "> description ")
Runner.run (suite) # run
b, install Beautifulreport module, more intuitive and beautiful test report generated than Htmltsetrunner module (also need to import manually)
Import Beautifulreport
if __name__ = =' __main__ ':
Suite = UnitTest. TestSuite ()#Define a test suite
# suite.addtest (Testcalc (' test_pass_case '))
# suite.addtest (Testcalc (' test_a '))
# suite.addtest (Testcalc (' Test_fail_case ')) #For a single add case
Suite.addtests (Unittest.makesuite (TESTCALC))#All the test cases inside this class
# f = open (' report.html ', ' WB ') #Open a file for a test report
# runner = Htmltestrunner.htmltestrunner (stream=f,title= ' Test_report ',
# description= ' description "
# Runner.run (Suite) # run
result = Beautifulreport (suite)
Result.report ( Filename=description = description ", log_path=< Span style= "color: #008080; Font-weight:bold ">".

Five, output the test report in XML format for subsequent Jenkins use
Pip Install xmlrunner command installs Xmlrunner module
Import Xmlrunner
if __name__ = =' __main__ ':
Suite = UnitTest. TestSuite ()#Define a test suite
# suite.addtest (Testcalc (' test_pass_case '))
# suite.addtest (Testcalc (' test_a '))
# suite.addtest (Testcalc (' Test_fail_case ')) #For a single add case
Suite.addtests (Unittest.makesuite (TESTCALC))#All the test cases inside this class
runner = Xmlrunner. Xmltestrunner (output= "report") Span style= "color: #808080; Font-style:italic "># Specify the directory where the report is placed
Runner.run (suite)
Output: You can see that the report has been generated in XML format, and the date has been automatically added


Python Unit Test

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.