You are a Python Coder Expert,I have something to ask you.
1、使用pytest+request及csv文件实现接口自动化测试,每一行是一条用例
2、将服务端,请求方式,请求地址,请求参数,断言,存放与csv文件
3、将接口响应结果及断言结果写入csv文件
Sure, I can help you with that. Here is an example implementation for your reference:
First, you need to install the necessary packages, pytest and requests:
pip install pytest requests
Next, create a CSV file to store the test data. For example, let's create a file named "test_data.csv" with the following contents:
service,method,url,params,expected_status_code,expected_response
add_user,POST,http://localhost:8000/users,{"name": "John", "age": 30},200,{"success": true}
get_user,GET,http://localhost:8000/users/1,200,{"name": "John", "age": 30}
In this example, we have two test cases: "add_user" and "get_user". The "params" field contains the request parameters in JSON format, and the "expected_response" field contains the expected response in JSON format.
Now, create a Python file named "test_api.py" with the following contents:
import csv
import json
import pytest
import requests
def read_test_data():
with open('test_data.csv') as f:
reader = csv.DictReader(f)
return list(reader)
def write_test_result(test_data, response, assert_result):
with open('test_result.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow([
test_data['service'],
test_data['method'],
test_data['url'],
test_data['params'],
test_data['expected_status_code'],
test_data['expected_response'],
response.status_code,
response.text,
assert_result
])
@pytest.mark.parametrize('test_data', read_test_data())
def test_api(test_data):
# Prepare the request
method = test_data['method']
url = test_data['url']
params = json.loads(test_data['params'])
expected_status_code = int(test_data['expected_status_code'])
expected_response = json.loads(test_data['expected_response'])
# Send the request
response = requests.request(method, url, json=params)
# Check the response
assert response.status_code == expected_status_code
assert response.json() == expected_response
# Write the test result to the CSV file
assert_result = 'Pass' if response.status_code == expected_status_code and response.json() == expected_response else 'Fail'
write_test_result(test_data, response, assert_result)
In this example, we define a read_test_data function to read the test data from the CSV file, and a write_test_result function to write the test result to another CSV file named "test_result.csv". The test_api function is the actual test function that uses the pytest.mark.parametrize decorator to run multiple test cases based on the test data read from the CSV file.
To run the test, simply execute the following command in the terminal:
pytest test_api.py
This will run the test and generate a "test_result.csv" file with the following contents:
service,method,url,params,expected_status_code,expected_response,status_code,response,assert_result
add_user,POST,http://localhost:8000/users,{"name": "John", "age": 30},200,{"success": true},200,{"success": true},"Pass"
get_user,GET,http://localhost:8000/users/1,,200,{"name": "John", "age": 30},200,{"name": "John", "age": 30},"Fail"
In this example, the "add_user" test case passed and the "get_user" test case failed because the expected response did not match the actual response.
翻译成中文
好的,我可以帮你完成这个任务。以下是一个示例实现:
首先,你需要安装必要的包pytest和requests:
pip install pytest requests
接下来,创建一个CSV文件来存储测试数据。例如,我们创建一个名为 "test_data.csv" 的文件,其内容如下:
service,method,url,params,expected_status_code,expected_response
add_user,POST,http://localhost:8000/users,{"name": "John", "age": 30},200,{"success": true}
get_user,GET,http://localhost:8000/users/1,200,{"name": "John", "age": 30}
在这个示例中,我们有两个测试用例:"add_user"和"get_user"。 "params"字段包含JSON格式的请求参数,“expected_response”字段包含JSON格式的预期响应。
现在,创建一个名为 "test_api.py" 的Python文件,其内容如下:
import csv
import json
import pytest
import requests
def read_test_data():
with open('test_data.csv') as f:
reader = csv.DictReader(f)
return list(reader)
def write_test_result(test_data, response, assert_result):
with open('test_result.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow([
test_data['service'],
test_data['method'],
test_data['url'],
test_data['params'],
test_data['expected_status_code'],
test_data['expected_response'],
response.status_code,
response.text,
assert_result
])
@pytest.mark.parametrize('test_data', read_test_data())
def test_api(test_data):
# 准备请求
method = test_data['method']
url = test_data['url']
params = json.loads(test_data['params'])
expected_status_code = int(test_data['expected_status_code'])
expected_response = json.loads(test_data['expected_response'])
# 发送请求
response = requests.request(method, url, json=params)
# 检查响应
assert response.status_code == expected_status_code
assert response.json() == expected_response
# 将测试结果写入CSV文件
assert_result = 'Pass' if response.status_code == expected_status_code and response.json() == expected_response else 'Fail'
write_test_result(test_data, response, assert_result)
在这个示例中,我们定义了一个read_test_data函数来从CSV文件中读取测试数据,以及一个write_test_result函数来将测试结果写入另一个名为 "test_result.csv" 的CSV文件中。 test_api函数是实际的测试函数,使用pytest.mark.parametrize装饰器基于从CSV文件中读取的测试数据运行多个测试用例。
要运行测试,只需在终端中执行以下命令:
pytest test_api.py
这将运行测试并生成一个带有以下内容的 "test_result.csv" 文件:
service,method,url,params,expected_status_code,expected_response,status_code,response,assert_result
add_user,POST,http://localhost:8000/users,{"name": "John", "age": 30},200,{"success": true},200,{"success": true},"Pass"
get_user,GET,http://localhost:8000/users/1,,200,{"name": "John", "age": 30},200,{"name": "John", "age": 30},"Fail"
在这个示例中,"add_user"测试用例通过了,而"get_user"测试用例失败了,因为预期响应与实际响应不匹配。
断言的信息是取了返回值中的某个字段去做校验,例如result["data"]["list"][0]["orderNo"]。麻烦重新设计下代码
好的,这里是一个重新设计的代码示例,它将使用返回值中的某些字段来执行校验:
import csv
import json
import pytest
import requests
def read_test_data():
with open('test_data.csv') as f:
reader = csv.DictReader(f)
return list(reader)
def write_test_result(test_data, response, assert_result):
with open('test_result.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow([
test_data['service'],
test_data['method'],
test_data['url'],
test_data['params'],
test_data['expected_status_code'],
test_data['expected_response'],
response.status_code,
response.text,
assert_result
])
@pytest.mark.parametrize('test_data', read_test_data())
def test_api(test_data):
# 准备请求
method = test_data['method']
url = test_data['url']
params = json.loads(test_data['params'])
expected_status_code = int(test_data['expected_status_code'])
expected_response = json.loads(test_data['expected_response'])
# 发送请求
response = requests.request(method, url, json=params)
# 检查响应
assert response.status_code == expected_status_code
assert_result = 'Pass'
if 'assertions' in test_data:
assertions = json.loads(test_data['assertions'])
for assertion in assertions:
value = response.json()
for key in assertion['key'].split('.'):
value = value[key]
assert value == assertion['expected_value'], f"Assertion failed for {assertion['key']}"
if value != assertion['expected_value']:
assert_result = 'Fail'
# 将测试结果写入CSV文件
write_test_result(test_data, response, assert_result)
在这个示例中,我们添加了一个名为"assertions"的字段,用于存储需要执行的断言列表。每个断言都包含一个 "key" 字段,该字段指定要检查的响应值的路径,以及一个 "expected_value" 字段,该字段指定预期值。
我们使用response.json()方法获取响应的JSON对象,并使用key字段指定的路径来获取要检查的值。然后我们将该值与expected_value字段中的预期值进行比较。如果有任何断言失败,则将assert_result设置为 "Fail"。
现在,我们可以在CSV文件中添加一个名为"assertions"的新字段,以便在测试用例中指定所需的断言。例如,以下是一个包含断言的测试数据的示例:
service,method,url,params,expected_status_code,expected_response,assertions
get_user,GET,http://localhost:8000/users/1,,200,{"data": {"id": 1, "name": "John", "age": 30, "orders": [{"orderNo": "12345"}]}},[{"key": "data.id", "expected_value": 1}, {"key": "data.orders.0.orderNo", "expected_value": "12345"}]
在这个示例中,我们添加了一个名为 "assertions" 的字段,它包含一个JSON数组,其中包含两个断言。第一个断言将检查 "data.id" 的值是否等于1,第二个断言将检查第一个订单的 "orderNo" 值是否等于 "12345"。
现在,我们可以运行pytest来运行测试:
pytest test_api.py
如果测试通过,则将生成一个名为 "test_result.csv" 的CSV文件,其内容如下:
service,method,url,params,expected_status_code,expected_response,status_code,response,assert_result
get_user,GET,http://localhost:8000/users/1,,200,{"data": {"id": 1, "name": "John", "age": 30, "orders": [{"orderNo": "12345"}]}},200,{"data": {"id": 1, "name": "John", "age": 30, "orders": [{"orderNo": "12345"}]},"assert_result": "Pass"}
在这个示例中,测试用例通过了,因为所有断言都成功。注意,我们添加了一个名为 "assert_result" 的新字段,以将测试结果写入CSV文件中。
例如,以下是我的一个包含断言的测试数据示例