从 Swagger/OpenAPI 2.0/3.x 规格文件生成 API 自动化测试用例,支持两种输出:
Excel 用例表 和 pytest 测试框架文件。
同时提供一个完整的测试运行框架,包含配置管理、日志、HTTP封装、Fixture、报告五大核心模块。
swagger-to-testcases/
framework/ # 测试运行框架
__init__.py # 框架入口,统一导出
config.py # 1. 配置模块 - 多环境切换
logger.py # 2. 日志模块 - 结构化日志
http_client.py # 3. HTTP请求封装 - 统一请求+断言+提取
fixtures.py # 4. Fixture机制 - 登录/初始化/清理
reporter.py # 5. 报告模块 - Allure报告
conftest.py # pytest 全局配置模板
config/ # 多环境配置文件
default.yaml # 默认配置
dev.yaml # 开发环境
test.yaml # 测试环境
scripts/
parse_swagger.py # Swagger 解析器
generate_testcases.py # Excel/pytest 生成器
run.py # 一键管道脚本
project_templates/
pyproject.toml # 项目依赖模板
framework/config.py)多环境配置管理,优先级:环境变量 > 环境YAML > default.yaml
TEST_BASE_URL, TEST_DATABASE_HOST 等config.get('database.host')from framework import config
# 切换环境
# export TEST_ENV=test
base_url = config.base_url # http://test.example.com/api/v1
db_host = config.database['host']
timeout = config.timeout # 30
# 设置运行时 token
config.set_token('xxx-token-xxx')
base_url: "http://localhost:8080"
timeout: 30
headers:
Content-Type: "application/json"
accounts:
admin:
username: "admin"
password: "admin123"
database:
host: "localhost"
port: 3306
database: "test_db"
auth:
login_path: "/api/login"
token_key: "token"
token_type: "Bearer"
report:
allure_dir: "reports/allure-results"
log_dir: "reports/logs"
framework/logger.py)结构化日志,请求/响应/断言都有专用方法,失败时快速定位。
logger.request(), logger.response(), logger.assertion()logger.extract() 记录关联变量值logger.step() 标记测试流程节点2026-06-05 16:30:00 | INFO | test_user.py:25 | REQUEST GET http://...
2026-06-05 16:30:00 | INFO | test_user.py:26 | RESPONSE 200 (45ms)
2026-06-05 16:30:00 | INFO | test_user.py:27 | ASSERT [PASS] status code == 200
2026-06-05 16:30:00 | ERROR | test_user.py:27 | ASSERT [FAIL] jsonpath $.code
framework/http_client.py)统一请求入口,自动处理 header、token、超时、重试、异常,内置断言和关联提取。
| 功能 | 说明 |
|---|---|
| ------ | ------ |
| 统一请求 | get/post/put/patch/delete,自动拼接 base_url |
| 公共 header | 自动携带 Content-Type, Accept 等 |
| Token 自动注入 | set_token() 后所有请求自动带 Authorization |
| 超时控制 | 默认30s,可全局配置或单次覆盖 |
| 重试机制 | 可配次数+间隔,仅对 5xx 重试 |
| 异常处理 | Timeout/ConnectionError 统一捕获并记录 |
| 状态码断言 | resp.assert_status(200) |
| 字段断言 | resp.assert_jsonpath({'$.code': 0}) |
| 业务码断言 | resp.assert_business_code() |
| 包含断言 | resp.assert_contains('success') |
| 存在断言 | resp.assert_field_exists('data.id') |
| 数据库断言 | client.db_assert(db_cfg, 'users', where, expect) |
| 变量提取 | resp.extract({'token': '$.data.token'}) |
| 参数化 | 请求体支持 {{variable}} 占位符自动替换 |
| 链式调用 | 所有断言方法返回 self,支持链式 |
from framework import client
# 基础请求
resp = client.get('/api/users', params={'page': 1})
# 自动断言 + 提取
resp = client.get('/api/users/1')
resp.assert_status(200)\
.assert_jsonpath({'$.code': 0})\
.assert_business_code()\
.extract({'user_id': '$.data.id'})
# 使用提取的变量
client.get('/api/users/{{user_id}}')
# POST 带 body 自动生成
client.post('/api/users', body={'name': 'John', 'email': 'john@test.com'})
.assert_status(201)
# 数据库断言
client.db_assert(
config.database,
table='users',
where={'id': 1},
expect={'status': 1}
)
framework/fixtures.py)测试前置/后置管理,登录、初始化、清理一站式。
| 功能 | 方法 |
|---|---|
| ------ | ------ |
| 自动登录 | fixture.login('admin') 或 fixture.login_if_needed() |
| 数据库初始化 | fixture.init_database(init_sql='...') |
| 自定义 headers | fixture.init_headers({'X-Version': '1.0'}) |
| 注册清理任务 | fixture.register_cleanup(fn) |
| DB 清理 | fixture.cleanup_db('users', {'id': 123}) |
| HTTP 清理 | fixture.cleanup_request('delete', '/users/123') |
| 全部清理 | fixture.cleanup() |
from framework import fixture
class TestUser:
@pytest.fixture(autouse=True)
def setup(self):
fixture.login_if_needed('admin') # 登录前置
yield
fixture.cleanup() # 清理后置
framework/reporter.py)生成 Allure 报告 + 邮件发送,自动附加请求/响应/断言信息。
allure-pytest 可用性,不可用时降级为文件记录attach_request/response/assertion 附加详细数据到 Allure 报告generate_summary() 生成 JSON 摘要报告(总数/通过/失败/跳过/通过率)TEST_REPORT_EMAIL_PASSWORDreport:
email:
smtp_host: "smtp.163.com"
smtp_port: 465
smtp_ssl: true
from_addr: "test-report@163.com"
from_name: "API测试报告"
password: "" # 推荐用环境变量避免明文
to_addrs:
- "dev-team@company.com"
cc_addrs: []
from framework import reporter
# 方式1:直接发送(使用配置的收件人)
reporter.send_email(
summary={'total': 100, 'passed': 98, 'failed': 2, 'skipped': 0},
title='User模块测试报告'
)
# 方式2:指定收件人 + 附件
reporter.send_email(
summary=summary,
to_addrs=['qa@company.com', 'dev@company.com'],
attachments=['reports/allure-report.zip', 'tests/testcases.xlsx']
)
# 方式3:一键打包 Allure 报告并发送
reporter.send_email_with_allure(
summary=summary,
allure_report_dir='reports/allure-report',
testcases_xlsx='tests/testcases.xlsx'
)
# 方式4:使用 EmailSender 直接控制
from framework.reporter import EmailSender
sender = EmailSender()
sender.send_simple(
subject='构建通知',
body='<h3>测试全部通过</h3><p>详情见附件</p>',
body_type='html'
)
# 运行测试并生成报告
pytest tests/ --alluredir=reports/allure-results -v
# 生成 Allure 静态报告
allure generate reports/allure-results -o reports/allure-report
# 发送邮件报告(在 conftest 的 pytest_sessionfinish hook 中自动发送)
python scripts/run.py swagger.json
# 输出: swagger_testcases.xlsx
python scripts/run.py swagger.json --format pytest --output tests/ --with-excel
# 输出: tests/test_*.py + tests/conftest.py + tests/testcases.xlsx
# Step 1: 解析 Swagger
python scripts/parse_swagger.py swagger.json > testcases.json
# Step 2: 生成文件
python scripts/generate_testcases.py testcases.json tests/ --format pytest --with-excel
framework/ 目录复制到测试项目config/default.yaml 和环境配置文件tests/ 目录放到项目根目录pip install -r requirements.txt(或使用 project_templates/pyproject.toml)pytest tests/ --alluredir=reports/allure-results -vallure serve reports/allure-results26列完整测试用例表,视觉格式化(蓝色表头/冻结首行/自动筛选/颜色编码)。
详见 references/field_spec.md。
requests>=2.28
openpyxl>=3.1
pyyaml>=6.0
pytest>=7.0
pymysql>=1.0 # 可选,DB断言需要
allure-pytest>=2.13 # 可选,Allure报告需要
共 1 个版本