gpt4 book ai didi

python - 如何修补 `pathlib.Path.exists()` 方法?

转载 作者:行者123 更新时间:2023-12-02 11:45:03 29 4
gpt4 key购买 nike

我想修补 pathlib.Path 对象的 exists() 方法以进行单元测试,但我在使其正常工作时遇到问题。

我想做的是:

from unittest.mock import patch
from pathlib import Path

def test_move_basic():
p = Path('~/test.py')
with patch.object(p, 'exists') as mock_exists:
mock_exists.return_value = True

但它失败了:

AttributeError:“PosixPath”对象属性“exists”是只读的

有什么想法吗?

最佳答案

您需要修补,而不是实例。修补 Path 类上的方法就足够了,因为它为整个 pathlib 库定义了 exists 方法( PosixPathWindowsPathPurePosixPathPureWindowsPath 均继承该实现):

>>> from unittest.mock import patch
>>> from pathlib import Path
>>> p = Path('~/test.py')
>>> with patch.object(Path, 'exists') as mock_exists:
... mock_exists.return_value = True
... p.exists()
...
True
>>> with patch.object(Path, 'exists') as mock_exists:
... mock_exists.return_value = False
... p.exists()
...
False
>>> with patch.object(Path, 'exists') as mock_exists:
... mock_exists.return_value = 'Anything you like, actually'
... p.exists()
...
'Anything you like, actually'

pathlib 类使用 __slots__以保持较低的内存占用量,这会产生其实例不支持任意属性分配的副作用。

关于python - 如何修补 `pathlib.Path.exists()` 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48864027/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com