做 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)
連接到人工智慧很簡單:建立一個客戶端,設定模型,然後傳遞提示訊息:
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) 中實際運作且不顯得笨拙的工作流程。
但最終,這真的很有趣,我也學到了很多關於人工智慧輔助測試的知識。
在建造這個的過程中,我開始憧憬接下來我可以做的所有事情:
從這些測試中自動產生Postman 集合
與 Zephyr 或 Xray 等測試管理工具集成
將其設定為服務,用於監控 Swagger 並在端點變更時更新測試。
可能性無窮無盡。
這個專案讓我真正體會到, AI + OpenAPI = 可以節省大量時間。
現在,我不再需要手動為每個端點編寫數十個測試案例,而是擁有一個自動化系統,可以在幾分鐘內產生正面和負面場景。
下一步?放眼更廣闊的領域:將其整合到 CI/CD 管線中,接取測試管理工具,甚至實現 API 的即時監控。更聰明、更快速、更輕鬆的 API 測試——這聽起來簡直完美。
如果您想查看完整的專案、探索程式碼或親自嘗試,所有內容都在我的 GitHub 上: API 測試產生器。
大膽嘗試,看看你能節省多少時間!