模拟模块变量作为自动使用

问题描述 投票:0回答:1

是否可以实现与此处所示相同的效果,但使用固定装置和自动使用?

Python 返回 MagicMock 对象而不是 return_value

到目前为止我所拥有的是以下内容:

@pytest.fixture(autouse=True)
def mock_default(mocker, tmp_path):
    """Mock Default Config File Path."""
    mocker.patch("mypackage.mymodule.DEFAULT", return_value=tmp_path / "myfile")

但这也像上面的问题一样返回 MagicMock 对象。在调试中我可以调用它并会得到

myfile
,但这不是解决方案,因为我需要更改变量的调用,它现在是可调用的而不是变量。

我在调试时注意到的:特定于路径对象的所有方法都不会引发任何错误。但作为示例

DEFAULT.touch(exsist_ok=True)
,未按预期创建文件。

python mocking pytest
1个回答
0
投票

由于我同时搜索的所有问题和答案都指向错误的方向,所以我在再次阅读(像往常一样)文档后得到了它。

因此,对于所描述的问题,解决方案是将

return_value
替换为
new

@pytest.fixture(autouse=True)
def mock_default(mocker, tmp_path):
    """Mock Default Config File Path."""
    mocker.patch("mypackage.mymodule.DEFAULT", new=tmp_path / "myfile")

仍然好奇为什么 MagicMock 在调用

Path
方法时不会抛出任何错误!

© www.soinside.com 2019 - 2024. All rights reserved.