当前位置:网站首页>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()
边栏推荐
- [unreal] animation notes of the scene
- 【UE5】AI随机漫游蓝图两种实现方法(角色蓝图、行为树)
- Bugkuctf-web24 (problem solving ideas and steps)
- 2837xd code generation module learning (3) -- IIC, ECAN, SCI, watchdog, ECAP modules
- 【UE5】动画重定向:如何将幻塔人物导入进游戏玩耍
- Project practice, redis cluster technology learning (16)
- 2837xd code generation - Supplement (2)
- ue4材质的入门和原理笔记
- The primary market project galaxy will conduct public offering on coinlist on February 17
- 虛幻AI藍圖基礎筆記(萬字整理)
猜你喜欢

Skywalking理论与实践

Remember the use of add method once

UE5——AI追逐(藍圖、行為樹)

Summary of demand R & D process nodes and key outputs

This monitoring system makes workers tremble: turnover intention and fishing can be monitored. After the dispute, the product page has 404

Skywalking theory and Practice

VLAN experiment

Introduction et prévention des essais de pénétration

Personal experience & blog status

UE4夜间打光笔记
随机推荐
Skywalking theory and Practice
Personal experience & blog status
C language strawberry
Remember the use of add method once
Feature (5): how to organize information
Vscode auto format
Aiphacode is not a substitute for programmers, but a tool for developers
Project practice, redis cluster technology learning (12)
go语言入门
ue虚幻引擎程序化植物生成器设置——如何快速生成大片森林
2837xd code generation module learning (2) -- ADC, epwm module, timer0
[unreal] animation notes of the scene
Project practice, redis cluster technology learning (16)
Project practice, redis cluster technology learning (13)
虚幻——动画蓝图、状态机制作人物走跑跳动作
Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
High level application of SQL statements in MySQL database (II)
What is call / cc- What is call/cc?
Blender海洋制作
Illusion -- Animation blueprint, state machine production, character walking, running and jumping action