Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

This paper has participated inProject DigginTo win the creative gift package and challenge the creative incentive money.

preface

In the software development process, we have all heard of the waterfall development process, which must have a certain understanding of the development of each link.

The waterfall development process is divided into three main parts

  1. Preliminary requirements design stage
  2. Coding implementation stage
  3. Test validation phase

As a test, we mainly participated in the verification of the part 3 test. Unit test, integration test, etc

Unit testing, which is closely linked to the RD coding phase, is how to nip most bugs in the bud at the beginning of coding. It cannot be omitted from the product.

For python, the built-in library also provides us with a unittest module called unittest. In this installment we’ll learn about unittest methods. Let’s go~

1. Unittest module overview

Unittest is a module provided by the Python built-in library for unit testing, similar in structure to mainstream unit testing frameworks such as JUnitd.

Features supported by Unittest

  1. Support test automation
  2. Configure the Shared
  3. Support aggregation of test cases into test sets
  4. Testing is independent of the reporting framework

Unittest Usage method

  • Import unittest module: import unittest
  • The test class needs to inherit from Unitest.TestCase
  • A test case must start with test
  • Assert to determine test results
  • Use HTMLTestRunner to produce test reports

2. Unittest

Unitest module consists of five parts

  1. Testcase Test cases

    • Testcase is usually a complete test item.
    • A test item contains prerequisites, steps, and expected results.
    • A Testcase is equivalent to a test unit
  2. Testsuit Test suite

    • Testsuit consists of multiple test units, TestCases, that fully verify a feature
    • You can add Testcase to Testsuit by adding test
    • Testsuit can also nest other testsuits
  3. TestRunner test execution

    • Provide execution policies and results for the test suite
    • Testsuit or Testcase is executed via TextTextRunner().run()
    • TestRunner supports graphical and text interfaces to display test results
  4. TestFixture tests before and after

    • Environment setup and destruction prior to test execution
    • This is done through Testcase’s setUP() and tearDown() methods

3. How UnitTest works

After understanding the five major parts of UnitTest, their execution process is shown in the diagram:

  1. Testcase created needs to inherit from UnitTest.testCase
  2. Testcase contains many methods, which must start with test
  3. Load testCases into Testsuite using TestLoader
  4. TextTestRunner performs Testsuit and stores the data in TextTestResult
  5. By default, TextTestResult execution results are printed to the console

4. Unittest

Unittest library common properties and methods:

  • Test cases for the new key all need to inherit from the UnitTest. TestCase class

Unittest. Testcase provides methods for setting up and destroying test environments

methods role
setUp() Preloading the test environment
tearDown() Postposition the test environment
setUpClass() The test method in Testcase performs the pre-operation
tearDownClass() The test method in Tescase performs the post-operation

📢 setUpClass (), tearDownClass ()

  1. You must use the @classMethod decorator
  2. All cases are run only once
  • Decorators that control methods are also provided in TestCase
A decorator role
@unittest.skip(reason) Skip this step
@unittest.skipIf(condition,reason) When condition is true, skip this step
@unittest.skipUnless(condition,reason) Skip this step unless condition is true
@unittest.expectedFailure Mark this step as an exception

5. Test the cat

Unittest = unitTest = unitTest = unitTest = unitTest = unitTest

  1. mathfunc.py
def add(a, b) :
    return a+b

def minus(a, b) :
    return a-b

def multi(a, b) :
    return a*b

def divide(a, b) :
    return a/b
Copy the code
  1. Unittest unittest scripts
import unittest
from test import mathfunc

class TestMathFunc(unittest.TestCase) :
    """Test mathfuc.py"""

    def setUp(self) - >None:
        print ("-----setup")

    def tearDown(self) - >None:
        print ("----teardown")
    #setUpClass(): the @classMethod decorator must be used, only once before all cases are run
    @classmethod
    def setUpClass(cls) - >None:
        print("This Setupclass() method only called once")

    #tearDownClass(): the @classMethod decorator must be used, only once after all cases are run
    @classmethod
    def tearDownClass(cls) - >None:
        print("this teardownclass() method only called once")

    @unittest.skipUnless(3>2."Non-execution")
    def test_add(self) :
        """Test method add(a, b)"""
        print ("---add")
        self.assertEqual(3, mathfunc.add(1.2))
        self.assertNotEqual(3, mathfunc.add(2.2))

    @unittest.skip("Do not execute this use case")
    def test_minus(self) :
        """Test method minus(a, b)"""
        print ("---minus")
        self.assertEqual(1, mathfunc.minus(3.2))

    @unittest.skipIf(3<2."Execute this use case")
    def test_multi(self) :
        """Test method multi(a, b)"""
        print ("---multi")
        self.assertEqual(6, mathfunc.multi(2.3))
    @unittest.expectedFailure
    def test_divide(self) :
        """Test method divide(a, b)"""
        #self.skipTest(" not executed ")
        print ("---divide")
        self.assertEqual(2, mathfunc.divide(6.3))
        self.assertEqual(2.5, mathfunc.divide(5.0))
if __name__ == '__main__':
    Execute all use cases once
    # unittest.main()
Copy the code
  1. Choose to execute the test_add and test_minus methods
if __name__ == '__main__'Suite = unittest.testSuite () tests = [TestMathFunc()"test_add"),TestMathFunc("test_minus")]
    suite.addTests(tests)

    unittest.TextTestRunner().run(suite)
Copy the code

conclusion

In this installment, we’ll take a look at Python’s unittest unittest module, how it works, and how to execute unittest.

After writing the automated use cases, we can use unitTest tests to verify the correctness and stability of our use cases.

That’s the content of this episode. Please give us your thumbs up and comments. See you next time