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

为何Pytest中TestMyTest类测试报AttributeError:无var1属性?

问题原因及解决办法

原因

  1. pytest会按测试方法名的ASCII码顺序执行用例,test_1里的数字1ASCII码比test_init里的字母i小,所以test_1会先于test_init运行。此时var1还没被赋值,访问self.var1自然会抛出AttributeError。
  2. 把初始化逻辑放在test_init这个测试方法里是错误的——所有以test_开头的方法都会被pytest当作测试用例执行,而非专门的初始化步骤,它们的执行顺序完全由pytest的排序规则决定,没法保证按你写的顺序运行。

解决办法

方案一:用类级初始化方法setup_class

这是unittest风格的初始化方式,会在类中所有测试方法执行前只运行一次:

class TestMyTest(BaseTestClass):
    ids = dict()
    task_id = list()
    output_json = None

    @classmethod
    def setup_class(cls):
        cls.var1 = Feature1()

    def test_1(self):
        self._logger.info("self.var1: {}".format(self.var1))

方案二:改用pytest fixture做初始化

定义类级别的fixture,确保初始化逻辑在测试用例前执行:

@pytest.fixture(scope="class")
def var1():
    return Feature1()

class TestMyTest(BaseTestClass):
    ids = dict()
    task_id = list()
    output_json = None

    def test_1(self, var1):
        self._logger.info("var1: {}".format(var1))

如果需要依赖其他fixture(比如你的do_setup),可以直接在fixture里引用:

@pytest.fixture(scope="class")
def var1(do_setup):
    return Feature1()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:47:28