返回
轻松构建Python接口自动化测试框架:Pytest+Allure+JSONPath+Xlrd+Excel(RESTful接口)
见解分享
2024-01-02 15:02:16
前言
接口自动化测试是指利用自动化工具对接口进行测试,以验证接口是否符合预期。接口自动化测试可以有效地提高测试效率和准确性,并减少人工测试的成本。
实现
本框架实现了以下功能:
- 支持GET/POST请求(上传文件):可以轻松地测试GET和POST请求,并支持文件上传。
- 支持RESTful接口规范:遵循RESTful接口设计原则,可以轻松地测试各种类型的接口。
- 理论上支持DELETE/PUT等请求:虽然本框架仅实现了GET和POST请求,但理论上也可以支持其他类型的请求,如DELETE、PUT等。
框架组成
本框架由以下组件组成:
- Pytest:一个流行的Python测试框架,用于编写和运行测试用例。
- Allure:一个报告生成工具,可以生成美观且易读的测试报告。
- JSONPath:一个Python库,用于解析JSON响应。
- Xlrd和Excel:用于读取和处理测试数据。
- requests:一个Python库,用于发送HTTP请求。
使用方法
安装依赖
pip install pytest allure jsonpath xlrd requests
编写测试用例
import pytest
import allure
@allure.feature("接口自动化测试")
class TestInterface:
@allure.story("GET请求")
def test_get_request(self):
response = requests.get("http://localhost:8080/api/v1/users")
assert response.status_code == 200
@allure.story("POST请求")
def test_post_request(self):
data = {"username": "test", "password": "test"}
response = requests.post("http://localhost:8080/api/v1/users", json=data)
assert response.status_code == 201
运行测试用例
pytest tests/
生成测试报告
allure generate reports/
完整示例
完整示例代码如下:
import pytest
import allure
import jsonpath
import xlrd
@allure.feature("接口自动化测试")
class TestInterface:
@allure.story("GET请求")
def test_get_request(self):
response = requests.get("http://localhost:8080/api/v1/users")
assert response.status_code == 200
@allure.story("POST请求")
def test_post_request(self):
data = {"username": "test", "password": "test"}
response = requests.post("http://localhost:8080/api/v1/users", json=data)
assert response.status_code == 201
@allure.story("解析JSON响应")
def test_parse_json_response(self):
response = requests.get("http://localhost:8080/api/v1/users")
data = jsonpath.jsonpath(response.json(), "$.data")
assert len(data) > 0
@allure.story("读取Excel数据")
def test_read_excel_data(self):
workbook = xlrd.open_workbook("test_data.xlsx")
sheet = workbook.sheet_by_index(0)
data = []
for row in range(1, sheet.nrows):
data.append(sheet.row_values(row))
assert len(data) > 0
if __name__ == "__main__":
pytest.main()
总结
本框架是一个简单易用的Python接口自动化测试框架。它可以帮助您快速搭建一个完整的接口自动化测试环境,并轻松地编写和运行测试用例。希望本文对您有所帮助。