Python learning - UnitTest automated testing framework

Basic use of the UnitTest framework

1. Concept: UnitTest is a unit testing framework that comes with Python, use it for unit testing

2. Advantages of the UnitTest framework:

  • Ability to organize multiple use cases to execute
  • Provides rich assertion methods
  • Ability to generate test reports

3. Core elements:

  • TestCase (test case)
  • TestSuite (test suite)
  • TestRunner (runs test cases as text)
  • TestLoader (batch execution of test cases - search for modules starting with the specified letter in the specified folder)
  • Fixture (fixtures: two fixed functions, one used at initialization and one at end)

3.1 TestCase

1. Description: TestCase is a test case

2. Case:

1. Import package: import unittest

2. Define the test class: the new test class must inherit unittest.TestCase

3. Define the test method: the name of the test method must start with test ( note )

import unittest


class Test(unittest.TestCase):
    def test01(self):
        print("测试用例1")

    def test02(self):
        print("测试用例2")

 operation result:

Note: To run all the test methods of the test class, the cursor is positioned on the current line of the class and right click to run.
           Run a single test method: place the cursor on the current line of the test method.

 3.2 TestSuite

1. Description: A collection of multiple test cases is a TestSuite (test suite)

2. Use:

1. 实例化: suite = unittest.TestSuite() 
                (suite:为TestSuite实例化的名称) 

2. 添加用例:suite.addTest(ClassName("MethodName")) 
                (ClassName:为类名;MethodName:为方法名) 

3. 添加扩展:suite.addTest(unittest.makeSuite(ClassName)) 
                (搜索指定ClassName内test开头的方法并添加到测试套件中)

Tip: TestSuite needs to cooperate with TestRunner to be executed

3.3 TextTestRunner

1. Description: TextTestRunner is used to execute test cases and test suites

2. Use:

1. 实例化: runner = unittest.TextTestRunner() 

2. 执行: runner.run(suite) # suite:为测试套件名称

3. Case: (The main program file is on the left, and the TestCase.py file is on the right)

operation result:

3.4 TestLoader

1. Description: It is used to load TestCase into TestSuite, that is, load the test cases that meet the conditions, and package the test cases into a test suite; use unittest.TestLoader to automatically search for the specified beginning in the specified directory through the discover() method under this class .py file, and assemble the found test cases into a test suite.

2. Use:

suite = unittest.TestLoader().discover(test_dir, pattern='test*.py') 
    自动搜索指定目录下指定开头的.py文件,并将查找到的测试用例组装到测试套件 
    test_dir: 为指定的测试用例的目录 
    pattern:为查找的.py文件的格式,默认为'test*.py' 

    
也可以使用unittest.defaultTestLoader 代替 unittest.TestLoader() 


运行:
    runner = unittest.TextTestRunner() 

    runner.run(suite)

3. The difference between TestLoader and TestSuite

(1) TestSuite needs to manually add test cases (you can add a test class, or you can add a test method in the test class)

(2) TestLoader searches for the specified beginning .py file in the specified directory, and adds all the test methods in the test class, and cannot specify to add a certain test method


Fixture

1. Description: Fixture is an overview, the initialization and destruction of a test case environment is a Fixture

2. Control level:

  • method level
  • class level
  • Module Level (Understanding)

3. Use:

1、方法级别:

# 初始化(前置处理)
def setUp(self):           --> 首先自动执行

# 销毁(后置处理)
def tearDown(self):        --> 最后自动执行

# 运行于测试方法的始末,即:运行一次测试方法就会运行一次setUp和tearDown

2、类级别:

# 初始化(前置处理)
@classmethod 
def setUpClass(cls):        --> 首先自动执行 

# 销毁(后置处理): 
@classmethod 
def tearDownClass(cls):     --> 最后自动执行

# 运行于测试类的始末,即:每个测试类只会运行一次setUpClass和tearDownClass

3、模块级别(了解)

# 初始化(前置处理) 
def setUpModule():          --> 首先自动执行

# 销毁(后置处理)
def tearDownModule():       --> 最后自动执行

# 运行于整个模块的始末,即:整个模块只会运行一次setUpModule和tearDownModule

4. Usage scenarios:

(1) Initialization

  • Get the browser instance object
  • maximize browser
  • implicit wait

(2) end

  • close browser driver object

Affirmation

1. Concept: Let the program replace the process of human judgment whether the execution result of the test program meets the expected result

2. Commonly used UnitTest assertion methods:

