当前位置:网站首页>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()
边栏推荐
- VLAN experiment
- Following nym, the new project Galaxy token announced by coinlist is gal
- ICLR 2022: how does AI recognize "things I haven't seen"?
- 渗透测试的介绍和防范
- Matlab generates DSP program -- official routine learning (6)
- 2021-09-12
- Introduction and Principle notes of UE4 material
- Ue5 - AI pursuit (blueprint, behavior tree)
- Metaclass type and using metaclass to implement model class ORM
- This article takes you to learn in detail what is fiber to home FTTH
猜你喜欢

Alibaba cloud ack introduction

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

阿里云短信服务

【MySQL】连接MySQL时出现异常:Connection must be valid and open

Introduction and Principle notes of UE4 material

High level application of SQL statements in MySQL database (II)

MySQL transaction

Tee command usage example

Illusion -- Animation blueprint, state machine production, character walking, running and jumping action

Ctrip starts mixed office. How can small and medium-sized enterprises achieve mixed office?
随机推荐
Blender多镜头(多机位)切换
2837xd code generation module learning (3) -- IIC, ECAN, SCI, watchdog, ECAP modules
Message mechanism -- getting to know messages and message queues for the first time
JS reduce accumulator
07数据导入Sqoop
Unreal material editor foundation - how to connect a basic material
Following nym, the new project Galaxy token announced by coinlist is gal
What is the relationship between realizing page watermarking and mutationobserver?
Junit4 runs MVN test test suite upgrade scheme
ICLR 2022: how does AI recognize "things I haven't seen"?
pytest框架实现前后置
About the college entrance examination
Project practice, redis cluster technology learning (VIII)
Translation d30 (with AC code POJ 28:sum number)
【教程】如何让VisualStudio的HelpViewer帮助文档独立运行
[ue5] blueprint making simple mine tutorial
Junit5 supports suite methods
Alibaba cloud Prometheus monitoring service
Delivery mode design of Spartacus UI of SAP e-commerce cloud
滲透測試的介紹和防範