当前位置:网站首页>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()
边栏推荐
- pytest学习--base
- Project practice, redis cluster technology learning (12)
- Blender体积雾
- Sum the two numbers to find the target value
- Leetcode -- the nearest common ancestor of 236 binary tree
- C language: making barrels
- Aiphacode is not a substitute for programmers, but a tool for developers
- Mixed development of uni app -- Taking wechat applet as an example
- Career planning and development
- webUI自动化学习
猜你喜欢
VLAN experiment
allure--常用配置项
Vscode set JSON file to format automatically after saving
Mixed development of uni app -- Taking wechat applet as an example
虛幻AI藍圖基礎筆記(萬字整理)
【JetBrain Rider】构建项目出现异常:未找到导入的项目“D:\VisualStudio2017\IDE\MSBuild\15.0\Bin\Roslyn\Microsoft.CSh
Blender多鏡頭(多機比特)切換
Large neural networks may be beginning to realize: the chief scientist of openai leads to controversy, and everyone quarrels
[Yu Yue education] University Physics (Electromagnetics) reference materials of Taizhou College of science and technology, Nanjing University of Technology
AutoCAD - layer Linetype
随机推荐
【虚幻】自动门蓝图笔记
Introduction and Principle notes of UE4 material
pytest学习--base
pytest框架实现前后置
2021-10-02
Project practice, redis cluster technology learning (12)
Spatial interpretation | comprehensive analysis of spatial structure of primary liver cancer
This article takes you to learn in detail what is fiber to home FTTH
【虚幻】按键开门蓝图笔记
webUI自动化学习
UE illusory engine programmed plant generator setup -- how to quickly generate large forests
阿里云短信服务
虚幻AI蓝图基础笔记(万字整理)
【避坑指南】Unity3D项目接入腾讯Bugly工具时遇到的坑
Network real-time video streaming based on OpenCV
go语言入门
2837xd code generation module learning (3) -- IIC, ECAN, SCI, watchdog, ECAP modules
SAP Spartacus express checkout design
【虚幻】武器插槽:拾取武器
判断数组中是否存在重复元素