← 返回
未分类

swagger-to-testcases

This skill should be used when the user wants to generate API automation test cases in Excel format or pytest framework files from a Swagger/OpenAPI specification file (JSON or YAML). Triggers: "Swagger生成测试用例", "OpenAPI转Excel用例", "接口文档生成自动化用例", "swagger to test cases", "API test case generation from spec", or any request involving converting an API specification into testable test cases. The skill also provides a complete test framework (config, logger, HTTP client, fixtures, reporter) that can
这是一个 Swagger/OpenAPI 规格文件 → API 自动化测试用例 的转换工具 ,同时附带完整的 pytest 测试运行框架。 核心能力: 输入:Swagger/OpenAPI 2.0 或 3.x 规格文件(JSON 或 YAML) 输出两种格式: Excel 测试用例表(26列完整用例,含请求参数、预期结果、测试数据等) 参阅:接口自动化全字段清单-CSDN博客 pytest 测试框架文件(可直接运行的测试代码 + 配置文件) 一键生成两种交付物 Excel 用例表可直送 QA 团队 pytest 代码可接入 CI/CD 流水线 两者同时生成,兼顾手工测试和自动化测试 配套框架完整度高 不只是生成用例,还提供完整的测试运行基础设施 config 支持环境变量覆盖、多环境切换 HTTP 客户端封装了重试、超时、token 自动注入、参数化替换等常用能力 数据库断言、清理机制等适合有状态的 API 测试场景 日志和报告专业 专用 logger.request() / logger.response() / logger.assertion() 方法,失败时快速定位 自动脱敏 Authorization、token、password 等敏感字段 邮件报告支持 HTML 格式、通过率进度条、Allure 报告 zip 附件 字段规范文档完善 references/field_spec.md 定义了 26 列 Excel 的每个字段含义;参阅:接口自动化全字段清单-CSDN博客 蓝色表头、冻结行、自动筛选、颜色编码等视觉格式化开箱即用 脚本支持分步和管道两种模式
user_a84e2069
未分类 community v1.0.0 1 版本 100000 Key: 无需
★ 1
Stars
📥 29
下载
💾 0
安装
1
版本
#latest

概述

Swagger to Test Cases -- API 自动化测试用例生成 + 测试框架

从 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        # 项目依赖模板

模块 1: 配置模块 (framework/config.py)

多环境配置管理,优先级:环境变量 > 环境YAML > default.yaml

功能

  • 支持 dev/test/staging/prod 多环境切换
  • 管理 base_url、账号、数据库连接、认证配置
  • 环境变量覆盖: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')

配置文件格式 (config/default.yaml)

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"

模块 2: 日志模块 (framework/logger.py)

结构化日志,请求/响应/断言都有专用方法,失败时快速定位。

功能

  • 双输出:控制台(INFO级别) + 按日期文件(DEBUG级别)
  • 专用方法:logger.request(), logger.response(), logger.assertion()
  • 自动脱敏:Authorization、token、cookie、password 等敏感字段掩码
  • 自动截断:过长 body/headers 超过2000字符自动截断
  • 提取变量: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

模块 3: HTTP请求封装 (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}
)

模块 4: Fixture机制 (framework/fixtures.py)

测试前置/后置管理,登录、初始化、清理一站式。

功能

功能方法
------------
自动登录fixture.login('admin')fixture.login_if_needed()
数据库初始化fixture.init_database(init_sql='...')
自定义 headersfixture.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()                  # 清理后置

模块 5: 报告模块 (framework/reporter.py)

生成 Allure 报告 + 邮件发送,自动附加请求/响应/断言信息。

功能

  • 自动检测 allure-pytest 可用性,不可用时降级为文件记录
  • attach_request/response/assertion 附加详细数据到 Allure 报告
  • 自动脱敏:敏感 header 值掩码
  • generate_summary() 生成 JSON 摘要报告(总数/通过/失败/跳过/通过率)
  • 邮件发送:通过 SMTP 发送精美 HTML 报告,支持附件(Allure报告zip/Excel用例/日志)
  • 邮件内容:通过率可视化进度条、失败用例详情、测试结果表格
  • 密码安全:SMTP密码支持环境变量 TEST_REPORT_EMAIL_PASSWORD

邮件配置 (config/default.yaml)

report:
  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 中自动发送)

工作流程

方式一:生成 Excel 用例表(默认)

python scripts/run.py swagger.json
# 输出: swagger_testcases.xlsx

方式二:生成 pytest 测试框架

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

在项目中运行

  1. framework/ 目录复制到测试项目
  2. 配置 config/default.yaml 和环境配置文件
  3. 将生成的 tests/ 目录放到项目根目录
  4. 安装依赖:pip install -r requirements.txt(或使用 project_templates/pyproject.toml
  5. 运行:pytest tests/ --alluredir=reports/allure-results -v
  6. 查看报告:allure serve reports/allure-results

Excel 输出格式

26列完整测试用例表,视觉格式化(蓝色表头/冻结首行/自动筛选/颜色编码)。

详见 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 个版本

  • v1.0.0 Initial release 当前
    2026-06-05 17:41 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

dev-programming

CodeConductor.ai

larsonreever
AI驱动平台,提供快速全栈开发、智能体、工作流自动化及低代码AI集成的可扩展产品创建。
★ 72 📥 181,787
dev-programming

Mcporter

steipete
使用 mcporter CLI 直接列出、配置、认证及调用 MCP 服务器/工具(支持 HTTP 或 stdio),涵盖临时服务器、配置编辑及 CLI/类型生成功能。
★ 195 📥 67,622
dev-programming

YouTube

byungkyu
使用托管OAuth集成YouTube Data API,支持搜索视频、管理播放列表、获取频道数据及评论互动,适用于用户需要时使用此技能。
★ 142 📥 41,528