温馨提示×

如何使用Debian Swagger进行API测试

小樊
39
2025-12-06 19:34:54
栏目: 智能运维

在 Debian 上进行 Swagger OpenAPI API 测试

一 准备环境与规范文件

  • 更新系统并安装常用工具:sudo apt update && sudo apt install -y curl docker.io nodejs npm python3 python3-pip
  • 准备 API 规范文件:确保有 swagger.jsonswagger.yaml(OpenAPI/Swagger 描述文件),后续用于生成文档、客户端或驱动自动化测试。

二 方式一 使用 Swagger UI 进行手工测试

  • 本地快速启动 Swagger UI(Docker):
    • 拉取并运行:docker pull swaggerapi/swagger-ui && docker run -d -p 38081:8080 swaggerapi/swagger-ui
    • 在浏览器访问:http://localhost:38081,将你的 swagger.json 通过页面导入或在启动时挂载到容器,即可在 UI 中直接 Try it out 发起请求。
  • 在你的 Node.js 服务中内嵌 Swagger UI(便于与后端同域调试):
    • 安装:npm i express swagger-ui-express [yamljs]
    • 示例代码(保存为 server.js):
      • const express = require(‘express’); const swaggerUi = require(‘swagger-ui-express’); const YAML = require(‘yamljs’);
      • const swaggerDocument = YAML.load(‘./swagger.yaml’);
      • const app = express(); app.use(‘/api-docs’, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
      • app.listen(3000, () => console.log(‘Server on http://localhost:3000/api-docs’));
    • 启动服务:node server.js,访问 http://localhost:3000/api-docs 进行手工测试。

三 方式二 自动化测试方案

  • 方案A 生成客户端 SDK 并编写测试

    • 安装 Swagger Codegen CLI(Java 方式,稳定通用):
      • wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.44/swagger-codegen-cli-3.0.44.jar -O swagger-codegen-cli.jar
    • 生成客户端(示例为 python):
      • java -jar swagger-codegen-cli.jar generate -i http://localhost:8080/v2/api-docs -l python -o ./generated-client
    • 使用 pytest/requests 编写测试(示例 test_api.py):
      • import pytest, requests
      • def test_get_users(): r = requests.get(‘http://localhost:8080/api/users’); assert r.status_code == 200
      • def test_create_user(): d = {“name”:“John Doe”,“email”:“john@example.com”}; r = requests.post(‘http://localhost:8080/api/users’, json=d); assert r.status_code == 201
    • 运行:pytest test_api.py。
  • 方案B 使用 Postman Newman 运行集合

    • 将 Swagger 导出为 Postman Collection JSON,然后用 Newman 在 CLI 执行:
      • npm install -g newman
      • newman run your-swagger-collection.json -r cli,json,html(生成控制台、JSON、HTML 报告)。
  • 方案C 使用 Dredd 对 OpenAPI 进行契约测试

    • 安装:npm install -g dredd
    • 执行:dredd swagger.yaml http://localhost:8080(按规范校验实际服务实现)。

四 在 CI/CD 中集成

  • 将测试纳入流水线(示例):
    • 构建阶段启动被测服务与 Mock/依赖。
    • 运行自动化测试:pytest、newman 或 dredd。
    • 归档报告(JUnit/JSON/HTML),设置失败阈值,阻止不合规合并。
  • 参考实践:将生成的客户端测试脚本或 Newman 集合在 GitHub Actions/GitLab CI 中定时或按提交触发执行。

五 常见问题与排查

  • 访问被拒绝或 404:确认目标服务已启动且规范中的 basePath 与实际路径一致;必要时在 Swagger UI 的 Servers 配置正确的 Base URL
  • 认证失败:在 UI 的 Authorize 填入 Bearer TokenAPI Key,或在 curl/Newman 中添加 -H “Authorization: Bearer
  • 规范与实现不一致:使用 Dredd 做契约测试,快速定位缺失或类型不匹配的接口。
  • 本地文件无法加载:若使用文件方式加载 swagger.yaml,注意 YAML 缩进与引用路径;使用 Docker 时可通过卷挂载规范文件到容器内。

0