实用教程展示如何用AI自动化API测试代码生成流程。降低测试编写成本,是程序员立即可用的编程提效技巧。
以 QA 身份做 API 测试可以说...有时候真的是个噩梦。API 一直在变化,新增端点,状态码更新,想要让测试保持同步就像在追赶一个移动的靶子。
如果你只看任务板,很容易就会失去对实际改动内容和还需要测试哪些部分的把握。
在我做过的项目中,我们都有 Swagger 文档来描述 API。然后我想:等等……为什么不用 AI 和 Swagger 来节省时间自动生成测试呢?
就这样,这个小项目启动了。在这篇文章中,我会带你看看我是怎么做的,遇到了哪些挑战,以及接下来有什么有趣的可能性。
目标很简单:从 Swagger 规范中提取所有有用的信息,比如:
然后自动生成正向和负向测试场景。
比如说,对于一个简单的 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 (CLI UX) – 因为一个漂亮的 CLI 让生活更美好
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)
连接到 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
瞧,AI 就返回了类似这样的东西:
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 辅助测试的东西。
在构建这个项目的过程中,我开始畅想接下来可以做的所有事情:
可能性无穷无尽。
这个项目真的让我看到了 AI + OpenAPI = 巨大的时间节省。
与其手工为每个端点编写数十个测试不如,我现在有了一个自动化系统,可以在几分钟内生成正向和负向测试场景。
下一步?考虑更大的目标:将其与 CI/CD 管线集成,接入测试管理工具,甚至让它实时监控 API。更智能、更快速、痛苦少得多的 API 测试——听起来就是个胜利。
如果你想查看完整项目、浏览代码或自己试试,一切都在我的 GitHub 上:API Test Generator。
深入其中,做做实验,看看你能节省多少时间吧!
有些评论可能仅对登录用户可见。登录查看所有评论。
如需后续操作,可以考虑屏蔽此人和/或举报滥用。