如何修补 `pathlib.Path.exists()` 方法?
How do I patch the `pathlib.Path.exists()` method?
我想为单元测试修补 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' object attribute 'exists' is read-only
.
有什么想法吗?
您需要修补 class,而不是实例。在 Path
class 上修补方法就足够了,因为它为整个 pathlib
库定义了 exists
方法(PosixPath
,WindowsPath
, PurePosixPath
和 PureWindowsPath
都继承了实现):
>>> 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
classes 使用 __slots__
来保持低内存占用,side-effect 它们的实例不支持任意属性分配。
我想为单元测试修补 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' object attribute 'exists' is read-only
.
有什么想法吗?
您需要修补 class,而不是实例。在 Path
class 上修补方法就足够了,因为它为整个 pathlib
库定义了 exists
方法(PosixPath
,WindowsPath
, PurePosixPath
和 PureWindowsPath
都继承了实现):
>>> 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
classes 使用 __slots__
来保持低内存占用,side-effect 它们的实例不支持任意属性分配。