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

Python:如何访问pytest fixture中的属性

问题解决:AttributeError: 'function' object has no attribute 'total'

你的代码存在两个核心问题:

  1. Fixture函数numbers最后返回了函数自身(return numbers),导致测试用例中拿到的是函数对象,而非包含total属性的数据结构。
  2. Fixture内部定义的one、two、total都是局部变量,无法直接作为属性被外部访问。

以下是两种常用的修复方案:

方案一:用字典存储属性

把需要暴露的变量存入字典,测试用例通过键名访问:

conftest.py(注意你原文件名拼写错误,pytest识别的固定文件名是conftest.py)

@pytest.fixture(scope="session")
def numbers():
    one = 1
    two = 2
    total = one + two
    return {"one": one, "two": two, "total": total}

num.py

def test(numbers):
    print("total = ", numbers["total"])

方案二:返回自定义类实例

如果需要更贴近“对象属性”的访问方式,可以定义简单类,将变量作为实例属性:

conftest.py

class Numbers:
    def __init__(self):
        self.one = 1
        self.two = 2
        self.total = self.one + self.two

@pytest.fixture(scope="session")
def numbers():
    return Numbers()

num.py

def test(numbers):
    print("total = ", numbers.total)

额外提示

务必确保fixture文件名是conftest.py,pytest会自动扫描该文件加载fixture,否则可能出现fixture无法被识别的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 16:55:54