当前位置:网站首页>Basic usage of mock server
Basic usage of mock server
2022-07-02 10:23:00 【Lost ~ know to return】
Mock Server
What is? mock server
Realization mock A service of function
mock server The role of
Nowadays, few business systems exist independently , They more or less need to use the services provided by brother teams or other companies, which causes trouble for our joint debugging and testing
In this case , Our common solution is to build a temporary server, Simulate those services , because flask Rich third-party open source components
initial Flask
The packaging function is not as good as Django perfect , The performance is not as good as Tomado, however Flask Strong expandability , because flask Rich third-party open source components
WSGI Introduce :
Django Use wsgiref modular
The configuration file
app=Flask(name,template_folder=‘templates’,static_url_path=‘/static/’,static_path=‘/zz’)
- Template path :template_folder=‘templates’
- Static file path :static_url_path=‘/static/’
- Static files introduce aliases :static_path=‘/zz’
- Set up the debugging environment :app.debug=True( Code changes are automatically updated )
- j Set up json If the encoding format is False Don't use ascii code :app.config[‘JSON_AS_ASCII’]=False
- Set response header information :Content-Type app.config[‘JSONIFY_MIMETYPE’]=“application/json;charset=utf-8”
( Be careful ;charset=utf-8)
Routing system
- Dynamic transfer parameters
from flask import Flask
app = Flask(__name__)
# Set a dynamic parameter
@app.route('/<name>')
def second_flask(name):
print(name)
return 'Hello World'
【 be based on flask Framework implementations Mock Server】

