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 报告,并通过钉钉/企业微信/飞书/邮箱发送通知。

框架核心能力一览

能力

说明

零代码编写

YAML 描述用例,自动生成 pytest 代码,纯小白也能上手

多接口依赖

A 接口的响应结果作为 B 接口的入参,支持 jsonpath 精准提取

多类型断言

响应断言 + 数据库断言 + 请求参数断言,三种来源自由组合

13 种断言方法

==、!=、contains、len_gt、startswith、endswith 等

动态数据生成

15+ 内置函数:${{random_int()}}、${{get_phone()}}、${{get_time()}} 等

后置清理

teardown 请求 + teardown SQL,用例执行后自动清理数据

多渠道通知

钉钉 / 企业微信 / 飞书 / 邮件,支持多通道并行发送

缓存系统

内存 + 文件双缓存,支撑跨用例数据共享

代理录制

mitmproxy 拦截流量 → 自动生成 YAML 测试用例

Swagger 转换

Swagger 接口文档 → 自动生成 YAML 用例

Allure 报告

美观的 HTML 测试报告,含请求/响应/断言详情


二、项目目录结构

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                            # 项目文档

三、核心技术栈

技术

版本

用途

Python

3.7+

开发语言

pytest

~7.1.2

测试框架核心

allure-pytest

2.9.45

Allure 测试报告

requests

2.26.0

HTTP 请求库

PyYAML

~5.4.1

YAML 文件解析

pydantic

~1.8.2

数据模型校验

jsonpath

0.82

JSON 数据提取

PyMySQL

1.0.2

MySQL 数据库操作

redis

~4.3.4

Redis 缓存

mitmproxy

~8.1.0

代理录制

Faker

9.8.3

随机数据生成

DingtalkChatbot

1.5.3

钉钉通知

openpyxl

3.0.9

Excel 处理

pytest-xdist

2.4.0

多进程执行


四、核心架构设计

4.1 整体架构图

                        ┌─────────────┐
                        │   run.py    │
                        │  (主入口)    │
                        └──────┬──────┘
                               │
      ┌────────────────────────┼────────────────────────┐
      │                        │                        │
      ▼                        ▼                        ▼
┌───────────┐        ┌─────────────────┐       ┌──────────────┐
│ 用例代码生成 │        │  pytest 执行引擎  │       │  通知分发      │
│ (可选)      │        │  conftest.py     │       │  钉钉/企微/    │
│ YAML→.py   │        └───────┬─────────┘       │  飞书/邮件     │
└───────────┘                │                 └──────────────┘
                             │
         ┌───────────────────┼───────────────────┐
         ▼                   ▼                   ▼
 ┌──────────────┐ ┌──────────────────┐ ┌────────────────┐
 │ RequestControl│ │  DependentCase   │ │ TearDownHandler │
 │ 请求发送引擎   │ │  依赖处理引擎     │ │ 后置处理引擎     │
 └──────┬───────┘ └────────┬─────────┘ └────────────────┘
        │                  │
        └──────┬───────────┘
               ▼
      ┌────────────────┐
      │   Assert 引擎   │
      │ 响应断言+SQL断言 │
      └────────────────┘

4.2 设计模式应用

模式

应用场景

说明

模板方法

testcase_template.py

固定模板 + 占位符替换,生成不同测试类文件

策略模式

notification_mapping

不同通知渠道(钉钉/企微/飞书/邮件)的策略分发

策略模式

requests_type_mapping

JSON/PARAMS/DATA/FILE/EXPORT 五种请求类型分发

工厂方法

CaseData.case_process()

YAML 原始 dict → 结构化的 TestCase 对象

单例模式

CacheHandler._cache_config

全局唯一内存字典,跨模块共享缓存

装饰器模式

log_decorator

请求日志自动记录

装饰器模式

execution_duration

接口执行时长统计


五、模块分层详解

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 用例解析后的标准数据结构,是框架内部流通的统一格式:

字段

类型

说明

必填

method

