pytest 接口自动化框架代码 结合allure
时间: 2023-05-29 16:05:25 浏览: 166
以下是pytest接口自动化框架代码,并结合allure进行测试报告展示:
```python
import pytest
import requests
import allure
@allure.feature('API Test')
class TestApi:
@allure.story('Get Request')
def test_get_request(self):
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
assert response.status_code == 200
response_json = response.json()
assert response_json["userId"] == 1
assert response_json["id"] == 1
assert response_json["title"] == "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
assert response_json["body"] == "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
@allure.story('Post Request')
def test_post_request(self):
url = "https://jsonplaceholder.typicode.com/posts"
payload = {
"userId": 1,
"title": "test title",
"body": "test body"
}
headers = {
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
assert response.status_code == 201
response_json = response.json()
assert response_json["userId"] == 1
assert response_json["title"] == "test title"
assert response_json["body"] == "test body"
if __name__ == '__main__':
pytest.main(['-s', '-q', '--alluredir', './report'])
```
以上代码中,使用了pytest进行接口自动化测试,并结合allure进行测试报告展示。在每个测试用例上添加了@allure.feature和@allure.story装饰器,用于定义测试用例的特性和故事,方便测试报告展示和分类。
在运行pytest时,使用--alluredir指定测试报告生成的目录,然后使用allure命令生成测试报告,例如:
```
allure generate ./report -o ./report_html --clean
```
以上命令会在report目录下生成测试报告,并保存在report_html目录下。可以使用浏览器打开report_html/index.html文件查看测试报告。
阅读全文