serial number Assertion method assertion description
1
assertTrue(expr, msg=None)
Verify that expr is true , if false , fail (important)
2
assertFalse(expr, msg=None)
Verify that expr is false , if true , fail
3
assertEqual(expected, actual,msg=None)
Verify expected==actual , fail if not equal (important)
4
assertNotEqual(first, second,msg=None)
Verify that first != second, if equal, fail
5
assertIsNone(obj, msg=None)
Verify that obj is None , otherwise fail
6
assertIsNotNone(obj, msg=None)
Verify that obj is not None , otherwise fail
7
assertIn(member, container,msg=None)
Verify whether member in container (important)
8
assertNotIn(member, container,msg=None)
Verify whether member not in container

3. How to use:

import unittest
 
def add(x, y): 
    return x + y 

class Assert(unittest.TestCase): 
    def test01(self): 
        num = add(1, 2) 
        self.assertEqual(3, num)     # 判断3是否和num相等

    def test02(self): 
        num = add(1, 2) 
        flag = num == 3 
        self.assertTrue(flag)        # 判断flag是否等于True

to parameterize

1. Concept: Pass data through parameters, so as to realize the separation of data and scripts and realize the repeated execution of use cases.

The unittest testing framework itself does not support parameterization, but it can be realized by installing the unittest extension plug-in parameterized.

2. Data format:

  • Single parameter: type is list
  • Multiple parameters: type is list nested tuple
  • The parameter setting variable in the test function refers to the parameter value, note: the number of variables must be the same as the number of data values

3. How to use:

  • 导包:from parameterized import parameterized
  • The parameters of the test function can be parameterized using the @parameterized.expand decorator
# 方式一 
@parameterized.expand([(1, 1, 2), (1, 0, 1), (0, 0, 0)]) 
def test_add(self, x, y, expect): 
    pass 

# 方式二 
data = [(1, 1, 2), (1, 0, 1), (0, 0, 0)] 

@parameterized.expand(data) 
def test_add(self, x, y, expect): 
    pass 

# 方式三 
def build_data(): 
    return [(1, 1, 2), (1, 0, 1), (0, 0, 0)] 

@parameterized.expand(build_data) 
def test_add(self, x, y, expect): 
    pass

jump over

1. Introduction: For some test functions and test classes that are not completed or do not meet the test conditions, execution can be skipped

2. How to use:

# 直接将测试函数标记成跳过 
@unittest.skip(reason) 

# 根据条件判断测试函数是否跳过
@unittest.skipIf(condition, reason)

 Note: The above two methods can modify functions (def) and classes (class)

3. Case:

import unittest

version = 35

class TestSkip(unittest.TestCase):
    @unittest.skip("代码未完成")
    def test_01(self):
        print("test_01")

    @unittest.skipIf(version <= 30, "版本大于30才会执行")
    def test_02(self):
        print("test_02")

Results of the:


Generate HTML test report

1. Description: The HTML test report is to generate a report in the form of HTML (web page) after the test case is executed.

2. Function:

  • The test report is the embodiment of the test results
  • The test report contains details about the test case

3. Generation method:

  • Export Test Results (included with UnitTest)
  • HTML TestRunner (3rd party module) - important

3.1  Export Test Results

case:

import unittest

# 定义 测试套件
suite = unittest.defaultTestLoader.discover("./", pattern="test0*.py")

# 自带执行
with open("./report.txt", "w", encoding="utf-8") as f:
    unittest.TextTestRunner(stream=f, verbosity=2).run(suite)

Note: strem is the file stream, verbosity is the execution mode, optional [1, 2, 3]

Results of the:

3.2 HTML TestRunner

Plug-in acquisition: https://pan.baidu.com/s/16rGtY_yIQ7sX5lAFolsGSg?pwd=jl89 Extraction code: jl89

case:

# 导包
from tools.HTMLTestRunner import HTMLTestRunner
import unittest

# 定义 测试套件
suite = unittest.defaultTestLoader.discover("./", pattern="test0*.py")

# 插件执行
with open('./report.html', "wb") as f:
    HTMLTestRunner(stream=f, title='xxx自动化测试报告', description='win10 Chrome').run(suite)

stream: file stream, the name and encoding format of the report to be opened and written (the html report must be in binary form)

title: [optional parameter], which is the title of the report, such as XXX automated test report

description: [optional parameter], describes the information for the report; such as the version of the operating system, browser, etc.

Results of the:

Guess you like

Origin blog.csdn.net/ouihsiad/article/details/126965555