Interface automated testing ideas and practice (3): Test library framework

Table of contents

Test library framework

Step 1. Create a new common_api_info.py file in the common folder to encapsulate all api interfaces.

Step 2. Modify the common_function.py file

Step 3. Modify the test_get_access_token_api.py file

Step 4. Modify the test_create_user_tag_api.py file code;

Step 5. Execute the run_api_tests.py file again to execute all use cases;


Test library framework

  It is very similar to the modular test script framework and has the same advantages. The difference is that the test library framework decomposes the application under test into procedures and functions instead of scripts (the test script only contains use cases that call functions). This framework requires the creation of functional library files that describe modules, fragments, and applications under test.

Scenario: In the modular framework, we found that the commonly used token acquisition process is difficult to maintain due to frequent calls and frequent changes, so it is made into a function to call, while all other interfaces may be changed;

For example: The use example is as follows:

Get token---Create tag.

Get token---Create label---Delete the newly created label

Get token---Create tag---Query tag for query

Next, modify the code through the test library framework. The changes are relatively large. It is recommended to copy the project written above to make a backup.

Step 1. Create a new common_api_info.py file in the common folder to encapsulate all api interfaces.

Both method encapsulation and class encapsulation are available

 Write code:

# encoding: utf-8
# @author: Jeffrey
# @file: common_api_info.py
# @time: 2022/7/26 22:05
# @desc: 测试库封装

import json

#该模块存放所有的接口定义及接口信息
class CommonApiInfo:

    def __init__(self,session,hosts):
        self.session = session
        self.hosts = hosts

    def get_access_token_api(self,grant_type,appid,secret):
        """获取token接口信息"""
        url_params = {"grant_type": grant_type,
                      "appid": appid,
                      "secret": secret}
        response = self.session.get(url="https://%s/cgi-bin/token" % self.hosts,
                                    params=url_params)
        return response

    def create_user_tag_info(self,token_value,tag_name):
        '''创建标签接口信息'''
        url_params = {"access_token": token_value}
        tag_info = { "tag": { "name": tag_name } }
        
        tag_str = json.dumps(tag_info, ensure_ascii=False)
        response = self.session.post(url="https://%s/cgi-bin/tags/create" % self.hosts,
                                     params = url_params,
                                     data=tag_str.encode('utf-8'))
        return response

    # 修改标签接口信息
    # 查询标签接口信息

Step 2. Modify the common_function.py file

 Write code:

# encoding: utf-8
# @author: Jeffrey
# @file: common_function.py
# @time: 2022/7/26 21:01
# @desc: 模块化框架
import jsonpath
from common.common_api_info import CommonApiInfo

def get_access_token_value(session_obj,hosts):
    """获取access_token的值"""
    response = CommonApiInfo(session_obj,hosts).get_access_token_api('client_credential',
                                                          'wxf14419077f707856',
                                                          '92a113bd4b5ffdc72144740dc7123c99')
    # 获取响应json中的access_token的值
    token_value = jsonpath.jsonpath(response.json(), "$.access_token")[0]
    return token_value

Step 3. Modify the test_get_access_token_api.py file

 Write code:

# encoding: utf-8
# @author: Jeffrey
# @file: test_get_access_token_api.py
# @time: 2022/7/24 18:08
# @desc:

# 导入模块顺序:内置模块、第三方模块、自定义模块
import unittest
import requests
import jsonpath
from common import local_config
from common.common_api_info import CommonApiInfo

class TestGetAccessTokenApi(unittest.TestCase):

    def setUp(self) -> None:
        self.session = requests.session()
        self.hosts = local_config.HOSTS
    def tearDown(self) -> None:
        self.session.close()

    def test_case_01(self):
        '''[api_case_01] 测试获取access_token能否正常调用'''

        response = CommonApiInfo(self.session,self.hosts).get_access_token_api(
            'client_credential','wxf14419077f707856','92a113bd4b5ffdc72144740dc7123c99'
        )
        # 获取响应json中的access_token的值
        actual_result = jsonpath.jsonpath(response.json(), "$.access_token")


        self.assertTrue(actual_result, "api_case_01 执行失败")  #非空,非0 都返回True为真

    def test_case_02(self):
        '''[api_case_02] 测试获取access_token接口在appid错误时,能否正常处理错误'''

        response = CommonApiInfo(self.session,self.hosts).get_access_token_api(
            'client_credential','wxf14419077f707','92a113bd4b5ffdc72144740dc7123c99'
        )
        # 获取响应json中的errcode的值,因为jsonpath返回的是列表,故加上下标0
        actual_result = jsonpath.jsonpath(response.json(), "$.errcode")[0]

        self.assertEqual(actual_result,40013,  "api_case_02 执行失败")



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

View execution results:

Step 4. Modify the test_create_user_tag_api.py file code;

 Write code:

# encoding: utf-8
# @author: Jeffrey
# @file: test_create_user_tag_api.py
# @time: 2022/7/24 19:02
# @desc:
import unittest
import requests
import jsonpath
import json
from common import common_function
from common import local_config
from common.common_api_info import CommonApiInfo


class TestCreateUserTagApi(unittest.TestCase):

    def setUp(self) -> None:
        self.session = requests.session()
        self.hosts = local_config.HOSTS
    def tearDown(self) -> None:
        self.session.close()

    def test_case_01(self):
        '''[api_case_03] 测试正常进行创建标签接口调用'''
        #获 取access_token
        token_value = common_function.get_access_token_value(self.session,self.hosts)


        # 解决中文乱码问题;模拟post请求时,携带json 数据包含中文发送给服务器会转码
        # 方式一:json.dumps()
        # 获取创建标签接口
        response = CommonApiInfo(self.session,self.hosts).create_user_tag_info(
            token_value,'深圳人5'
        )

        # # 方式二:修改requests中的models.py中的源码,修改完后
        # response = self.session.post(url="https://api.weixin.qq.com/cgi-bin/tags/create",
        #                              params=tag_url_params,
        #                              json=tag_boby)
        # print(response.json())


        # 获取响应json的tag的name值,因为jsonpath返回的是列表,故加上下标0
        actual_result = jsonpath.jsonpath(response.json(), "$.tag.name")[0]


        self.assertEqual(actual_result,"深圳人5", "api_case_03 执行失败")


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

View execution results:

Step 5. Execute the run_api_tests.py file again to execute all use cases;

Advantages: 1. Easy to maintain 2. Test case scripts focus more on the testing process and downplay interface details 3. Reduce code redundancy


The following are relatively good learning tutorial resources that I have collected. Although they are not very valuable, if you happen to need them, you can leave a message in the comment area [777] and just take them away.

Friends who want to get information, please like + comment + collect , three times in a row!

After three consecutive rounds , I will send you private messages one by one in the comment area~

Guess you like

Origin blog.csdn.net/m0_70618214/article/details/133274209