Python+request+pytest+allure核心代码
时间: 2023-12-22 20:29:02 浏览: 99
pytest+yaml+allure+requests 框架源码带注释版本
5星 · 资源好评率100%
以下是一个使用Python + requests + pytest + allure的核心代码示例:
```python
import requests
import pytest
import allure
@allure.feature("接口测试")
class TestAPI:
@allure.story("测试接口1")
def test_api1(self):
url = "http://api.example.com/api1"
headers = {"Content-Type": "application/json"}
data = {"key": "value"}
response = requests.post(url, headers=headers, json=data)
assert response.status_code == 200
assert response.json()["result"] == "success"
allure.attach(name="请求参数", body=str(data), attachment_type=allure.attachment_type.JSON)
allure.attach(name="响应结果", body=str(response.json()), attachment_type=allure.attachment_type.JSON)
@allure.story("测试接口2")
def test_api2(self):
url = "http://api.example.com/api2"
headers = {"Content-Type": "application/json"}
data = {"key": "value"}
response = requests.post(url, headers=headers, json=data)
assert response.status_code == 200
assert response.json()["result"] == "success"
allure.attach(name="请求参数", body=str(data), attachment_type=allure.attachment_type.JSON)
allure.attach(name="响应结果", body=str(response.json()), attachment_type=allure.attachment_type.JSON)
if __name__ == "__main__":
pytest.main(["-s", "-v", "--alluredir", "./allure-results"])
```
这段代码演示了如何使用Python的requests库发送HTTP请求,并结合pytest和allure进行接口测试。其中,`test_api1`和`test_api2`是两个测试用例,分别发送POST请求到不同的接口,并对响应结果进行断言。使用allure的`attach`方法可以将请求参数和响应结果作为附件展示在测试报告中。
阅读全文