【发布时间】:2025-11-28 22:05:02
【问题描述】:
在我的 pytest 文件 test_foo.py 中,我正在尝试使用 monkeypatch 将 foo.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