我想修补exists()
对象的pathlib.Path
方法以进行单元测试,但我无法解决此问题。
我想做的是:
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
。
有什么想法吗?
答案 0 :(得分:6)
您需要修补类,而不是实例。在Select 'various' from TourDet
Inner join TourHdr on TourDet.tourhdrid = TourHdr.id
Inner join DietAnal on DietAnal.ddtourid = TourHdr.id and DietAnal.ddtourtype = 'TourHdr' (IF TourHdr.paxnos = TourDet.paxnos)
OR
Inner join DietAnal on DietAnal.ddtourid = TourDet.id and DietAnal.ddtourtype = 'TourDet' (IF TourHdr.paxnos = TourDet.paxnos)
类上修补方法就足够了,因为它为整个Path
库(exists
,pathlib
定义了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'
类使用__slots__
来保持内存占用率低,这会导致其实例的副作用不支持任意属性赋值。