惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

宝玉的分享
宝玉的分享
NISL@THU
NISL@THU
E
Exploit-DB.com RSS Feed
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
K
Kaspersky official blog
Project Zero
Project Zero
Cisco Talos Blog
Cisco Talos Blog
T
The Exploit Database - CXSecurity.com
P
Palo Alto Networks Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threatpost
S
Schneier on Security
G
GRAHAM CLULEY
The Hacker News
The Hacker News
T
Threat Research - Cisco Blogs
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Cyberwarzone
Cyberwarzone
C
CERT Recently Published Vulnerability Notes
T
Tor Project blog
AWS News Blog
AWS News Blog
Simon Willison's Weblog
Simon Willison's Weblog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
爱范儿
爱范儿
P
Privacy International News Feed
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
S
Securelist
G
Google Developers Blog
The Last Watchdog
The Last Watchdog
Google Online Security Blog
Google Online Security Blog
美团技术团队
F
Fortinet All Blogs
小众软件
小众软件
Recorded Future
Recorded Future
V
Visual Studio Blog
B
Blog RSS Feed
H
Help Net Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
Blog — PlanetScale
Blog — PlanetScale
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
Martin Fowler
Martin Fowler
Latest news
Latest news
Spread Privacy
Spread Privacy
H
Heimdal Security Blog

博客园 - 小海海宁宁

OpenAPI规范及自动化用例生成 playwright & selenium对Shadow DOM的处理 自动化平台质量体系建设(草稿) 【模板】邮件提测模板 研发测试质量规范(草稿) 自动化框架 - Q&A 自动化框架 - 核心模块使用指南 - Kafka 自动化框架 - 核心模块使用指南 - Kibana 自动化框架 - 核心模块使用指南 - Playwright 自动化框架 - 核心模块使用指南 - API 自动化框架 - 核心功能使用指南 - 动态值生成 自动化框架 - 核心功能使用指南 - 数据处理模块 自动化框架 - 核心功能使用指南 - 数据校验模块 自动化框架 - 核心功能使用指南 - 上下文值传递 自动化框架 - 核心功能使用指南 - 用例过滤Tag使用 自动化框架 - 核心功能使用指南 - Excel测试用例编写 自动化框架 - 核心功能使用指南 - 配置文件使用指南 自动化框架使用说明 - 快速开始 Kibana如何添加可视化看板
从0到1:使用Schemathesis搭建API自动化测试框架实战
小海海宁宁 · 2026-03-11 · via 博客园 - 小海海宁宁

一、背景与挑战

在传统API测试中,我们常常面临这些问题:

  • 手工编写用例:每个接口要写几十个用例,耗时耗力

  • 边界值覆盖不全:总有遗漏的边界情况

  • 维护成本高:接口一变更,用例全重写

  • 发现问题晚:很多问题到线上才暴露

直到我遇到了Schemathesis——一个基于OpenAPI规范的属性测试框架。

什么是Schemathesis?

Schemathesis是一个基于属性测试(Property-based Testing)的API自动化测试工具。它能从OpenAPI规范自动生成测试用例,发现手动测试难以覆盖的边缘场景。

与传统框架的对比

Schemathesis的核心价值

  1. 自动发现崩溃:找出哪些请求能让API崩溃

  2. 规范一致性验证:确保API实现与OpenAPI文档一致

  3. 边缘场景覆盖:自动生成边界值、异常值

  4. 零维护成本:测试用例随API schema自动更新

三、环境搭建与初探

3.1 安装Schemathesis


image


3.2 创建OpenAPI YAML文件

原始的一个api请求是这样的:

image

创建一个它的OpenAPI定义,命名为test_openapi.yml

