Python+pytest+allure 代码示例

本文展示了如何在Python环境下运用pytest和allure框架进行测试,并生成详细的测试报告。首先,介绍了环境的搭建过程,然后给出了创建测试脚本test_sample.py的示例,接着说明了运行测试命令以生成测试结果,最后解释了如何通过额外的命令将这些结果转化为可视化的allure测试报告。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境搭建见上一篇文章

简单代码如下:
创建文件:test_sample.py

import pytest
import allure

@allure.feature('测试用例')  # feature定义功能
class TestClass(object):

   @pytest.fixture(scope='function')
   def setup_function(request):
       def teardown_function
以下是一个使用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请求,并结合pytestallure进行接口测试。其中,`test_api1`和`test_api2`是两个测试用例,分别发送POST请求到不同的接口,并对响应结果进行断言。使用allure的`attach`方法可以将请求参数和响应结果作为附件展示在测试报告中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值