pytest-auto-api2 接口自动化测试框架 — 架构全景解析
一个零代码、YAML 驱动的接口自动化测试框架,基于 Python + pytest + Allure + MySQL + 多通道通知实现。
项目地址:https://gitee.com/yu_xiao_qi/pytest-auto-api2
作者:余少琪 | 技术邮箱:1603453211@qq.com | 博客:https://blog.csdn.net/weixin_43865008
目录
一、框架概述
本框架的核心理念是 「测试人员只需在 YAML 文件中描述测试用例,无需编写一行 Python 代码」。框架会自动将 YAML 转换为 pytest 测试代码,执行接口请求、处理多接口依赖、执行断言、生成 Allure 报告,并通过钉钉/企业微信/飞书/邮箱发送通知。
框架核心能力一览
二、项目目录结构
pytest-auto-api2/
│
├── common/ # 公共配置
│ ├── config.yaml # 全局配置(域名、数据库、通知、镜像源等)
│ └── setting.py # 路径工具类(root_path、ensure_path_sep)
│
├── data/ # 测试用例数据(YAML)
│ ├── Login/login.yaml # 登录模块用例
│ ├── Collect/ # 收藏模块用例(增删改查)
│ │ ├── collect_addtool.yaml
│ │ ├── collect_delete_tool.yaml
│ │ ├── collect_tool_list.yaml
│ │ └── collect_update_tool.yaml
│ └── UserInfo/get_user_info.yaml # 用户信息用例
│
├── test_case/ # 自动生成的 pytest 测试代码
│ ├── conftest.py # pytest 全局 fixture 和 hooks
│ ├── Login/test_login.py
│ ├── Collect/
│ │ ├── test_collect_addtool.py
│ │ ├── test_collect_delete_tool.py
│ │ ├── test_collect_tool_list.py
│ │ └── test_collect_update_tool.py
│ └── UserInfo/test_get_user_info.py
│
├── utils/ # 核心工具库(框架的心脏)
│ ├── __init__.py # 全局配置对象 config 的初始化入口
│ │
│ ├── assertion/ # 断言层
│ │ ├── assert_control.py # Assert + AssertUtil 多断言引擎
│ │ └── assert_type.py # 13 种断言方法的具体实现
│ │
│ ├── cache_process/ # 缓存层
│ │ ├── cache_control.py # Cache(文件缓存)+ CacheHandler(内存缓存)
│ │ └── redis_control.py # Redis 缓存支持(可选)
│ │
│ ├── logging_tool/ # 日志层
│ │ ├── log_control.py # 日志配置与控制
│ │ ├── log_decorator.py # 请求日志装饰器
│ │ └── run_time_decorator.py # 执行时长统计装饰器
│ │
│ ├── mysql_tool/ # 数据库层
│ │ └── mysql_control.py # MySQL 连接 + SQL 执行 + 断言数据提取
│ │
│ ├── notify/ # 通知层
│ │ ├── ding_talk.py # 钉钉机器人通知
│ │ ├── wechat_send.py # 企业微信通知
│ │ ├── send_mail.py # 邮件通知
│ │ └── lark.py # 飞书通知
│ │
│ ├── other_tools/ # 辅助工具
│ │ ├── models.py # 所有数据模型(TestCase、ResponseData、枚举等)
│ │ ├── exceptions.py # 自定义异常
│ │ ├── jsonpath_date_replace.py # jsonpath 动态替换引擎
│ │ ├── thread_tool.py # 多线程工具
│ │ └── allure_data/ # Allure 报告数据处理
│ │
│ ├── read_files_tools/ # 文件读写与 YAML 解析
│ │ ├── yaml_control.py # YAML 读取/写入
│ │ ├── get_yaml_data_analysis.py # YAML → TestCase 转换 + 字段校验
│ │ ├── case_automatic_control.py # 自动生成 pytest 测试代码
│ │ ├── testcase_template.py # 测试代码模板引擎
│ │ ├── regular_control.py # 动态变量替换引擎(${{...}} 语法)
│ │ ├── get_all_files_path.py # 递归获取所有 YAML 文件
│ │ ├── excel_control.py # Excel 用例转换
│ │ ├── swagger_for_yaml.py # Swagger → YAML 转换
│ │ └── clean_files.py # 文件清理工具
│ │
│ ├── requests_tool/ # 请求层(核心)
│ │ ├── request_control.py # RequestControl — HTTP 请求总控
│ │ ├── dependent_case.py # DependentCase — 多接口依赖处理
│ │ ├── set_current_request_cache.py # 请求/响应数据写入缓存
│ │ ├── teardown_control.py # TearDownHandler — 后置请求+SQL处理
│ │ └── encryption_algorithm_control.py # 加解密算法
│ │
│ ├── recording/ # 代理录制
│ │ └── mitmproxy_control.py # mitmproxy 拦截生成 YAML
│ │
│ └── times_tool/ # 时间工具
│ └── time_control.py
│
├── Files/ # 上传文件接口所需的文件 + 文档图片
├── logs/ # 日志输出目录
├── report/ # Allure 报告输出(自动生成)
├── run.py # 主入口程序
├── pytest.ini # pytest 配置
├── requirements.txt # Python 依赖(约 90 个包)
└── README.md # 项目文档
三、核心技术栈
四、核心架构设计
4.1 整体架构图
┌─────────────┐
│ run.py │
│ (主入口) │
└──────┬──────┘
│
┌────────────────────────┼────────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────┐ ┌─────────────────┐ ┌──────────────┐
│ 用例代码生成 │ │ pytest 执行引擎 │ │ 通知分发 │
│ (可选) │ │ conftest.py │ │ 钉钉/企微/ │
│ YAML→.py │ └───────┬─────────┘ │ 飞书/邮件 │
└───────────┘ │ └──────────────┘
│
┌───────────────────┼───────────────────┐
▼ ▼ ▼
┌──────────────┐ ┌──────────────────┐ ┌────────────────┐
│ RequestControl│ │ DependentCase │ │ TearDownHandler │
│ 请求发送引擎 │ │ 依赖处理引擎 │ │ 后置处理引擎 │
└──────┬───────┘ └────────┬─────────┘ └────────────────┘
│ │
└──────┬───────────┘
▼
┌────────────────┐
│ Assert 引擎 │
│ 响应断言+SQL断言 │
└────────────────┘
4.2 设计模式应用
五、模块分层详解
5.1 配置层
所在位置: common/ + utils/__init__.py + utils/other_tools/models.py::Config
框架的配置入口在 utils/__init__.py,它在模块加载时自动执行一次,解析 config.yaml 并实例化为全局可用的 Config 对象:
# utils/__init__.py
from utils.read_files_tools.yaml_control import GetYamlData
from common.setting import ensure_path_sep
from utils.other_tools.models import Config
_data = GetYamlData(ensure_path_sep("\\common\\config.yaml")).get_yaml_data()
config = Config(**_data) # ← 全局配置对象,所有模块通过 from utils import config 引用
路径工具 setting.py 提供两个关键函数:
root_path()— 获取项目根目录的绝对路径ensure_path_sep(path)— 将路径中的/和\统一为当前操作系统的分隔符,确保跨平台兼容
5.2 数据模型层
所在位置: utils/other_tools/models.py
框架使用 pydantic BaseModel + Python dataclass + Enum 构建了完整的类型安全体系,约 270 行定义了 20+ 个模型。
核心模型:TestCase
这是 YAML 用例解析后的标准数据结构,是框架内部流通的统一格式:
请求类型枚举:RequestType
class RequestType(Enum):
JSON = "JSON" # → requests.post(url, json=data)
PARAMS = "PARAMS" # → requests.get(url, params=data)
DATA = "DATA" # → requests.post(url, data=data)
FILE = "FILE" # → MultipartEncoder 上传文件
EXPORT = "EXPORT" # → 文件流式下载
NONE = "NONE" # → 无请求体
断言方法枚举:AssertMethod
class AssertMethod(Enum):
equals = "==" # 相等
less_than = "lt" # 小于
less_than_or_equals = "le" # 小于等于
greater_than = "gt" # 大于
greater_than_or_equals = "ge" # 大于等于
not_equals = "not_eq" # 不等于
string_equals = "str_eq" # 字符串相等
length_equals = "len_eq" # 长度相等
length_greater_than = "len_gt" # 长度大于
length_greater_than_or_equals = 'len_ge' # 长度大于等于
length_less_than = "len_lt" # 长度小于
length_less_than_or_equals = 'len_le' # 长度小于等于
contains = "contains" # 包含
contained_by = 'contained_by' # 被包含
startswith = 'startswith' # 以...开头
endswith = 'endswith' # 以...结尾
5.3 YAML 解析与校验层
所在位置: utils/read_files_tools/
这一层负责将原始的 YAML 文件转换为 Python 可以操作的结构化数据。核心调用链如下:
YAML 文件
│
▼
GetYamlData(file_path).get_yaml_data()
│ ← yaml_control.py:使用 PyYAML 的 yaml.load() 读取
│
▼
CaseDataCheck.check_params_exit()
│ ← get_yaml_data_analysis.py
│ 遍历 TestCaseEnum 中标记为必填的字段,
│ 逐字段 assert 校验是否存在
│
▼
CaseData.case_process()
│ 将校验通过的 YAML 数据转换为 TestCase pydantic 对象
│ 处理 host+url 拼接、枚举值转换、sql 开关判断等
│ 返回 dict 列表(每个元素是已格式化的用例数据)
│
▼
CacheHandler.update_cache(case_id, data)
│ 以 case_id 为 key,写入内存缓存
│ 供后续 GetTestCase.case_data() 读取
│
▼
TestCaseAutomaticGeneration.get_case_automatic()
│ ← case_automatic_control.py
│ 扫描 data/ 目录下的所有 YAML,
│ 为每个 YAML 文件生成对应的 test_case/*.py
│
▼
write_testcase_file()
│ ← testcase_template.py
│ 根据 real_time_update_test_cases 配置决定:
│ True → 每次运行都覆盖生成
│ False → 仅当 .py 文件不存在时才生成
字段校验的核心逻辑:
class TestCaseEnum(Enum):
URL = ("url", True) # (字段名, 是否必填)
HOST = ("host", True)
METHOD = ("method", True)
# ... 共 16 个字段,含必填和可选 ...
def check_params_exit(self):
for enum in list(TestCaseEnum._value2member_map_.keys()):
if enum[1]: # if required is True
self._assert(enum[0])
def _assert(self, attr):
assert attr in self.case_data.keys(), (
f"用例ID为 {self.case_id} 的用例中缺少 {attr} 参数,"
f"请确认用例内容是否编写规范。"
)
5.4 请求控制层
所在位置: utils/requests_tool/
这是框架最复杂的模块,包含 5 个类,约 1000 行代码。
RequestControl — HTTP 请求引擎
http_request() 的完整执行流程:
┌────────────────────────────────────────────────────────────────┐
│ RequestControl.http_request() │
├────────────────────────────────────────────────────────────────┤
│ 1. 解析请求类型 → 获取对应的 requests 调用方式 │
│ requests_type_mapping = { │
│ JSON: lambda: requests.request(method, url, json=data) │
│ PARAMS: lambda: requests.request(method, url, params=data) │
│ DATA: lambda: requests.request(method, url, data=data) │
│ FILE: lambda: requests.request(method, url, files=data) │
│ EXPORT: lambda: requests.request(method, url, data=data) │
│ } │
│ │
│ 2. 预处理 headers:空值处理、int→str 类型兼容 │
│ │
│ 3. 处理上传文件:兼容 data+file 混合参数 │
│ 使用 MultipartEncoder 处理 multipart/form-data │
│ │
│ 4. 判断用例是否执行:is_run 为 False 则跳过 │
│ │
│ 5. 处理数据依赖(如果开启): │
│ if dependence_case: DependentCase().get_dependent_data() │
│ │
│ 6. 发送 HTTP 请求 │
│ res = requests_type_mapping[requestType](...) │
│ │
│ 7. 可选等待: │
│ if self.__yaml_case.sleep: time.sleep(sleep) │
│ │
│ 8. 后置处理: │
│ TearDownHandler().teardown_handle() │
│ ├── teardown 请求(清理数据) │
│ └── teardown_sql(清理数据库) │
│ │
│ 9. 断言检查: │
│ Assert().assert_type_handle() │
│ ├── status_code 断言 │
│ └── 多断言遍历(响应/SQL/请求来源) │
│ │
│ 10. Allure 报告记录: │
│ allure_step() / allure_attach() │
│ 记录 url / headers / method / data / assert / response │
│ │
│ 11. 缓存当前请求数据: │
│ SetCurrentRequestCache().set_caches_main() │
│ type=response → 缓存当前响应 │
│ type=request → 缓存当前请求参数 │
│ │
│ 12. 返回 ResponseData 对象 │
└────────────────────────────────────────────────────────────────┘
DependentCase — 多接口依赖引擎
get_dependent_data() 执行流程:
┌──────────────────────────────────────────────────────────┐
│ 1. 判断 dependence_case 是否为 True │
│ │
│ 2. 遍历 dependence_case_data 列表 │
│ 每组包含:case_id, dependent_type, jsonpath, │
│ replace_key, set_cache │
│ │
│ 3. 根据 dependent_type 从缓存获取数据源: │
│ ├── "response" → 读取前置接口的响应 │
│ ├── "request" → 读取前置接口的请求参数 │
│ └── "sql" → 读取前置接口的 SQL 查询结果 │
│ │
│ 4. 通过 jsonpath 从数据源中提取具体字段值: │
│ jsonpath_data = jsonpath(source_data, "$.data.token") │
│ │
│ 5. 通过 jsonpath_replace + exec 动态替换目标字段: │
│ replace_key = "$.data.token" │
│ → yaml_case.data.token = '实际提取到的token值' │
│ → exec(代码字符串) 在运行时动态修改当前对象 │
│ │
│ 6. 如果设置了 set_cache,将提取值写入缓存: │
│ CacheHandler.update_cache(cache_name, value) │
└──────────────────────────────────────────────────────────┘
TearDownHandler — 后置处理引擎
请求完成后执行清理操作,支持三种模式:
5.5 断言系统
所在位置: utils/assertion/
架构设计
采用 双类继承 结构:
AssertUtil(基类)
│ 属性:assert_data, sql_data, request_data, response_data, status_code
│ 方法:assert_type_handle() — 根据 AssertType 分发断言
│ _assert() — 调用具体的断言函数
│
└─ Assert(子类,外部调用的入口)
│ 方法:assert_data_list() — 拆出 status_code 和普通断言
│ assert_type_handle() — 遍历所有断言,逐条调父类方法
三种断言来源
断言执行流程
def assert_type_handle(self):
if self.get_assert_type == "R_SQL":
self._assert(
self._assert_request_data, # 从请求参数 jsonpath 提取
self.get_sql_data, # 从 SQL 结果提取
self.get_message
)
elif self.get_assert_type in ("SQL", "D_SQL"):
self._assert(
self._assert_resp_data, # 从响应 JSON 提取
self.get_sql_data, # 从 SQL 结果提取
self.get_message
)
elif self.get_assert_type is None:
self._assert(
self._assert_resp_data, # 从响应 JSON 提取
self.get_value, # 直接从 YAML 读期望值
self.get_message
)
5.6 缓存系统
所在位置: utils/cache_process/
两层缓存架构
缓存数据流全景
conftest.py (session fixture, autouse)
│
│ 登录获取 cookie
▼
CacheHandler.update_cache(
cache_name="login_cookie",
value="JSESSIONID=xxx;..."
)
│
│ YAML 用例中引用
▼
collect_addtool.yaml:
headers:
cookie: $cache{login_cookie}
│
│ cache_regular() 解析
▼
headers["cookie"] = "JSESSIONID=xxx;..."
│
│ 请求完成后
▼
SetCurrentRequestCache.set_caches_main()
type: response, jsonpath: $.data.id, name: new_tool_id
│
▼
CacheHandler.update_cache(
cache_name="new_tool_id",
value=12345
)
│
│ 后续接口(或 teardown)中引用
▼
collect_delete_tool.yaml:
data:
id: $cache{new_tool_id}
5.7 动态变量引擎
所在位置: utils/read_files_tools/regular_control.py
模板语法
框架支持两种动态变量语法:
内置函数一览(15+)
正则替换引擎的核心实现
def regular(target):
"""使用正则替换请求数据中的 ${{...}} 模板"""
regular_pattern = r'\${{(.*?)}}'
while re.findall(regular_pattern, target):
key = re.search(regular_pattern, target).group(1)
value_types = ['int:', 'bool:', 'list:', 'dict:', 'tuple:', 'float:']
if any(i in key for i in value_types):
func_name = key.split(":")[1].split("(")[0]
value_name = key.split(":")[1].split("(")[1][:-1]
value_data = getattr(Context(), func_name)(*args)
# 类型标注时去掉外层引号
target = re.sub(r'\'\${{(.*?)}}\'', str(value_data), target, 1)
else:
func_name = key.split("(")[0]
value_data = getattr(Context(), func_name)(*args)
target = re.sub(regular_pattern, str(value_data), target, 1)
return target
5.8 通知系统
所在位置: utils/notify/
策略分发
# run.py
notification_mapping = {
NotificationType.DING_TALK.value: DingTalkSendMsg(allure_data).send_ding_notification,
NotificationType.WECHAT.value: WeChatSend(allure_data).send_wechat_notification,
NotificationType.EMAIL.value: SendEmail(allure_data).send_main,
NotificationType.FEI_SHU.value: FeiShuTalkChatBot(allure_data).post
}
# 支持多通道并行!逗号分隔即可
if config.notification_type != NotificationType.DEFAULT.value:
notify_type = config.notification_type.split(",")
for i in notify_type:
notification_mapping.get(i.lstrip(""))()
5.9 pytest 集成层
所在位置: test_case/conftest.py
六、核心调用链路
6.1 完整执行流程
run.py → 启动
│
├─ 1. 打印启动 Banner + 项目名称
│
├─ 2. (可选) 自动生成测试代码
│ TestCaseAutomaticGeneration().get_case_automatic()
│ 扫描 data/ → 生成 test_case/*.py
│
├─ 3. pytest.main(['-s', '--alluredir ./report/tmp'])
│ │
│ ├─ conftest.py 钩子加载
│ │ ├─ clear_report (session) → 清理报告
│ │ ├─ work_login_init (session, autouse) → 登录
│ │ └─ pytest_collection_modifyitems → 排序
│ │
│ ├─ 收集 test_case/ 下的用例
│ │
│ └─ 对每条参数化用例:
│ ├─ case_skip fixture → 检查 is_run
│ ├─ GetTestCase.case_data() → 从缓存拿数据
│ ├─ regular() → 替换动态变量
│ ├─ RequestControl(http_request)
│ │ ├─ 替换 ${{}} + $cache{}
│ │ ├─ 依赖处理 → DependentCase
│ │ ├─ 发送 HTTP 请求
│ │ ├─ TearDownHandler → 后置清理
│ │ ├─ Allure 记录
│ │ └─ SetCurrentRequestCache → 写入缓存
│ └─ Assert().assert_type_handle()
│ └─ 遍历断言 → jsonpath提取 → 类型比较
│
├─ 4. allure generate → 生成 HTML 报告
│
├─ 5. 通知分发(根据 notification_type 配置)
│
├─ 6. (可选) Excel 失败用例报告
│
└─ 7. allure serve -h 127.0.0.1 -p 9999 → 自动打开报告
七、配置系统
所有外部配置集中在 common/config.yaml 中:
# --- 基础配置 ---
project_name: xxx项目名称
env: 测试环境
tester_name: 七月
# --- 域名 ---
host: https://www.wanandroid.com # 主域名,${{host()}} 获取
app_host: # 备用域名
# --- 代码自动生成 ---
real_time_update_test_cases: False # True: 每次覆盖生成;False: 仅首次
# --- 通知 ---
notification_type: 0 # 0=不发送 1=钉钉 2=企微 3=邮件 4=飞书,逗号分隔多通道
excel_report: False
# --- 钉钉 ---
ding_talk:
webhook: https://oapi.dingtalk.com/robot/send?access_token=xxx
secret: SECxxxxxx
# --- MySQL ---
mysql_db:
switch: False
host:
user: root
password: '123456'
port: 3306
# --- 企业微信 ---
wechat:
webhook: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx
# --- 邮箱 ---
email:
send_user:
email_host: smtp.qq.com
stamp_key:
send_list:
# --- 飞书 ---
lark:
webhook:
八、YAML 用例规范
完整结构模板
# ========== 公共配置(每个 YAML 文件有且只有一个)==========
case_common:
allureEpic: 项目名称 # 【必填】
allureFeature: 模块名称 # 【必填】
allureStory: 接口名称 # 【必填】
# ========== 用例主体(可以有 N 个)==========
{case_id}:
host: ${{host()}} # 【必填】
url: /api/path # 【必填】
method: POST # 【必填】
detail: 用例描述 # 【必填】
headers: # 【必填可为空】
cookie: $cache{login_cookie}
requestType: JSON # 【必填】
is_run: # 【必填】空或true=执行
sleep: 0.5 # 【可选】
data: # 【必填可为空】
username: test
password: '123456'
# --- 接口依赖 ---
dependence_case: False # 【必填】
dependence_case_data: # 【依赖开启时必填】
- case_id: login_01
dependent_type: response # response/request/sql
jsonpath: $.data.token
replace_key: $.data.token
set_cache: login_token # 【可选】
# --- 断言 ---
assert: # 【必填】
{断言名称}:
jsonpath: $.errorCode
type: ==
value: 0
AssertType: # 空/None=响应 SQL=数据库
message: "错误码必须为 0" # 【可选】
# --- 数据库 ---
sql: # 【可选】
- SELECT count(*) FROM users
# --- 前后置 ---
setup_sql: # 【可选】
- INSERT INTO users VALUES (1, 'test')
teardown: # 【可选】
- case_id: delete_01
send_request:
- dependent_type: response
jsonpath: $.data.id
replace_key: $.data.id
teardown_sql: # 【可选】
- DELETE FROM users WHERE id = $json($.data.id)$
# --- 缓存当前请求/响应 ---
current_request_set_cache: # 【可选】
- type: response
jsonpath: $.data.id
name: new_tool_id
九、使用 Demo 合集
Demo 1:最简 GET 请求
YAML 用例 data/UserInfo/get_user_info.yaml:
case_common:
allureEpic: 开发平台接口
allureFeature: 用户模块
allureStory: 获取用户信息
get_user_info_01:
host: ${{host()}}
url: /user/lg/userinfo/json
method: GET
detail: 正常获取用户信息
headers:
cookie: $cache{login_cookie} # ← 引用登录 cookie
requestType: PARAMS
is_run:
data:
dependence_case: False
dependence_case_data:
assert:
errorCode:
jsonpath: $.errorCode
type: ==
value: 0
AssertType:
username:
jsonpath: $.data.username
type: ==
value: '18800000001'
AssertType:
sql:
自动生成的 pytest 代码 test_case/UserInfo/test_get_user_info.py:
import allure
import pytest
from utils.read_files_tools.get_yaml_data_analysis import GetTestCase
from utils.assertion.assert_control import Assert
from utils.requests_tool.request_control import RequestControl
from utils.read_files_tools.regular_control import regular
from utils.requests_tool.teardown_control import TearDownHandler
case_id = ['get_user_info_01']
TestData = GetTestCase.case_data(case_id)
re_data = regular(str(TestData))
@allure.epic("开发平台接口")
@allure.feature("用户模块")
class TestGetUserInfo:
@allure.story("获取用户信息")
@pytest.mark.parametrize('in_data', eval(re_data), ids=[i['detail'] for i in TestData])
def test_get_user_info(self, in_data, case_skip):
res = RequestControl(in_data).http_request()
TearDownHandler(res).teardown_handle()
Assert(
assert_data=in_data['assert_data'],
sql_data=res.sql_data,
request_data=res.body,
response_data=res.response_data,
status_code=res.status_code
).assert_type_handle()
Demo 2:POST 请求 + 多断言
login_01:
host: ${{host()}}
url: /user/login
method: POST
detail: 正常登录
requestType: data
data:
username: '18800000001'
password: '123456'
dependence_case: False
dependence_case_data:
assert:
status_code: 200 # HTTP 状态码断言
errorCode: # 断言 1
jsonpath: $.errorCode
type: ==
value: 0
AssertType:
username: # 断言 2
jsonpath: $.data.username
type: ==
value: '18800000001'
AssertType:
nickname: # 断言 3: contains
jsonpath: $.data.nickname
type: contains
value: '18800000001'
AssertType:
sql:
Demo 3:多接口依赖(A接口结果 → B接口参数)
场景: 新增收藏 → 后置自动清理
YAML 用例 data/Collect/collect_addtool.yaml:
collect_addtool_01:
host: ${{host()}}
url: /lg/collect/addtool/json
method: POST
detail: 新增收藏网址
headers:
cookie: $cache{login_cookie}
requestType: data
data:
name: 自动化框架
link: https://gitee.com/yu_xiao_qi/pytest-auto-api2
dependence_case: False
dependence_case_data:
assert:
errorCode:
jsonpath: $.errorCode
type: ==
value: 0
AssertType:
message: "errorCode 必须为 0"
# ★★★ 关键:将响应的 data.id 存入缓存 ★★★
current_request_set_cache:
- type: response
jsonpath: $.data.id
name: new_tool_id
# ★★★ 关键:后置请求 — 自动调用删除接口清理数据 ★★★
teardown:
- case_id: collect_delete_tool_01
send_request:
- dependent_type: response
jsonpath: $.data.id
replace_key: $.data.id
teardown_sql:
- DELETE FROM collection WHERE id = $json($.data.id)$
数据流动过程:
collect_addtool_01 发起 POST 请求
│ 响应: {"data": {"id": 12345, ...}, "errorCode": 0}
▼
SetCurrentRequestCache → 缓存响应中的 $.data.id = 12345
│ cache_name: new_tool_id
▼
TearDownHandler → 读取 collect_delete_tool_01 的 YAML
│ 将响应 id=12345 替换到删除接口的 data.id
▼
发送 collect_delete_tool_01: POST data={"id": 12345}
│ 删除成功
▼
执行 teardown_sql: DELETE FROM collection WHERE id = 12345
Demo 4:数据库断言
sql_assert_demo:
host: ${{host()}}
url: /user/register
method: POST
detail: 注册用户 + 验证数据库写入正确
requestType: JSON
data:
username: "test_${{random_int()}}"
password: "123456"
dependence_case: False
dependence_case_data:
assert:
errorCode:
jsonpath: $.errorCode
type: ==
value: 0
AssertType:
# ★★★ 数据库断言:响应中的 userId 与数据库中的 id 对应 ★★★
user_id_check:
jsonpath: $.data.userId
type: ==
value: $.data.userId
AssertType: SQL # ← 标记为数据库断言
sql:
- SELECT id FROM users WHERE username = 'test_user'
Demo 5:动态数据 + 类型标注
random_data_demo:
host: ${{host()}}
url: /user/register
method: POST
detail: 使用随机数据注册用户
requestType: JSON
data:
username: "user_${{random_int()}}" # user_1234
phone: '${{get_phone()}}' # 18812345678
email: '${{get_email()}}' # test@example.com
name: '${{get_female_name()}}' # 张三
birthday: '${{today_date()}}' # 2024-01-15 00:00:00
id_card: '${{get_id_number()}}' # 110101199001011234
id: '${{int:random_int()}}' # 1234(无引号)
is_vip: '${{bool:False}}' # False(布尔)
dependence_case: False
dependence_case_data:
assert:
errorCode:
jsonpath: $.errorCode
type: ==
value: 0
AssertType:
sql:
Demo 6:后置 SQL 清理数据
collect_addtool_01:
host: ${{host()}}
url: /lg/collect/addtool/json
method: POST
detail: 新增收藏 + 后置数据库清理
headers:
cookie: $cache{login_cookie}
requestType: data
data:
name: "博客文章 ${{random_int()}}"
link: https://blog.csdn.net/weixin_43865008
dependence_case: False
dependence_case_data:
assert:
errorCode:
jsonpath: $.errorCode
type: ==
value: 0
AssertType:
sql:
# ★★★ 后置 SQL:执行后自动清理数据库 ★★★
teardown_sql:
# 方式 1:硬编码
- DELETE FROM collection WHERE name LIKE '博客文章%'
# 方式 2:从响应动态提取
- DELETE FROM collection WHERE id = $json($.data.id)$
十、扩展与定制
10.1 添加自定义动态函数
在 Context 类(utils/read_files_tools/regular_control.py)中添加方法:
class Context:
@classmethod
def get_random_order_id(cls) -> str:
"""生成随机订单号"""
import time
return "ORD" + str(int(time.time() * 1000))
YAML 中直接使用:${{get_random_order_id()}}
10.2 添加自定义断言类型
第 1 步: 在 assert_type.py 中实现函数:
def in_range(check_value, expect_value, message=""):
low, high = expect_value
assert low <= check_value <= high, message
第 2 步: 在 models.py 的 AssertMethod 枚举中注册:
class AssertMethod(Enum):
# ...
in_range = "in_range"
第 3 步: YAML 中调用:
assert:
age:
jsonpath: $.data.age
type: in_range
value: [18, 60]
AssertType:
10.3 运行方式
# 安装依赖
pip install -r requirements.txt
# 完整运行(生成报告 + 通知 + 自动打开报告)
python run.py
# 只运行 pytest
pytest test_case/ -s -v --alluredir=./report/tmp
# 生成 Allure 报告
allure generate ./report/tmp -o ./report/html --clean
# 启动报告服务
allure serve ./report/tmp -h 127.0.0.1 -p 9999
# 多进程运行
pytest -n 4 -s --alluredir=./report/tmp
十一、总结
各模块核心职责一览
框架优势
✅ 零代码门槛 — 纯 YAML 编写用例,框架自动生成 pytest 代码
✅ 类型安全 — pydantic + Enum 全覆盖,配置错误早发现
✅ 松耦合 — 各引擎通过模型类(TestCase/ResponseData)通信,可独立扩展
✅ 开箱即用 — 钉钉/企业微信/飞书/邮件/MySQL 均已集成
✅ 分层清晰 — 配置层 → 数据层 → 解析层 → 请求层 → 断言层 → 通知层
写在最后
本框架为余少琪个人业余时间开发,如果对你有帮助,欢迎在 Gitee 仓库点星支持。
仓库地址:https://gitee.com/yu_xiao_qi/pytest-auto-api2
作者博客:https://blog.csdn.net/weixin_43865008
Happy Testing!🚀
十二、环境就绪与实战验证
本章记录了从零开始将框架跑通的全过程,包含 API 验证、依赖安装、pydantic v2 兼容修复、Demo 构建和运行结果。
12.1 API 可用性确认
目标 API: https://wanandroid.com(玩 Android 开放 API)
⚠️ 关键注意事项:
域名必须使用
wanandroid.com,不要带www(www.wanandroid.com部分区域 DNS 解析异常)所有 POST 接口使用
Content-Type: application/x-www-form-urlencoded
12.2 环境搭建步骤
# 1. 创建虚拟环境
cd /Users/shisuiyi/pytest-auto-api2
python3 -m venv venv
# 2. 安装核心依赖
venv/bin/pip install pytest requests PyYAML pydantic jsonpath faker colorlog allure-pytest requests-toolbelt openpyxl pymysql
# 3. 验证安装
venv/bin/python -c "import requests, yaml, pytest, pydantic, jsonpath, faker; print('All OK')"
12.3 pydantic v2 兼容修复
框架原代码基于 pydantic v1,而当前环境中安装的是 pydantic v2,v2 在类型校验上更严格。以下为兼容修复清单:
修改文件:utils/other_tools/models.py
修改文件:utils/read_files_tools/get_yaml_data_analysis.py
12.4 注册的新账号
在运行 Demo 前已注册可用账号:
username: test_reasonix
password: "123456"
user_id: 172458
12.5 配置文件更新
# common/config.yaml —— 核心变更
project_name: WanAndroid 接口自动化测试
host: https://wanandroid.com
tester_name: Reasonix
# test_case/conftest.py —— 登录凭据变更
url = "https://wanandroid.com/user/login"
data = {
"username": "test_reasonix",
"password": "123456"
}
12.6 全功能 Demo 一览
在 data/Demo/ 目录下创建了 7 个功能分支的 Demo YAML 文件:
12.7 运行结果
执行 venv/bin/python run_demo.py 输出:
[1] 配置系统 ✅ 项目: WanAndroid 接口自动化测试 | API: https://wanandroid.com
[2] YAML 解析 ✅ 3 cases parsed (文章列表/Banner/常用网站)
[3] 动态变量 ✅ host() -> https://wanandroid.com
phone() -> '18626817308'
get_time() -> '2026-05-31 21:04:32'
cache{login_cookie} -> JSESSIONID=X;
[4] 请求引擎 ✅ HTTP 200, errorCode=0, 3 banners, 响应时长 276ms
[5] 断言 13种 ✅ 12/12 assertions passed
[6] 缓存 ✅ CacheHandler 读写正常
[7] API连通性 ✅ 4/4 接口 errorCode=0
[8] 登录+Cookie ✅ 登录成功 userId=172458, 收藏列表 0 条
12.8 PyCharm 使用指南
打开项目
File -> Open -> /Users/shisuiyi/pytest-auto-api2
配置解释器
Settings -> Project: pytest-auto-api2 -> Python Interpreter
-> Add Interpreter -> Existing environment
-> Interpreter: /Users/shisuiyi/pytest-auto-api2/venv/bin/python3
运行方式
注意事项
API 域名必须用
wanandroid.com,不加www如需体验数据库断言,需安装 MySQL 并将
config.yaml的mysql_db.switch改为True通知功能需配置钉钉/企微/飞书/邮件的 webhook(默认关闭)
文件上传功能(requestType: FILE)需要实际的接口配合,当前 Demo 中以
is_run: False展示语法
评论交流
欢迎留下你的想法