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

如何在Pytest自动使用的测试夹具中忽略setup_class方法

解决方法

1. 先把setup_class改成标准类方法

先检查你的setup_class有没有加@classmethod装饰——要是没加,pytest会把它当成普通测试函数,自然会触发autouse夹具。改成这样:

@classmethod
def setup_class(cls):
    # 这里写你的初始化逻辑,比如准备测试环境,别创建实例

2. 调整夹具的执行逻辑

要是setup_class已经是标准类方法,但夹具还是在它之后跑,试试这两种办法:

办法一:给夹具加判断,只在测试函数后执行

默认function作用域的autouse夹具只会在test_开头的方法前后跑,但保险起见,可以加个判断,只在真正的测试函数结束后清理:

import pytest

@pytest.fixture(autouse=True)
def teardown_test(self, request):
    yield  # 先执行测试函数
    # 只处理test_开头的测试方法
    if request.node.name.startswith("test_"):
        Log.test_teardown("Deleting instance")
        Utils.compute_utils().delete_instance_and_wait_for_state(
            TestAutoValidateCpuAlignment.instance_id, teardown=True)

办法二:关掉自动触发,手动调用夹具

要是不想让夹具自动跑,就去掉autouse=True,只在需要清理的测试函数里传入夹具参数:

@pytest.fixture
def teardown_test(self):
    yield
    Log.test_teardown("Deleting instance")
    Utils.compute_utils().delete_instance_and_wait_for_state(
        TestAutoValidateCpuAlignment.instance_id, teardown=True)

# 测试函数里这么用
def test_cpu_alignment(self, teardown_test):
    # 你的测试逻辑
    pass

3. 顺便改个夹具名字(推荐)

你现在的夹具叫teardown_module,但它是类里的夹具,不是模块级的(模块级夹具要写在文件顶层,不能带self)。改成teardown_test_instance这类名字,不容易搞混。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:05:26