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

时间:2018-02-19 10:24:38

标签: python unit-testing mocking pathlib

我想修补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

有什么想法吗?

1 个答案:

答案 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库(existspathlib定义了PosixPath方法, WindowsPathPurePosixPath都继承了实现):

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__来保持内存占用率低,这会导致其实例的副作用不支持任意属性赋值。