example.yml
apis:
# 最精简写法
- url: login # 接口路径
method: POST # 接口方法
defined_data_list: # 在此处定义request与response的匹配关系
[
{
body: { "username": "edison", "password": "123" }, # request body
response: { "code": -1, "msg": "密码输入不正确" } # response body
}
]
pip install easy-mock
启动服务
easy_mock example.yml
调用接口
curl -H "Content-Type: application/json" -X POST 'http://127.0.0.1:9000/login' -d '{"username":"edison", "password": "123"}' | python -m json.tool
$ easy_mock -h
usage: easy_mock [-h] [-v] [-p PORT] [-https] [-req] [-res] file_path
Generate mock service according to the YAML file
positional arguments:
file_path yaml configuration file, directory or .proto file
optional arguments:
-h, --help show this help message and exit
-v, --version show version
-p mock service port
-https enable mock server https protocol
-req generate request_schema in yaml
-res generate response_schema in yaml
在当前目录下新建 python 文件 processor.py
$ touch processor.py
$ vim processor.py
# 函数命名无限制,在yaml指定函数名即可
def xxx_setup(req):
req["username"] = "abc"
return req
def xxx_teardown(req, resp):
resp["age"] = 100
return resp
在 YAML 文件中新增setup
or teardown
字段
apis:
login:
name: 用户登录
desc: 用户登录成功,接口会返回一个token
method: POST
setup: xxxx_setup # 指定前置处理函数名,此函数接受一个参数, 对请求体做前置操作
teardown: xxx_teardown # 指定后置处理函数名,此函数接受两个参数, 对请求体和响应体做后置操作
- url: login # 接口路径
method: POST # 接口方法
request_schema: # (可选)用于对request body做合法性校验
{
"type": "object",
"properties": {
"username": {
"type": "string"
},
"password": {
"type": "string"
},
},
"required": [
"username",
"password"
]
}
response_schema: # (可选) 根据schema生成response随机数据 response_schema 和 defined_data_list 二者不可全为空
{
"type": "object",
"properties": {
"code": {
"type": "integer", # 数据类型
"maximun": 100, # 数据范围 最大
"minimun": 1 # 数据范围 最小
},
"msg": {
"type": "string"
},
"token": {
"type": "string"
},
},
"required": [ # required中的字段,response中必须返回, token字段则随机返回
"code",
"msg"
]
}
defined_data_list: # 定义request与response的匹配关系
[
{
body: { "username": "edison", "password": "123" },
response: { "code": -1, "msg": "密码输入不正确" }
},
{
body: { "password": "123" },
response: { "code": -1, "msg": "用户名是必填的" }
}
]
参数为.proto 文件类型时生成 yaml 文件
easy_mock server.proto -res
输出server.yml