API(应用程序编程接口)是现代软件开发的重要组成部分,它在客户端和服务器端之间传递数据。在测试中,如何快速生成不同的API请求,并验证响应数据,通常是测试工程师需要解决的难题。本文将探讨如何利用OpenAI,生成API请求,解析响应,并将其集成到测试框架中。
我们以一个简单的电商网站为例,假设该网站提供一个查询商品的API接口,测试工程师需要验证接口的行为。
场景背景
被测试的API接口:
GET /api/products
接口功能:返回商品列表,支持按类别(category
)、排序(sort
)、数量限制(limit
)进行查询。
请求示例:
GET /api/products?category=electronics&sort=price_asc&limit=5
响应示例:
{
"products": [
{"id": 1, "name": "Smartphone", "price": 199},
{"id": 2, "name": "Laptop", "price": 999}
],
"total_count": 2
}
目标是:
- 自动生成API请求参数。
- 验证响应内容是否符合预期。
步骤1:安装依赖
首先,我们需要安装OpenAI的Python库以调用GPT-3.5-Turbo模型:
pip install openai
步骤2:生成API请求
利用自然语言描述测试场景,GPT-3.5-Turbo可以生成符合测试需求的API请求。以下是一个代码示例,生成API请求的查询参数:
import openai
# 配置OpenAI API密钥
openai.api_key = "your_openai_api_key"
# 使用自然语言生成API请求参数
def generate_api_request(category, sort, limit):
# 自然语言描述请求需求
prompt = (
f"Generate query parameters for an API request to fetch products. "
f"The category is '{category}', sorted by '{sort}', and the limit is {limit} products."
)
# 调用GPT模型生成结果
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
# 返回生成的查询参数
return response['choices'][0]['message']['content']
# 示例调用
category = "electronics"
sort = "price_asc"
limit = 5
api_request = generate_api_request(category, sort, limit)
print("Generated API Request:", api_request)
运行结果:
Generated API Request: category=electronics&sort=price_asc&limit=5
GPT模型根据输入需求生成了查询参数,我们可以直接将其用于API测试。
步骤3:解析API响应
假设服务器返回以下响应:
{
"products": [
{"id": 1, "name": "Smartphone", "price": 199},
{"id": 2, "name": "Laptop", "price": 999}
],
"total_count": 2
}
我们可以利用GPT模型分析响应内容,并提取关键信息:
# 使用自然语言解析API响应
def parse_api_response(response):
# 将响应数据作为上下文
prompt = (
f"Analyze the following JSON response from an API. Extract the total product count "
f"and list the product names with their prices. Response: {response}"
)
# 调用GPT模型
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
# 返回解析结果
return response['choices'][0]['message']['content']
# 示例响应数据
response_data = {
"products": [
{"id": 1, "name": "Smartphone", "price": 199},
{"id": 2, "name": "Laptop", "price": 999}
],
"total_count": 2
}
# 调用解析函数
parsed_response = parse_api_response(response_data)
print("Parsed Response:", parsed_response)
运行结果:
Parsed Response: Total product count: 2
Product names with their prices:
1. Smartphone - $199
2. Laptop - $999
GPT模型成功提取了响应中的关键信息,这有助于验证API返回的数据是否正确。
步骤4:集成到测试框架
为了让测试自动化,我们可以将上述逻辑集成到pytest
框架中。以下是一个完整的测试示例:
import pytest
# 模拟一个发送API请求的函数
def send_request(query_params):
# 模拟API响应(实际中需要通过requests库发送请求)
return {
"products": [
{"id": 1, "name": "Smartphone", "price": 199},
{"id": 2, "name": "Laptop", "price": 999}
],
"total_count": 2
}
# 测试案例:验证API响应
@pytest.mark.parametrize("category, sort, limit, expected_count", [
("electronics", "price_asc", 5, 2),
("furniture", "price_desc", 3, 0)
])
def test_api(category, sort, limit, expected_count):
# Step 1: 生成API请求参数
query_params = generate_api_request(category, sort, limit)
print(f"Generated Query Params: {query_params}")
# Step 2: 发送请求并获取响应
response = send_request(query_params)
print(f"API Response: {response}")
# Step 3: 解析响应
parsed_response = parse_api_response(response)
print(f"Parsed Response: {parsed_response}")
# Step 4: 验证响应内容
assert response["total_count"] == expected_count, "Product count mismatch"
for product in response["products"]:
assert "id" in product
assert "name" in product
assert "price" in product
执行测试
运行测试命令:
pytest test_api.py
测试框架将自动完成以下流程:
- 调用GPT生成请求参数。
- 模拟发送请求,获取响应。
- 使用GPT解析响应内容。
- 验证响应与预期是否匹配。
Pytest测试结果报告示例:
============================= test session starts =============================
collecting ... collected 2 items
apidemo2.py::test_api[electronics-price_asc-5-2]
apidemo2.py::test_api[furniture-price_desc-3-0]
========================= 1 failed, 1 passed in 4.82s =========================
PASSED [ 50%]Generated Query Params: API request query parameters:
- category: electronics
- sort: price_asc
- limit: 5
API Response: {'products': [{'id': 1, 'name': 'Smartphone', 'price': 199}, {'id': 2, 'name': 'Laptop', 'price': 999}], 'total_count': 2}
Parsed Response: Total product count: 2
Product Names with Prices:
1. Smartphone - $199
2. Laptop - $999
FAILED [100%]Generated Query Params: category=furniture&sort=price_desc&limit=3
API Response: {'products': [{'id': 1, 'name': 'Smartphone', 'price': 199}, {'id': 2, 'name': 'Laptop', 'price': 999}], 'total_count': 2}
Parsed Response: Total product count: 2
Product name: Smartphone, Price: $199
Product name: Laptop, Price: $999
apidemo2.py:59 (test_api[furniture-price_desc-3-0])
2 != 0
Expected :0
Actual :2
<Click to see difference>
category = 'furniture', sort = 'price_desc', limit = 3, expected_count = 0
@pytest.mark.parametrize("category, sort, limit, expected_count", [
("electronics", "price_asc", 5, 2),
("furniture", "price_desc", 3, 0)
])
def test_api(category, sort, limit, expected_count):
# Step 1: 生成API请求参数
query_params = generate_api_request(category, sort, limit)
print(f"Generated Query Params: {query_params}")
# Step 2: 发送请求并获取响应
response = send_request(query_params)
print(f"API Response: {response}")
# Step 3: 解析响应
parsed_response = parse_api_response(response)
print(f"Parsed Response: {parsed_response}")
# Step 4: 验证响应内容
> assert response["total_count"] == expected_count, "Product count mismatch"
E AssertionError: Product count mismatch
E assert 2 == 0
apidemo2.py:78: AssertionError
Process finished with exit code 1
总结
通过GPT-3.5-Turbo的自然语言能力,测试工程师可以:
- 快速生成不同场景的API请求参数。
- 自动解析复杂的API响应,提取关键信息。
- 提升效率,将生成与解析逻辑集成到自动化测试框架中。
这种方法不仅提高了接口测试的效率,还能覆盖更多的测试场景,为测试工程师提供了强有力的支持。