当前位置:网站首页>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()
边栏推荐
- How to achieve the top progress bar effect in background management projects
- 2837xd code generation module learning (1) -- GPIO module
- Alibaba cloud Prometheus monitoring service
- [leetcode] sword finger offer 53 - I. find the number I in the sorted array
- MySQL index
- Database -- acid of transaction -- introduction / explanation
- What is call / cc- What is call/cc?
- Eslint reports an error
- ue虛幻引擎程序化植物生成器設置——如何快速生成大片森林
- UE5——AI追逐(藍圖、行為樹)
猜你喜欢
2837xd code generation - stateflow (2)
ue4材质的入门和原理笔记
Blender多鏡頭(多機比特)切換
2837xd代码生成模块学习(3)——IIC、eCAN、SCI、Watchdog、eCAP模块
ue虛幻引擎程序化植物生成器設置——如何快速生成大片森林
2.14 is it Valentine's day or Valentine's day when the mainstream market continues to fluctuate and wait for changes?
Feature (5): how to organize information
Ue5 - ai Pursuit (Blueprint, Behavior tree)
A model can do two things: image annotation and image reading Q & A. VQA accuracy is close to human level | demo can be played
UE4夜间打光笔记
随机推荐
【虚幻】按键开门蓝图笔记
Judging right triangle in C language
Application of rxjs operator withlatestfrom in Spartacus UI of SAP e-commerce cloud
[illusory] weapon slot: pick up weapons
[Yu Yue education] University Physics (Electromagnetics) reference materials of Taizhou College of science and technology, Nanjing University of Technology
ICLR 2022: how does AI recognize "things I haven't seen"?
2837xd代码生成模块学习(4)——idle_task、Simulink Coder
XA Transaction SQL Statements
MySQL transaction
Career planning and development
The road is blocked and long, and the line is coming
[unreal] key to open the door blueprint notes
Edge computing accelerates live video scenes: clearer, smoother, and more real-time
Error reporting on the first day of work (incomplete awvs unloading)
【虚幻4】UMG组件的简介与使用(更新中...)
Bookmark collection management software suspension reading and data migration between knowledge base and browser bookmarks
Binary and decimal system of C language
【避坑指南】使用UGUI遇到的坑:Text组件无法首行缩进两格
ESLint 报错
Leetcode -- the nearest common ancestor of 236 binary tree