Python-based interface automation - building mock interface services

introduction

      Mock is simulation. During the test process, for some objects that are not easy to construct or obtain, a virtual object is used to create a test method for testing. Its biggest advantage is to reduce the front-end and back-end coupling, so that front-end
engineers You can develop the front-end style and logic processing without relying on the backend to return data. Simply put: Mock is used to solve dependency problems, and replace complex/unstable/not yet established dependent objects with a simple fake
object .
Mock Server is the Mock interface server, which can be configured to quickly mock out new interfaces.
The scope of use of Mock Server:
front-end and back-end separation projects.
The measured interface depends on the third-party system (not yet available).
The measured interface depends on complex or unstable interfaces. Not as the main verification object
At the same time, when the interface has not yet been developed, providing a mock interface (false interface) will be more intuitive than only interface documents, and can effectively reduce communication costs and some document understanding

     When performing interface testing, the system under test often needs to be connected to a third-party system. However, there is no ready-made third-party system environment. At this time, we need to use mock to solve this dependency, and python provides a mock API that can be conveniently built Interface service module: flask. Flask is a simple and very powerful Python web framework.

It's called a microframework. "Micro" doesn't mean putting an entire web application into a single Python file. The "micro" in microframework means that Flask is designed to keep the code clean and easy to expand. The main features of the Flask framework are The core structure is relatively simple, but it has strong scalability and compatibility. Programmers can use the Python language to quickly implement a website or Web service.

Therefore, flask can easily build a web service and provide web services to external clients, which can also be called clients. According to the characteristics of the flask framework, we can easily build API interfaces for client access.

Flask mock interface development example

First install the required Flask module. If pip is already installed in your environment, type: pip install flask to complete the installation

Or retrieve the installation directly in pycharm:

1.1 Build the interface of the GET request method

Create a new py file in Pycharm and edit the following code

# -*- coding: utf-8 -*-
import flask,json
import time
 
server = flask.Flask(__name__)   # 创建一个服务,把当前这个python文件当做一个服务
 
@server.route('/VIID/System/Time', methods=['get'])  # @server.route()可以将普通函数转变为服务、接口的路径、请求方式,如果不写methods则默认get方法
def Time():
    '''查询字符串:无,消息体:无,返回结果:SystemTime'''
    response_data = {
                "SystemTimeObject": {
                    "VIIDServerID": "123",
                    "TimeMode": "1",          
                    "LocalTime": time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())),
                }
            }
    return json.dumps(response_data, ensure_ascii=False)
 
if __name__ == '__main__':
    server.run(debug=True, port=5000, host='10.82.25.11')  #  指定访问端口、host

 Then run the py file, the file running locally is a web service, just use a browser or postman to try to access the URL of the service

Browser access:

Postman sends a request to access:

After the browser or postman request is completed, the output column of Pycharm will output as follows:

Other requests such as POST, PUT, DELETE and other methods can be specified in the methods parameter, but POST, PUT, DELETE and other methods cannot be directly accessed by the browser, because the default access method of the browser is the get method, which can be specified by postman method to send a request

1.2 Obtain an interface with a request body in json format

Sometimes the request sent by the client is in json format. At this time, it is necessary to obtain the requested json. Edit the code as follows:

@server.route('/data',methods=['post'])
def post_json():
    if flask.request.is_json:
        print(flask.request.json)
        name = flask.request.json.get('name')            # 获取json请求体的第一个参数的值
        age = flask.request.json.get('age')             # 获取json请求体的第二个参数的值
        data = {'name':name,'age':age}
        return json.dumps(data,ensure_ascii=False)
    else:
        return json.dumps({'msg':'请传json格式参数'},ensure_ascii=False)

 Use postman as the client to send a request with a json request body, as shown below:

1.3 Get the parameters sent in the get request

The method provided by flask is:

value = flask.request.args.get('name')           # 获取get请求参数name的值

1.4 Construction of dynamic URL and redirection of response body

In many cases, the url requested by the client changes, that is, with dynamic parameters. Flask can also easily build a url resource service that provides dynamic parameters and redirect the response body. The code is as follows:

# -*- coding: utf-8 -*-
import flask,json
from flask import url_for,redirect
 
server = flask.Flask(__name__)   # 创建一个服务,把当前这个python文件当做一个服务
 
@server.route('/data')
def data():                       #  返回data
    data = {
                'VideoSliceInfoObject': {
                    'VideoID': 'esse elit',
                    'AudioCodeFormat': 'commodo'
                }
    }
    return json.dumps(data, ensure_ascii=False)
 
@server.route('/data/<ID>/Info', methods=['post'])
def data_redirect(ID):
    return redirect(url_for('data', guest=ID))
 
if __name__ == '__main__':
    server.run(debug=True, port=5000, host='10.82.25.11')  #  指定访问端口、host

 Regardless of the ID parameter in the url sent by postman or the client, it can respond

1.5 Rebuild the response header and response status code

Sometimes when docking with a third-party system, it is necessary to return a message carrying a response header and a specified response status code. It is also possible to build a custom response message in flask

# -*- coding: utf-8 -*-
import flask,json
 
server = flask.Flask(__name__)   # 创建一个服务,把当前这个python文件当做一个服务
 
@server.route('/data',methods=['post'])
def post_json():
    if flask.request.is_json:
        print(flask.request.json)
        name = flask.request.json.get('name')            # 获取json请求体的第一个参数的值
        age = flask.request.json.get('age')             # 获取json请求体的第二个参数的值
        data = {'name':name,'age':age}
        # 构建响应头域和状态码
        resp = flask.make_response(json.dumps(data, ensure_ascii=False))
        resp.status = "666"
        resp.headers[
            "python"] = "python flask"
        return resp
    else:
        return json.dumps({'msg':'请传json格式参数'},ensure_ascii=False)
 
if __name__ == '__main__':
    server.run(debug=True, port=5000, host='10.82.25.11')  #  指定访问端口、host

Run the py file, send a request in postman, and view the response information, as shown in the figure below, which becomes the response header and status code of our custom settings

This way we completely customize the headers and status codes of the response

epilogue

This post ends here, and finally, I hope that friends who read this post can gain something.

 How to get free learning tutorials: Leave a message [Python interface automation]

From entry to proficiency [Python + interface automation testing] advanced collection of actual combat projects! !

If you think the article is not bad, please like, share, and leave a message , because this will be the strongest motivation for me to continue to output more high-quality articles!

 

Guess you like

Origin blog.csdn.net/weixin_67553250/article/details/130991431