openapi: 3.0.0
info:
title: 内部租户初始化流程任务配置API
version: 1.0.0
servers:
- url: https://**-test.******.com
description: 测试
paths:
/test1/public/rest/api/bu/config/tenantInitFlowTask/page:
post:
summary: 分页查询租户初始化流程任务
description: 用于分页查询租户初始化流程任务配置信息
parameters:
# Header 参数
- name: oah-app-id
in: header
required: true
schema:
type: string
example: "DZ-Tr9ilnE8"
description: 应用ID
- name: oah-sign
in: header
required: true
schema:
type: string
example: "hz8zuVeF+IXYMVnPMPVGSmCelZo3WBGl6qVKeUnwT+g="
description: 签名
- name: oah-sign-type
in: header
required: true
schema:
type: string
enum: [ASK]
example: "ASK"
description: 签名类型
- name: oah-timestamp
in: header
required: true
schema:
type: string
example: "1761113092294"
description: 时间戳
- name: tenant-id
in: header
required: true
schema:
type: string
example: "TE7382974987348738"
description: 租户ID
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- pageNumber
- pageSize
properties:
pageNumber:
type: integer
description: 当前页码
example: 1
minimum: 1
pageSize:
type: integer
description: 每页大小
example: 20
minimum: 1
maximum: 100
types:
type: array
description: 类型列表
items:
type: integer
example: [1]
responses:
'200':
description: 成功响应
content:
application/json:
schema:
type: object
properties:
success:
type: boolean
example: true
status_code:
type: integer
example: 200
data:
type: object
properties:
data:
type: object
properties:
total:
type: integer
rows:
type: array
items:
type: object
code:
type: string
msg:
type: string
traceId:
type: string
'400':
description: 请求参数错误

 创建test_api.py:

import schemathesis
import yaml

#加载schema
with open("test_openapi.yaml", 'r', encoding='utf-8') as f:
raw_spec = yaml.safe_load(f)

schema = schemathesis.openapi.from_dict(raw_spec)

@schema.parametrize()
def test_api(case):
"""测试租户初始化流程任务分页查询接口"""
print(f"\n测试接口: {case.method} {case.path}")
print(f" Headers: {case.headers}")
print(f" Body: {case.body}")

try:
# 调用内部API
response = case.call(base_url="https://icc-oah-ingress-test.msxf.com")

print(f"响应状态码: {response.status_code}")

# 解析响应
if response.status_code == 200:
resp_json = response.json()
print(f" 响应code: {resp_json.get('code')}")
print(f" 响应msg: {resp_json.get('msg')}")
print(f" 响应data: {resp_json.get('data')}")

# 正确的断言:检查code是否为"200"
assert resp_json.get('code') == "200", f"接口调用失败: {resp_json.get('msg')}"

# 如果返回了data,可以进一步验证
data = resp_json.get('data', {})
if data:
print(f" 查询结果总数: {data.get('total')}")
print(f" 本次返回行数: {len(data.get('rows', []))}")
else:
print(f" 错误响应: {response.text[:200]}")

except Exception as e:
print(f" ❌ 测试执行错误: {e}")
raise

之后执行:

image

测试结果分析

6.1 测试用例统计

运行测试后,Schemathesis自动生成了 58个测试用例!

成功与失败

  • 成功用例:1个(提供正确Header和Body的用例)

  • 失败用例:57个(验证了API的参数校验机制)

这57个失败用例恰恰证明了API的健壮性——它对各种异常输入都返回了正确的错误码。

关键发现

通过这次测试,我们验证了API的:

  1. 必填参数校验:缺失Header时返回10000

  2. 参数类型校验:类型错误时返回10000

  3. 边界值处理:pageSize=101时返回10000

  4. HTTP方法限制:非POST方法返回405


Schemathesis的核心价值

7.1 自动生成边界测试

手工测试需要编写50个用例,耗时2天;Schemathesis自动生成58个用例,只需5分钟。

7.2 零维护成本

当API接口变更时,只需要更新OpenAPI文件,测试用例自动同步更新。

7.3 发现API设计缺陷

  • 发现缺失的必填参数校验

  • 发现不完善的类型校验

  • 发现不一致的错误码

7.4 提升测试效率

从编写用例到分析结果,效率提升至少80%。

八、经验总结

8.1 成功的关键

  1. OpenAPI规范是基础——规范的质量决定了测试的质量

  2. 渐进式实施:从简单到复杂,逐步完善

  3. 及时调整断言:根据实际API响应调整验证逻辑

8.2 避坑指南