【问题标题】:AttributeError when using Pytest monkeypatch to change fixture object attribute使用 Pytest monkeypatch 更改夹具对象属性时出现 AttributeError
【发布时间】:2025-11-28 22:05:02
【问题描述】:

在我的 pytest 文件 test_foo.py 中,我正在尝试使用 monkeypatchfoo.path 的值更改为 mock_path。但是,当我尝试以下操作时,出现错误

错误 test_foo.py::test_foo - AttributeError: 'foo' has no attribute 'path'

进行此更改的正确方法应该是什么,以便test_foo 中的foo 对象将使用mock_path 并通过该测试?

test_foo.py

import os
import pytest


class Foo:
    def __init__(self):
        self.path = os.path.join(os.getcwd(), "test.txt")
        
@pytest.fixture
def foo(monkeypatch):
    monkeypatch.setattr(Foo, 'path', 'mock_path')
    return Foo()

def test_foo(foo):
    assert foo.path == "mock_path"

【问题讨论】:

    标签: python python-3.x pytest fixtures monkeypatching


    【解决方案1】:

    您正在尝试更改类的属性而不是类实例,因此错误消息来自monkeypath.setattr - Foo 确实没有属性path,因为这是一个实例变量。

    要解决此问题,请改为修补类实例:

    @pytest.fixture
    def foo(monkeypatch):
        inst = Foo()
        monkeypatch.setattr(inst, 'path', 'mock_path')
        return inst
    

    【讨论】:

      最近更新 更多