- According to the interface documentation , Design Mock Server
- mock server Design - Sign in
1) The parameter is empty.
2) The username and password are correct
3) Wrong username and password
mockServer It is not a real backend system , You need to make it meet the simulation test requirements of your interface
post Basic use of the method
# coding:utf-8
from flask import Flask, request
# establish Flask object
app = Flask(__name__)
# The view function
@app.route('/login', methods=['GET', 'POST'])
def request_flask():
"""post Request parameter prompt """
# Get request data , The return data type is bytes: b'{"username": "zz", "password": "123456"}' <class 'bytes'>
c = request.get_data()
print(c, type(c))
# Get the requested data type , Return to json: {'username': 'zz', 'password': '123456'} <class 'dict'>
d = request.get_json()
print(d, type(d))
# Get the requested data type , Return to bytes: b'{"username": "zz", "password": "123456"}' <class 'bytes'>
e = request.data
print(e, type(e))
# obtain json: {'username': 'zz', 'password': '123456'} <class 'dict'>
f = request.json
print(f, type(f))
f1 = request.json['username']
print(f1)
return 'Hello world'
if __name__ == '__main__':
app.run()
post Test code
# coding:utf-8
import requests
data = {
'username': 'zz',
'password': '123456'
}
url = 'http://127.0.0.1:5000/login'
resp = requests.post(url=url, json=data)
print(resp)
post Method data output
b'{"username": "zz", "password": "123456"}' <class 'bytes'>
{
'username': 'zz', 'password': '123456'} <class 'dict'>
b'{"username": "zz", "password": "123456"}' <class 'bytes'>
{
'username': 'zz', 'password': '123456'} <class 'dict'>
zz
get Use the basic method
# coding:utf-8
from flask import Flask, request
# establish Flask object
app = Flask(__name__)
# The view function
@app.route('/login', methods=['GET', 'POST'])
def request_flask():
# get request
# Get the specified key value :zz
h = request.args.get('username')
print(h)
# Get the return values of all parameters , Can get get The return values of all the requested parameters are immutableMultiDict type : ImmutableMultiDict([('username', 'zz'), ('password', '123456')])
i = request.args
print(i)
# Turn the obtained parameters into dictionaries : {'username': 'zz', 'password': '123456'}
j = i.to_dict()
print(j)
# Request header
""" Host: 127.0.0.1:5000 User-Agent: python-requests/2.27.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive """
head = request.headers
print(head)
# Obtain requested url:http://127.0.0.1:5000/login?username=zz&password=123456
url = request.url
print(url)
# Get request method : GET
method = request.method
print(method)
return 'Hello world'
if __name__ == '__main__':
app.run()
get Method data output
zz
ImmutableMultiDict([('username', 'zz'), ('password', '123456')])
{
'username': 'zz', 'password': '123456'}
Host: 127.0.0.1:5000
User-Agent: python-requests/2.27.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
http://127.0.0.1:5000/login?username=zz&password=123456
GET
mock server Basic service construction
# coding:utf-8
from flask import Flask, request, jsonify
# Create an instance
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
# Specify routing and request methods
@app.route('/api/login', methods=['POST'])
def login():
""" Login interface """
# Debugging information , Print request method
print(request.method)
# Get request data , Turn data into a dictionary
data = request.get_json()
print(data, type(data))
# Define user name and password variables , from data The value of
username = data['username']
pwd = data['password']
""" Test scenario design : 1) The parameter is empty. 2) The username and password are correct 3) Wrong username and password """
if username == '' and pwd == '':
""" """
return jsonify({
"code": "001", "msg": "username or password can not null"})
elif username == 'qb_10' and pwd == '[email protected]*':
return jsonify({
"address": {
"city": "changsha"
},
"httpstatus": 200,
"info": {
"age": 19,
"name": "zz"
},
"msg": " Login successful ",
"token": "1234567890dfghjkl;"
})
else:
return jsonify({
"code": "001",
"msg": "username or password not fail"
})
@app.route('/api/addcart', methods=['POST']) # Route to a specified interface , And the request method of this interface
def add_shop_tocart():
""" Add items to cart """
data_base = request.get_data()
print(data_base, type(data_base))
data = request.get_json()
productid = data['productid']
if productid == '':
return "please choose shop"
elif productid == 8888:
return jsonify(
{
"data": [
{
"carid": 45233,
"openid": "2345678sdfghjkl",
"price": 30,
"productid": 9999,
"userid": 1000
}
],
"httpstatus": 200,
"result": " Adding goods to shopping cart succeeded "
}
)
elif "productid" != 8888:
return " Please choose the right product "
# else:
# return jsonify(
# {
# "data": [
# {
# "carid": 45233,
# "openid": "2345678sdfghjkl",
# "price": 30,
# "productid": 9999,
# "userid": 1000
# }
# ],
# "httpstatus": 200,
# "result": " Adding goods to shopping cart succeeded "
# }
# )
if __name__ == '__main__':
app.run(
host='127.0.0.1',
port=5000,
debug=True
)
Test code
# coding:utf-8
import json
import pytest
import requests
class TestDemo:
"""Test Demo"""
def test_login(self):
data = {
'username': 'qb_10',
'password': '[email protected]*'
}
url = 'http://127.0.0.1:5000/api/login'
resp = requests.post(url=url, json=data)
print(resp)
print(resp.text)
def test_add_cart(self):
data = {
"openid": "2345678sdfghjkl",
"productid": '',
"userid": 1000
}
url = 'http://127.0.0.1:5000/api/addcart'
resp = requests.post(url=url, json=data)
print(resp)
print(resp.text)
if __name__ == '__main__':
pytest.main()
边栏推荐
- go语言入门
- Translation d30 (with AC code POJ 28:sum number)
- What wires are suitable for wiring on bread board?
- What is the relationship between realizing page watermarking and mutationobserver?
- Tee command usage example
- 【MySQL】连接MySQL时出现异常:Connection must be valid and open
- [Yu Yue education] University Physics (Electromagnetics) reference materials of Taizhou College of science and technology, Nanjing University of Technology
- MySQL index
- Blender体积雾
- Sum the two numbers to find the target value
猜你喜欢

Blender ocean production

Mysql索引

Blender multi lens (multi stand) switching

【虚幻4】从U3D到UE4的转型之路

pytest--之测试报告allure配置

Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer

How to judge the quality of primary market projects when the market is depressed?

Network real-time video streaming based on OpenCV
What is the relationship between realizing page watermarking and mutationobserver?

Mock Server基本使用方法
随机推荐
2021-10-02
This monitoring system makes workers tremble: turnover intention and fishing can be monitored. After the dispute, the product page has 404
ERROR 1118 (42000): Row size too large (&gt; 8126)
Blender volume fog
Nonlinear optimization: establishment of slam model
Unreal material editor foundation - how to connect a basic material
MPLS experiment
How much is it to develop a system software in Beijing, and what funds are needed to develop the software
Introduction and prevention of penetration test
Understand the composition of building energy-saving system
Edge computing accelerates live video scenes: clearer, smoother, and more real-time
【虚幻】过场动画笔记
虚幻AI蓝图基础笔记(万字整理)
Career planning and development
【虚幻】武器插槽:拾取武器
UE5——AI追逐(蓝图、行为树)
【UE5】动画重定向:如何将幻塔人物导入进游戏玩耍
Mock Server基本使用方法
webUI自动化学习
Junit4 runs MVN test test suite upgrade scheme