You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让pytest函数作用域fixture在测试类中仅执行一次?

问题描述

我在conftest.py中定义了一个函数作用域的fixture:

@pytest.fixture()
def registration_setup(
    test_data, # fixture 1
    credentials, # fixture 2
    deployment, # 注:原代码此处缺少逗号,需补充避免语法错误
    deployment_object # fixture 4
):
    # 测试前清理
    do_cleanup()
    yield
    # 测试后清理
    do_cleanup()

在现有测试类中,我通过自动使用的函数作用域fixture调用它,这会导致每个测试用例执行前后都触发registration_setup:

class TestClass:

    @pytest.fixture(autouse=True)
    def _inventory_cleanup(self, registration_setup):
        log('Cleanup Done!')
    
    def test_1():
        ...

    def test_2():
        ...
    
    def test_3():
        ...

现在需要创建一个新测试类,让registration_setup在整个类生命周期内仅执行一次:先执行测试前清理,运行类中所有测试,最后执行测试后清理。


解决方案

方案一:为新测试类单独定义类作用域fixture(不影响原有fixture)

如果希望保留原registration_setup的函数作用域,仅在新测试类中实现类级别的执行,可以在新测试类中定义一个类作用域的自动执行fixture,通过request.getfixturevalue()调用原fixture,这样整个类只会触发一次registration_setup的前置和后置逻辑:

class TestNewClass:
    @pytest.fixture(autouse=True, scope="class")
    def _class_registration_setup(self, request):
        # 触发原registration_setup的执行:类运行前执行前置清理,类结束后执行后置清理
        request.getfixturevalue("registration_setup")
        yield
        log("类级别清理完成")
    
    def test_a(self):
        # 测试逻辑
        ...
    
    def test_b(self):
        # 测试逻辑
        ...

方案二:修改原fixture的作用域为类级别(影响所有调用处)

如果所有使用registration_setup的场景都需要类级别的执行,可以直接修改conftest.py中fixture的scope参数为"class":

# conftest.py中修改fixture作用域
@pytest.fixture(scope="class")
def registration_setup(
    test_data,
    credentials,
    deployment,
    deployment_object
):
    do_cleanup()
    yield
    do_cleanup()

之后在新测试类中,同样通过自动执行的fixture调用它即可,此时整个类只会执行一次registration_setup的清理逻辑:

class TestNewClass:
    @pytest.fixture(autouse=True)
    def _class_cleanup(self, registration_setup):
        log("类级别清理完成")
    
    def test_a(self):
        ...
    
    def test_b(self):
        ...

内容的提问来源于stack exchange,提问作者pankaj_m05

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:45:33