Method 枚举

GET / POST / PUT / PATCH / DELETE / HEAD / OPTION

✅

url

str

完整的请求 URL(host + path)

✅

headers

dict

请求头

✅

requestType

RequestType 枚举

JSON / PARAMS / DATA / FILE / EXPORT / NONE

✅

data

dict

请求参数体

✅

dependence_case

bool

是否开启接口依赖

✅

dependence_case_data

list[DependentCaseData]

依赖数据提取规则

assert_data

dict

断言规则

✅

sql

list

数据库查询断言

teardown

list[TearDown]

后置请求处理

teardown_sql

list

后置 SQL

setup_sql

list

前置 SQL

current_request_set_cache

list[CurrentRequestSetCache]

缓存当前请求/响应

sleep

float

请求前等待秒数

is_run

bool

是否执行该用例

✅

detail

str

用例描述

✅

请求类型枚举: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 — 后置处理引擎

请求完成后执行清理操作,支持三种模式:

模式

配置路径

行为

param_prepare

teardown[].param_prepare

从已有响应中提取数据,不额外发请求

send_request

teardown[].send_request

发起新的 HTTP 请求(调用删除接口清理数据)

teardown_sql

teardown_sql list

执行后置 SQL(DELETE / UPDATE 清理数据库)

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() — 遍历所有断言,逐条调父类方法

三种断言来源

AssertType 值

含义

实际提取值来源

期望值来源

None / 未填

纯响应断言

jsonpath(响应JSON, jsonpath)

YAML 中的 value

SQL / D_SQL

响应+数据库断言

jsonpath(响应JSON, jsonpath)

jsonpath(SQL查询结果, value)

R_SQL

请求+数据库断言

jsonpath(请求参数, jsonpath)

jsonpath(SQL查询结果, value)

断言执行流程

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/

两层缓存架构

层级

类

存储位置

生命周期

用途

内存缓存

CacheHandler

全局字典 _cache_config

进程级

跨用例数据共享(依赖传递)、session 级缓存

文件缓存

Cache

cache/ 目录下的文件

持久化

需要跨 session 保留的数据

缓存数据流全景

                  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

模板语法

框架支持两种动态变量语法:

语法

功能

示例

${{函数名()}}

调用内置函数,结果带引号

${{get_time()}} → '2024-01-15 14:30:00'

${{类型:函数名()}}

指定返回类型,结果不带引号

${{int:random_int()}} → 1234

$cache{缓存名}

引用缓存数据

$cache{login_cookie}

内置函数一览(15+)

函数

返回类型

说明

random_int()

int

0-5000 随机整数

get_phone()

int

随机手机号(11位)

get_id_number()

int

随机身份证号(18位)

get_female_name()

str

随机女性中文姓名

get_male_name()

str

随机男性中文姓名

get_email()

str

随机邮箱地址

get_time()

str

当前时间 YYYY-MM-DD HH:mm:SS

today_date()

str

今日 00:00:00

time_after_week()

str

一周后 00:00:00

host()

str

从配置读取主域名

app_host()

str

从配置读取备用域名

self_operated_id()

int

固定返回 212

正则替换引擎的核心实现

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

Fixture / Hook

作用域

autouse

功能

clear_report

session

False

删除历史报告

work_login_init

session

True

登录获取 cookie → 缓存 login_cookie

case_skip

function

True

检查 is_run → 跳过或执行

pytest_collection_modifyitems

hook

—

中文显示 + 自定义用例执行顺序

pytest_terminal_summary

hook

—

统计通过/失败/跳过/时长/成功率


六、核心调用链路

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

十一、总结

各模块核心职责一览

引擎

所在模块

核心职责

解析引擎

get_yaml_data_analysis.py + case_automatic_control.py

YAML → TestCase 对象 → 自动生成 pytest 代码

请求引擎

request_control.py

5 种请求类型的统一发送

依赖引擎

dependent_case.py

jsonpath 提取 + exec 动态替换,实现多接口数据依赖

