Interface automation testing ideas and practical test library framework

Test library framework

  Similar to the Modular Test Scripting Framework and has the same benefits. The difference is that the test library framework decomposes the application under test into procedures and functions instead of scripts (and the test scripts only include use cases that call functions). This framework requires the creation of library files describing the modules, fragments, and functionality of the application under test.

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

For example: The use case is as follows:

Get token --- create a tag.

Get token---create tag---delete the tag you just created

Get token---create tag---query tag to query

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

Step 1. Create a new common_api_info.py file under the common folder, and 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;

Benefits: 1. Easy to maintain. 2. Test case scripts pay more attention to the test process and downplay interface details. 3. Reduce code redundancy

Practical case

Optical theory is useless, you have to learn to follow along, and you have to do it yourself, so that you can apply what you have learned to practice. At this time, you can learn from some actual combat cases.

If it is helpful to you, please like and collect it to give the author an encouragement. It is also convenient for you to quickly find it next time.

If you don’t understand, please consult the small card below. The blogger also hopes to learn and progress with like-minded testers

At the right age, choose the right position, and try to give full play to your own advantages.

My road of automated test development is inseparable from the plan of each stage along the way, because I like planning and summarizing,

Test and develop video tutorials, study notes and receive portals! ! !

Guess you like

Origin blog.csdn.net/Liuyanan990830/article/details/130487359