模拟模块变量而不是可调用的

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

如果我想使用以下代码模拟模块内的变量:

@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
对象返回。

如何将其作为

Path
对象(或任何其他需要的类型)返回?

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

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

python mocking pytest
1个回答
-1
投票

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

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

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.