Python unit testing framework unittest uses full analysis (book at the end of the article)

unittest is a unit testing framework that comes with the Python language. It is not only suitable for unit testing, but also for web automation testing. It provides many assertion methods, can organize and execute test cases, and generate test results.

unittest basic concept

  1. TestCase test case, a TestCase is a test case.

  2. TestSuite test suite, a collection of multiple test cases. TestSuite can nest TestSuite.

  3. TestRunner test execution, used to execute the test case suite.

  4. The setup and destruction of a test environment by TestFixture is called a Fixture, such as closing the database connection, cleaning up the test environment data, and starting and closing the service process.

  5. TestLoaderTestLoader is used to load TestCase into TestSuite. There are several loadTestsFrom__() methods, which are to find TestCase from various places, create their instances, add them to TestSuite, and return a TestSuite instance.

Test method: setUp, tearDown execution Each test method will execute setUp, tearDown once

Class level: setUpClass, tearDownClass All test methods are executed before running and after running. Using the @classmethod decorator, the entire test process is only executed once.

unittest affirmations

Assertion is to let the program judge whether the execution result meets expectations.

6d2d8d0b3c427bfa12689f5d56687394.png
  • The test module introduces import unittest

  • The test class must inherit unittest.TestCase

  • The test method must start with "test", and the execution sequence is executed in ascending order according to the ASCII code of the beginning string.

A simple unittest usage example

import unittest
class Test(unittest.TestCase):
    def setUp(self) -> None:
        # 每个测试方法前执行
        print("setUp方法")
    def tearDown(self) -> None:
        # 每个测试方法后执行
        print("tearDown方法")
    @classmethod
    def setUpClass(cls) -> None:
        print("setUpClass每个类执行一次")
    @classmethod
    def tearDownClass(cls) -> None:
        print("tearDownClass每个类执行一次")
    def test_01(self):
        a = 1
        b = 2
        c = a + b
        self.assertEqual(c,3)
    def test_02(self):
        a = 2
        b = 3
        c = a*b
        self.assertEqual(c,6)

if __name__ == '__main__':
    # 调用main方法执行unittest内所有test开头的方法
    unittest.main()
ea57ee591f8a2055af835875481a1b70.png

Several methods of loading and executing use cases

main method

if __name__ == '__main__':
    unittest.main()

testsuit mode

suit = unittest.TestSuite()  # 创建suit实例并构造测试用例集
    suit.addTest(Test('test_01'))  # Test为class名;test_01是class中的方法
    suit.addTest(Test('test_02')) # 用例执行顺序,按照加载的顺序执行
    runner = unittest.TextTestRunner()
    # 使用run方法运行测试套件
    runner.run(suit)

testloader method

The loader TestLoader provides the following methods to find use cases and add test suites in batches:

  • loadTestsFromTestCase: Find the test case based on the incoming test class

  • loadTestsFromName: Find test cases based on the name passed in

  • loadTestsFromModule: Add all test cases in the module by module name

suit = unittest.TestSuite()
    loader = unittest.TestLoader() # 创建加载器对象
    suit.addTest(loader.loadTestsFromTestCase(Test)) # 通过测试类加载测试
    runner = unittest.TextTestRunner()
    # # 使用run方法运行测试套件
    runner.run(suit)

discover path loading

Use the unittest.defaultTestLoader() class to automatically search for .py files at the specified beginning in the specified directory through the discover() method under this class, and assemble the found test cases into the test suite.

test_dir='./'
    # test_dir为要指定的目录 ./为当前目录;pattern:为查找的.py文件的格式
    discover = unittest.defaultTestLoader.discover(test_dir,pattern='test_*.py')
    runner = unittest.TextTestRunner()
    runner.run(discover)

Execution result of unittest

  • "." indicates that the test case execution passed

  • "F" means execution failed

  • "E" means execution error

  • "s" means run skip

testing report

After the unit test is completed, the result can be generated as an HTML test report. HTMLTestRunner is an extension of the unittest module of the Python standard library. It generates easy-to-use HTML test reports.

Preparation for using HTMLTestRunner

1. Download HTMLTestRunner.py Link: https://pan.baidu.com/s/1-iLHuHHbpuL1qdV3AMj6bA Extraction code: w8og You can also search for more powerful templates on github.

2. Copy the HTMLTestRunner.py file to the project folder or the lib folder under the Python installation path.

example

import unittest
from HTMLTestRunner import HTMLTestRunner
import time


class Test(unittest.TestCase):
    def setUp(self) -> None:
        # 每个测试方法前执行
        print("setUp方法")

    def tearDown(self) -> None:
        # 每个测试方法后执行
        print("tearDown方法")

    @classmethod
    def setUpClass(cls) -> None:
        print("setUpClass每个类执行一次")

    @classmethod
    def tearDownClass(cls) -> None:
        print("tearDownClass每个类执行一次")

    def test_01(self):
        a = 1
        b = 2
        c = a + b
        self.assertEqual(c, 3)

    def test_02(self):
        a = 2
        b = 3
        c = a * b
        self.assertEqual(c, 5, "不相等")


if __name__ == '__main__':

    test_dir = './'
    # test_dir为要指定的目录 ./为当前目录;pattern:为查找的.py文件的格式
    discover = unittest.defaultTestLoader.discover(test_dir,pattern='test_*.py')
    # 定义报告目录
    file_dir = "./report/"
    # 定义报告名称格式
    now_time = time.strftime("%Y-%m-%d %H_%M_%S")
    # 报告完整路径和名称
    file_name = file_dir + now_time + "Report.html"
    with open(file_name, "wb") as fp:
        # 创建执行对象  是一个HTMLTestRunner的对象  生成测试结果报告内容
        runner = HTMLTestRunner(stream=fp,
                                title="测试报告",
                                description="用例执行情况:",
                                verbosity=2
                                )
        # 执行测试流程
        runner.run(discover)

1ae9d684a8193c8873693690726dcd53.png

 
  

Recommended books

" Vue.js family bucket zero basic entry to advanced project actual combat "

Vue.js is a progressive framework for building user interfaces. This book aims to help readers fully grasp the Vue.js family bucket technology and single-page front-end and back-end separation project development, understand the MVVM framework idea, and let front-end and back-end developers quickly Proficient in Vue.js family bucket technology.

This book runs through entry preparation practice, basic core cases, intermediate advanced practical combat, and comprehensive advanced project explanations. Main technologies included: NPM/CNPM, VS Code, Vue.js, MVVM, Axios, Vue Router, webpack, ECMAScript 6, Vue Loader, Vue CLI, Element UI, Vuex, Mock.js, Easy Mock, ECharts, Promise, Interceptors, component communication, cross-domain issues, online deployment, etc.

36550f401778c1001ad561cd34007003.png

留言点赞送此书: 点在看本文并留言(本文内容相关、本书相关、其他公众号建议),我将随机挑选一位粉丝包邮送出本书(同一人一个月只有一次机会),送书活动会持续进行,机会多多,大家持续关注,感谢。

Guess you like

Origin blog.csdn.net/XingLongSKY/article/details/121279746