Detailed explanation of UnitTest for Python interface automated testing

basic concept

The UnitTest unit testing framework is inspired by JUnit and has a similar style to mainstream unit testing frameworks in other languages. It supports test automation, configuration sharing and shutdown code testing. Supports aggregating test cases into test sets and making tests independent of the reporting framework.

It is divided into four parts: test fixture, TestCase, test suite, and test runner, which are:

Test scaffolding: the preparation work required to carry out a test, as well as all related cleaning operations;

Test Case: A test case is an independent unit of testing. It checks the response when specific data is entered;

Test suite: It is used to archive test cases that need to be executed together;

Test runner: is a component used to execute and output test results.

Detailed explanation of TestCase

Class TestCase provides support for test cases. Set up a new test class by inheriting TestCase, and set up test methods. Each test method implements unit testing by comparing the actual response results with the expected results.

Test cases include methods: setUp(), tearDown(), setUpClass(), tearDownClass(). Note that the class name should start with Test, and the test case name should start with test.

Here is an example to show:

import unittest
class Test_unittest(unittest.TestCase):
    def setUp(self) -> None:
    def test(self):
    def tearDown(self) -> None:
if __name__ == '__main__':

You can see that the running results print the contents of three test cases. The setup and teatdown methods will be executed before and after each test case is executed. If another test case is added, setup and teardown will be executed again, as shown in the following figure:

So if you want to initialize and end the method only once, you can use setUpClass(), tearDownClass(), but be sure to add the annotation @classmethod in front of the method. See the following example and results:

import unittest
class Test_unittest(unittest.TestCase):
    def setUpClass(cls) -> None:
    def testcase1(self):
    def testcase2(self):
    def tearDown(self) -> None:
if __name__ == '__main__':

As you can see, if the setUpClass() method is used, it is only initialized once. If teardown is not used, each use case will be executed once.

Common methods


There are also commonly used assertions and skip test cases in the test cases. The UniTtest framework also provides a built-in assertion method, which mainly includes the following:

skip skip

In actual testing, if the automated test cases corresponding to the functional points with functional defects cannot be executed, or the test cases are not executed, you can use the skip() method to operate. The usage method is:

1.unittest.skip(‘Enter reason’) – perform skip operation unconditionally

2.unittest.skipif(2>1,’reason’)——executed when the judgment condition is true

3.unittest.skipUnless(1>2’reason’)—executed when the judgment condition is false

4.unittest.expectedFailure—Execution errors are not included in failed test cases

Check the example below. The testcase1 method is skipped. The testcase2 method uses assertions, but the assertion results are incorrect, so an error message is reported:

import unittest
class Test_unittest(unittest.TestCase):
    def setUpClass(cls) -> None:
    def testcase1(self):
    def testcase2(self):
        a = 1
    def tearDown(self) -> None:
if __name__ == '__main__':

test suite

When there are multiple test cases in a class and they will not run at the same time, you can choose to add the test cases to the suite and run them in the suite (writing directly in the file in pycharm does not work, you need to create a new py file).

1. Add directly to the suite one by one:
Explanation: Import the class in the file, define a suite name, use the testsuite method, add test cases to the suite, define a run name, use the run method, add the test suite, and then run (you have to add test cases one by one) .

2. Define a list [ ] to save all use cases in it, and then run:
3. Directly read the form of the class name to run (the simplest and most convenient, cannot use ”):
4. The name is also read, but it is easy to find the class. You need to add a file name in front.


1. After writing the script, create a new file and add the use cases to the suite to execute them all.

2. Download the htmlTestrunner source code from the Internet, copy it to the python/lib directory and import it:

Python request

Main method analysis

requests is the simplest and easiest-to-use HTTP library implemented in Python. The requests library has 7 main methods:
For example: There is no correlation between the interfaces of the ordinary interface test, so you can directly define variables to initiate get and post requests.
Post requests are commonly divided into json and formdata. The parameters requested by the two methods are as shown in the screenshot. If authentication is required, you need to import the auth package and follow the request method.

Detailed explanation of requests method

To view the specific method, you can directly hold down ctrl+left-click the requests method to view the source code.
1.url: request address dictionary, byte sequence or file object, as the content of Request

3.json: JSON format data, as the content of the Request

4.headers: dictionary, HTTP custom headers

5.Cookie: dictionary or CooKiJar, cookie in Request

6.auth: Yuanzu, supports HTTP authentication function

7.files: dictionary type, transfer files

8.timeout: Set the timeout time in seconds

9.proxies: Dictionary type, set access proxy server, you can add login authentication

10.allow_redirects: True/False, default is True, redirection switch True/False, the default is True, get the content and download the switch immediately

12.verity: True/False default True, authentication ssl certificate switch

13.cert: local ssl certificate path

Response return method detailed explanation

1.response.status_code #Returned http response status code

2.response.content #returns bytes type, which is binary data

3.response.headers #Returned http request headers

4.response.json() # Return the Json data in the response

5.response.url # Return url

6.response.encoding #Return the encoding format of the response

7.response.cookies # Return the cookies in the response

