当前位置:网站首页>Mock Server基本使用方法
Mock Server基本使用方法
2022-07-02 06:36:00 【迷途~知返】
什么是mock server
实现mock功能的一个服务
mock server的作用
现今的业务系统很少有独立存在的,他们或多或少需要使用兄弟团队或者其他公司提供的服务这给我们的联调和测试造成了麻烦
对于这种情况,我们常见的解决方法是搭建一个临时的server,模拟那些服务,因为flask的第三方开源组件丰富
初始Flask
封装功能不及Django完善,性能不及Tomado,但是Flask可拓展性强,因为flask的第三方开源组件丰富
WSGI介绍:
Django使用wsgiref模块
配置文件
app=Flask(name,template_folder=‘templates’,static_url_path=‘/static/’,static_path=‘/zz’)
- 模板路径:template_folder=‘templates’
- 静态文件路径:static_url_path=‘/static/’
- 静态文件引入别名:static_path=‘/zz’
- 设置调试环境:app.debug=True(代码修改自动更新)
- j设置json编码格式如果为False就不使用ascii编码:app.config[‘JSON_AS_ASCII’]=False
- 设置响应头信息:Content-Type app.config[‘JSONIFY_MIMETYPE’]=“application/json;charset=utf-8”
(注意;charset=utf-8)
路由系统
- 动态传参
from flask import Flask
app = Flask(__name__)
# 设置一个动态参数
@app.route('/<name>')
def second_flask(name):
print(name)
return 'Hello World'
【基于flask框架实现Mock Server】
- 根据接口文档,设计Mock Server
- mock server设计-登录
1) 参数为空
2)用户名密码正确
3)用户名密码错误
mockServer它不是一个真实的后端系统,你需要让他满足你的接口的模拟测试需求即可
post方法的基本使用
# coding:utf-8
from flask import Flask, request
# 创建Flask对象
app = Flask(__name__)
# 视图函数
@app.route('/login', methods=['GET', 'POST'])
def request_flask():
"""post请求参数提示"""
# 获取请求数据,返回数据类型为bytes: b'{"username": "zz", "password": "123456"}' <class 'bytes'>
c = request.get_data()
print(c, type(c))
# 获取请求的数据类型,返回为json: {'username': 'zz', 'password': '123456'} <class 'dict'>
d = request.get_json()
print(d, type(d))
# 获取请求的数据类型,返回为bytes: b'{"username": "zz", "password": "123456"}' <class 'bytes'>
e = request.data
print(e, type(e))
# 获取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测试代码
# 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方法数据输出
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基本方法使用
# coding:utf-8
from flask import Flask, request
# 创建Flask对象
app = Flask(__name__)
# 视图函数
@app.route('/login', methods=['GET', 'POST'])
def request_flask():
# get 请求
# 获取指定的key值:zz
h = request.args.get('username')
print(h)
# 获取所有参数的返回值,可以获取get请求的所有参数返回值是immutableMultiDict类型: ImmutableMultiDict([('username', 'zz'), ('password', '123456')])
i = request.args
print(i)
# 将获得的参数转为字典: {'username': 'zz', 'password': '123456'}
j = i.to_dict()
print(j)
# 请求头
""" 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)
# 获取请求的url:http://127.0.0.1:5000/login?username=zz&password=123456
url = request.url
print(url)
# 获取请求方法: GET
method = request.method
print(method)
return 'Hello world'
if __name__ == '__main__':
app.run()
get方法数据输出
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的基本服务搭建
# coding:utf-8
from flask import Flask, request, jsonify
# 创建一个实例
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
# 指定路由和请求方法
@app.route('/api/login', methods=['POST'])
def login():
"""登录接口"""
# 调试信息,打印请求方法
print(request.method)
# 获取请求数据,将数据变为字典
data = request.get_json()
print(data, type(data))
# 定义用户名和密码变量,从data中取值
username = data['username']
pwd = data['password']
""" 测试场景设计: 1) 参数为空 2)用户名密码正确 3) 用户名密码错误 """
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": "登录成功",
"token": "1234567890dfghjkl;"
})
else:
return jsonify({
"code": "001",
"msg": "username or password not fail"
})
@app.route('/api/addcart', methods=['POST']) # 路由到一个指定的接口,和这个接口的请求方法
def add_shop_tocart():
"""添加商品到购物车"""
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": "添加商品到购物车成功"
}
)
elif "productid" != 8888:
return "请选择正确的商品"
# else:
# return jsonify(
# {
# "data": [
# {
# "carid": 45233,
# "openid": "2345678sdfghjkl",
# "price": 30,
# "productid": 9999,
# "userid": 1000
# }
# ],
# "httpstatus": 200,
# "result": "添加商品到购物车成功"
# }
# )
if __name__ == '__main__':
app.run(
host='127.0.0.1',
port=5000,
debug=True
)
测试代码
# 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()
边栏推荐
- 2837xd代码生成模块学习(4)——idle_task、Simulink Coder
- 2837xd code generation module learning (1) -- GPIO module
- Alibaba cloud ack introduction
- Project practice, redis cluster technology learning (16)
- What wires are suitable for wiring on bread board?
- Is the C language too fat
- Large neural networks may be beginning to realize: the chief scientist of openai leads to controversy, and everyone quarrels
- Project practice, redis cluster technology learning (13)
- Message mechanism -- getting to know messages and message queues for the first time
- The primary market project galaxy will conduct public offering on coinlist on February 17
猜你喜欢
ue虛幻引擎程序化植物生成器設置——如何快速生成大片森林
【UE5】动画重定向:如何将幻塔人物导入进游戏玩耍
[unreal] key to open the door blueprint notes
Blender多鏡頭(多機比特)切換
Large neural networks may be beginning to realize: the chief scientist of openai leads to controversy, and everyone quarrels
Application of rxjs operator withlatestfrom in Spartacus UI of SAP e-commerce cloud
2837xd code generation module learning (3) -- IIC, ECAN, SCI, watchdog, ECAP modules
虚幻——动画蓝图、状态机制作人物走跑跳动作
A model can do two things: image annotation and image reading Q & A. VQA accuracy is close to human level | demo can be played
The latest progress and development trend of 2022 intelligent voice technology
随机推荐
Matlab代码生成之SIL/PIL测试
Ctrip starts mixed office. How can small and medium-sized enterprises achieve mixed office?
阿里云Prometheus监控服务
2837xd代码生成模块学习(3)——IIC、eCAN、SCI、Watchdog、eCAP模块
Large neural networks may be beginning to realize: the chief scientist of openai leads to controversy, and everyone quarrels
Project practice, redis cluster technology learning (IX)
Introduction and prevention of penetration test
What is the relationship between realizing page watermarking and mutationobserver?
Configuration programmée du générateur de plantes du moteur illusoire UE - - Comment générer rapidement une grande forêt
Attack and defense world web advanced area unserialize3
How to achieve the top progress bar effect in background management projects
[unreal] animation notes of the scene
In SQL injection, why must the ID of union joint query be equal to 0
Matlab generates DSP program -- official routine learning (6)
Junit4 runs MVN test test suite upgrade scheme
Is the C language too fat
Introduction et prévention des essais de pénétration
Blender多镜头(多机位)切换
Matlab生成dsp程序——官方例程学习(6)
Blender ocean production