pytest方法间变量值传递--request夹具

相当于self对象,因为调试的时候测试用例是类似沙箱的单步运行,所以self对象的属性被阻挡在沙箱外边。

request.cls 是pytest中的一个属性,它允许您在测试类中共享数据或属性。当您使用pytest编写测试类时,request 夹具允许您在测试方法之间传递数据或设置属性。

具体来说,以下是 request.cls 的用法:

在测试类中设置属性:您可以在一个测试方法中使用 request.cls 来设置属性,然后在同一个测试类中的其他测试方法中访问这些属性。这使得在整个测试类中共享数据变得容易。

继承测试夹具:通过使用 @pytest.mark.usefixtures("request") 装饰器,您可以将 request 夹具应用于整个测试类,以使 request.cls 在整个测试类中可用。

下面是一个示例,展示了如何在pytest测试类中使用 request.cls:

python 复制代码
import pytest

class TestSample:
    def test_example1(self, request):
        # 在这个测试方法中,使用request夹具来写入属性到self对象中
        request.cls.shared_data = "Data from test_example1"
        assert 1 == 1

    def test_example2(self, request):
        # 在这个测试方法中,获取先前设置的属性
        shared_data = request.cls.shared_data
        assert shared_data == "Data from test_example1"

@pytest.mark.usefixtures("request")
class TestSampleFixture:
    pass

运行结果

python 复制代码
============================= test session starts =============================
collecting ... collected 2 items

test.py::TestSample::test_example1 PASSED                                [ 50%]
test.py::TestSample::test_example2 PASSED                                [100%]

============================== 2 passed in 0.02s ==============================

在上述示例中,request.cls 用于在 test_example1 中设置属性 shared_data,然后在 test_example2 中获取该属性。通过使用 @pytest.mark.usefixtures("request") 装饰器,我们确保 request 夹具在整个 TestSampleFixture 测试类中可用。

请注意,使用 request.cls 应该小心谨慎,确保不会引入测试之间的状态污染,因为pytest默认情况下会运行测试方法的时候不会重用测试类的实例。

相关推荐
我的xiaodoujiao2 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 22--数据驱动--参数化处理 Json 文件
python·学习·测试工具·pytest
胜天半月子2 天前
Python自动化测试 | 快速认识并了解pytest的基本使用
服务器·python·pytest
北珣.6 天前
自动化框架pytest基础
自动化·pytest
程序员杰哥7 天前
Pytest之收集用例规则与运行指定用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
学习3人组8 天前
Python + requests + pytest + allure + Jenkins 构建完整的接口自动化测试框架
python·jenkins·pytest
shao91851611 天前
Gradio全解14——使用Gradio构建MCP的服务器与客户端(4)——Python包命令:uv与uvx实战
pytest·uv·1024程序员节·npx·uvx·uv pip·ruff
我的xiaodoujiao12 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest
sky0Lan12 天前
一个类似 pytest 的 html 报告
android·html·pytest
一半烟火以谋生13 天前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
一半烟火以谋生14 天前
pytest conftest.py 使用教程
pytest