8.response.text #Returns Unicode data. -text

Session detailed explanation

For interface tests that require front and rear interface dependencies, such as obtaining a token from the previous request and using it as a parameter for the next interface request to submit, the above method is obviously inappropriate. According to the above method, many variables need to be defined, and then based on the dependencies to add to the corresponding request parameters.

The following method uses the session method. It runs through the front and back. As long as it is added once, it can be used for all requests.

1. This is the cynthia defect management system. When logging in, you need to get the cookie in the response as the cookie for the next request, otherwise you will not be able to log in.

2. Therefore, in the UniTtest structure, the login operation can be placed in the setup. Similar to UI automation, the login is placed in the initialization.

3. In the setup, add the response cookie value to the request, and also add the browser UA.

4. Parameters can be reused. The variables requested from beginning to end are all rsp, and the parameters in the body are all dict. It is simple and convenient to write.
Define a session with variable s equal to requests, and use this session of s to initiate requests later.

Define a variable equal to rsp equal to s to initiate the result of the request.

The tokenid needs to be added to the cookie in the header file of the s session request, otherwise you will not be able to log in. This ID is in the rsp response information.

Because the response information is in json dictionary format, it needs to be added to the request header in the screenshot format.

If you need to add fields or content to the dictionary, follow the format of the screenshot s.headers[‘xxx’] = “xxx”. If there is this key: value in the dictionary, then the value value will be updated directly. If there is no such key, then it will be added. This key:value to the dictionary.

Interface practice

Add token to header file

In the company’s actual projects, when debugging the interface, you first need to obtain the token. You must first call the request to obtain the token. Then, after getting the token value, add it to the header file in the subsequent interface.

(Swipe left or right to view the complete code)

By calling Get Token in the setup initialization method, you can get the token value, and then add it to the head of the entire session. There is no need to add additional head to subsequent requests.

Use ddt for parameterization

For ddt data-driven testing, first pip list ddt, install the third-party library, and import the data in the library at the top of the code

from ddt import ddt, data, declare ddt in front of the test class, use @ddt:
1. Declare the use of data before the test case, using @data:

def test_ddt1(self,value):
    print(value)`Insert code snippet here`
(Swipe left or right to view the complete code)

In the running results, this use case is executed twice, and test1 and test2 are output respectively.

2. Data usage reads files

This method requires unpacking, so the unpack method needs to be used. Just declare @unpack before the test case.

def readline(self):
    date = []
    file = open('D:\\base64\\keyid.txt','r',encoding='utf-8')
    for line in file:
    return date
def test_ddt2(self,vars):

Explanation of the running results: Define a method for reading files, define a list array, use the open method of the file function, read the file named “txt1” in the form of read, the encoding format is utf-8, and use for The loop method keeps reading each line, ending with a \n newline character, separating each parameter with a comma, and finally returning the data value for direct calling below.

After writing the reading method above, you can use this method directly before the test case, in the form of @data (*readfile ()), and then use the @unpack unpacking method.

Generate test report

After writing the test cases according to the above method, combine the HTMLTestRunner of the UniTtest framework to generate the report to generate the interface test report.
Just download the HTMLTestRunner library file found on the Internet and put it in the lib folder of the Python installation directory. You can then call it directly


This tutorial is just a small taste of interface testing. There is still much to learn in the future. The requests library can not only be used for interface testing, but can also be used for crawlers and the like. The road to technology will never end. We Testers also need to work harder.

The house must be built layer by layer, and knowledge must be learned bit by bit. Everyone should have a good foundation in the learning process and get started with practical operations. Without further ado, here is a quick introduction! This is the skill learning materials + practical explanations for each stage (function, interface, automation, performance, test development) that I stayed up late to compile. It is very suitable for private study. It is much more efficient than looking for materials for self-study. I share it with you.

Get the w/x/g/z/h: software testing tool

Self-study recommended videos from Bilibili:

Career change with zero foundation:38 days! After studying software testing by myself, I got a test job offer from Byte, which can be called the best video at Bilibili! [Automated testing, performance testing, test development]

Automation advancement:In 2022, site B launches the first ultra-detailed Python automated software testing practical tutorial to prepare for the gold, three, silver and four job-hopping seasons. After advanced learning, you will gain a whopping 20K.

It’s not easy to type. If this article is helpful to you, please like, bookmark, and follow to give the author an encouragement. It also makes it easier for you to search quickly next time.

Related Posts

Solution to SSL failure reported during compilation and installation of python3.10

Package python project into exe and installation package

ImportError: cannot import name ‘Literal‘ from ‘typing‘ (D:\Anaconda\envs\tensorflow\lib\

Selenium practical application – realizing automatic playback of courses on Zhidao wisdom tree

Selenium simulation browser in Python

YOLO series — YOLOV7 algorithm (1): Use a custom data set to run through the YOLOV7 algorithm

Tutorial on creating python virtual environment based on Anaconda under Windows

Based on python and deep learning (speech recognition, NLP) to implement local offline intelligent voice control terminal (with chat function and home control function)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>