























在传统API测试中,我们常常面临这些问题:
手工编写用例:每个接口要写几十个用例,耗时耗力
边界值覆盖不全:总有遗漏的边界情况
维护成本高:接口一变更,用例全重写
发现问题晚:很多问题到线上才暴露
直到我遇到了Schemathesis——一个基于OpenAPI规范的属性测试框架。
Schemathesis是一个基于属性测试(Property-based Testing)的API自动化测试工具。它能从OpenAPI规范自动生成测试用例,发现手动测试难以覆盖的边缘场景。
自动发现崩溃:找出哪些请求能让API崩溃
规范一致性验证:确保API实现与OpenAPI文档一致
边缘场景覆盖:自动生成边界值、异常值
零维护成本:测试用例随API schema自动更新

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

创建一个它的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
之后执行:

运行测试后,Schemathesis自动生成了 58个测试用例!
成功用例:1个(提供正确Header和Body的用例)
失败用例:57个(验证了API的参数校验机制)
这57个失败用例恰恰证明了API的健壮性——它对各种异常输入都返回了正确的错误码。
通过这次测试,我们验证了API的:
必填参数校验:缺失Header时返回10000
参数类型校验:类型错误时返回10000
边界值处理:pageSize=101时返回10000
HTTP方法限制:非POST方法返回405
手工测试需要编写50个用例,耗时2天;Schemathesis自动生成58个用例,只需5分钟。
当API接口变更时,只需要更新OpenAPI文件,测试用例自动同步更新。
发现缺失的必填参数校验
发现不完善的类型校验
发现不一致的错误码
从编写用例到分析结果,效率提升至少80%。
OpenAPI规范是基础——规范的质量决定了测试的质量
渐进式实施:从简单到复杂,逐步完善
及时调整断言:根据实际API响应调整验证逻辑
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。