断言引擎

assert_control.py + assert_type.py

响应/SQL/请求三种来源 + 13 种比较方式

后置引擎

teardown_control.py

后置请求 + 后置 SQL 自动清理

变量引擎

regular_control.py

${{...}} 模板语法 + 15+ 内置函数 + $cache{} 缓存引用

缓存引擎

cache_control.py

内存 + 文件双缓存,支撑跨用例数据共享

通知引擎

notify/

钉钉/企微/飞书/邮件多通道策略分发

框架优势

  • ✅ 零代码门槛 — 纯 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)

检测项

结果

API 文档页 https://wanandroid.com/blog/show/2

✅ 正常加载(最后更新 2024-05-26)

首页 Banner GET /banner/json

✅ errorCode: 0,返回 3 条数据

常用网站 GET /friend/json

✅ errorCode: 0,36 条记录

文章列表 GET /article/list/0/json

✅ errorCode: 0,分页数据完整

知识体系 GET /tree/json

✅ errorCode: 0

用户注册 POST /user/register

✅ 成功注册新账号

用户登录 POST /user/login

✅ 成功获取 cookie

⚠️ 关键注意事项:

  • 域名必须使用 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

原代码

修改后

原因

sql: List = None

sql: Optional[List] = None

YAML 中 sql: 为空时解析为 None

setup_sql: List = None

setup_sql: Optional[List] = None

同上

teardown: List["TearDown"] = None

teardown: Optional[List["TearDown"]] = None

ResponseData 的 teardown 字段

teardown_sql: Optional[Union[None, List]]

teardown_sql: Optional[List]

简化类型签名

sql_data: Dict

sql_data: Optional[Dict] = None

无 SQL 查询时可为空

current_request_set_cache: Optional[List[...]]

补充 = None 默认值

缺少默认值

sleep: Optional[Union[int, float]]

补充 = None 默认值

缺少默认值

dependence_case_data: Optional[...]

去重 = None

修复重复赋值语法错误

修改文件:utils/read_files_tools/get_yaml_data_analysis.py

原代码

修改后

原因

.dict()

.model_dump()

pydantic v2 废弃了 .dict()

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 文件:

文件

覆盖功能

用例数

demo_01_get.yaml

GET 请求 / PARAMS / 多断言 / contains / len_gt

3

demo_02_post_assert.yaml

POST 请求 / DATA / == / != / str_eq / gt / 错误码 -1

5

demo_03_dependency.yaml

Cookie 缓存 / 接口依赖 / current_request_set_cache / teardown

3

demo_04_sql.yaml

SQL 断言 / setup_sql / teardown_sql / AssertType: SQL / R_SQL

3

demo_05_variables.yaml

15+ 内置函数 / 类型标注 / $cache{} 引用

3

demo_06_request_types.yaml

5 种 requestType (PARAMS/DATA/JSON/NONE/FILE)

5

demo_07_control.yaml

is_run 跳过 / sleep 等待

4

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

运行方式

方式

操作

说明

运行全功能 Demo

Terminal: venv/bin/python run_demo.py

验证 8 大模块

运行 pytest

Terminal: venv/bin/python run.py

完整 pytest + Allure 报告

运行 pytest(纯控制台)

Terminal: venv/bin/python -m pytest test_case/ -s -v

只看结果

调试单条用例

在 conftest.py 打断点 -> Debug run.py

逐行跟踪请求-依赖-断言

运行指定 Demo

Terminal: venv/bin/python -m pytest data/Demo/demo_01_get.yaml -s -v

单个 YAML 文件

注意事项

  1. API 域名必须用 wanandroid.com,不加 www

  2. 如需体验数据库断言,需安装 MySQL 并将 config.yaml 的 mysql_db.switch 改为 True

  3. 通知功能需配置钉钉/企微/飞书/邮件的 webhook(默认关闭)

  4. 文件上传功能(requestType: FILE)需要实际的接口配合,当前 Demo 中以 is_run: False 展示语法