关注「索引目录」公众号,获取更多干货。
做 API 测试有时简直是噩梦。API 总是在变化,端点不断增加,状态码不断更新,要让测试保持同步就像追逐一个移动的目标。
如果你只看任务看板,很容易忽略哪些内容已经实际更改,哪些内容仍然需要测试。
在我参与的项目中,API 可以使用 Swagger。我当时就想:等等……为什么不利用 AI 和 Swagger 来节省生成测试的时间呢?
这就是这个小项目的由来。在这篇文章中,我将带你了解我是如何完成这个项目的,我遇到的挑战,以及接下来你可以尝试的一些有趣的事情。
这个想法
目标很简单:获取 Swagger 规范并提取所有有用信息,例如:
-
HTTP 方法 -
预期状态码 -
查询参数 -
请求机构
然后自动生成阳性和阴性测试场景。
例如,对于一个简单的GET /users/{id}端点,我希望输出如下所示:
GET /users/{id}
✔ Scenario: Retrieve a user with a valid ID
✔ Scenario: Validate 404 for user not found
✘ Scenario: Missing ID parameter
✘ Scenario: Invalid format for ID
为了使之顺利运行,我使用 AI 根据端点的 Swagger 规范,按照我定义的模板创建了场景。
关于本项目
堆
- Python——
速度快,易于解析数据,集成各种功能 - Rich/Typer(命令行界面用户体验)
——因为美观的命令行界面让生活更美好 - Gemini AI
– 超简单的 Python 集成,用于 AI 提示。 - dotenv
– 用于保护 AI 密钥安全
项目结构
api-test-generator/
├── README.md # Documentation of the project
├── requirements.txt # Dependências Python
├── main.py # Main function
│
├── output/ # Folder with generated tests
│ ├── get_Books.txt
│ ├── post_Books.txt
│
├── functions/ # Main functions of the project
│ ├── navigation.py # CLI navigation
│ ├── read_swagger.py # Read files and URL swaggers
│ └── test_generator.py # Generate tests and save them in the files
│
└── assets/ # theme and example for the project
├── swaggerexample.json
└── theme.py
工作原理
┌──────────────────────────────┐
│ User / QA │
│ (CLI Interaction - Rich) │
└──────────────┬───────────────┘
│
▼
┌──────────────────────────────┐
│ CLI Interface │
│ (Typer + Rich Menu) │
└──────────────┬───────────────┘
│
▼
┌──────────────────────────────┐
│ Swagger/OpenAPI Loader │
│ - URL, Manual, or Local JSON│
│ - Validation & Parsing │
└──────────────┬───────────────┘
│
▼
┌──────────────────────────────┐
│ API Specification Parser │
│ - Endpoints │
│ - Methods │
│ - Parameters │
│ - Responses / Status Codes │
└──────────────┬───────────────┘
│
▼
┌──────────────────────────────┐
│ Gemini AI API │
│ (Test Case Generation) │
└──────────────┬───────────────┘
│
▼
┌──────────────────────────────┐
│ Output Generator │
│ - Text file export (.txt) │
│ - Structured scenarios │
└──────────────────────────────┘
基本上:用户与 CLI 交互 → 加载 Swagger → 解析规范 → 构建提示 → 发送给 AI → AI 返回测试 → 保存到文件。
代码高亮显示
测试生成器
其核心思想是:从 Swagger 中提取尽可能多的信息,以便 AI 能够生成有意义的测试。
以下是我编写的主要函数:
def test_generator(path, method, swagger_data):
print(f"Generating tests for {method.upper()} {path}...")
details = swagger_data["paths"][path][method]
request_body = ""
parameters = ""
# Getting information about the endpoint
if 'tags' not in details:
endpoint_name = path
elif len(details['tags']) == 0:
endpoint_name = path
else:
endpoint_name = details['tags'][0]
if 'requestBody' in details:
request_body = details['requestBody']
if 'parameters' in details:
parameters = details['parameters']
prompt = (f"Generate positive and negative tests for this endpoint:{path} for the method {method.upper()}"
f"considering the following specifications: "
f"Name of the endpoint: {endpoint_name}"
f"Request body: {request_body}"
f"Query Parameters: {parameters} and return the tests following this template: {theme.PROMPT_TEMPLATE}")
test_scenario = ai_connection(prompt)
print(f"Exporting tests to file...")
export_to_file(test_scenario, method, endpoint_name)
连接到 Gemini AI
连接到人工智能很简单:创建一个客户端,设置模型,然后传递提示信息:
def ai_connection(prompt):
load_dotenv()
api_key = os.getenv("GOOGLE_API_KEY")
client = genai.Client(api_key=api_key)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=prompt
)
return response.text
瞧!人工智能返回了类似这样的结果:
POST /api/v1/Books
✔ Scenario: Successfully create a new book with all valid fields
✔ Scenario: Successfully create a new book with only mandatory fields
✔ Scenario: Successfully create a new book using 'text/json; v=1.0' content type
✘ Scenario: Fail to create book due to missing 'title' field
✘ Scenario: Fail to create book due to missing 'author' field
✘ Scenario: Fail to create book due to missing 'isbn' field
✘ Scenario: Fail to create book with an 'isbn' that already exists (conflict)
✘ Scenario: Fail to create book due to invalid 'isbn' format (e.g., too short, non-numeric where expected)
✘ Scenario: Fail to create book due to 'publication_year' being a string instead of an integer
✘ Scenario: Fail to create book due to empty request body
✘ Scenario: Fail to create book due to malformed JSON in request body
✘ Scenario: Fail to create book with an empty 'title' string
✘ Scenario: Fail to create book with an empty 'author' string
挑战与经验教训
说实话,最难的部分是清理 Swagger 数据,以及构建对 AI 有意义的提示信息。
另一个挑战是设计一个既能在命令行界面 (CLI) 中流畅运行,又不会显得笨拙的工作流程。
但最终,整个过程非常有趣,我也学到了很多关于 AI 辅助测试的知识。
接下来会发生什么?
在建造这个的过程中,我开始憧憬接下来我可以做的所有事情:
-
从这些测试中自动生成Postman 集合 -
与Zephyr 或 Xray 等测试管理工具集成 -
将其打造为一个监控 Swagger 并在端点更改时更新测试的服务。可能性无穷无尽。
结论
这个项目让我真正体会到,AI + OpenAPI = 可以节省大量时间。
现在,我不再需要手动为每个端点编写数十个测试用例,而是拥有一个自动化系统,可以在几分钟内生成正面和负面场景。
下一步?放眼更广阔的领域:将其集成到 CI/CD 流水线中,接入测试管理工具,甚至实现 API 的实时监控。更智能、更快速、更轻松的 API 测试——这听起来简直完美。
如果您想查看完整的项目、探索代码或亲自尝试,所有内容都在我的 GitHub 上:API 测试生成器。
关注「索引目录」公众号,获取更多干货。

