【问题标题】:How do I patch the `pathlib.Path.exists()` method?如何修补 `pathlib.Path.exists()` 方法?
【发布时间】:2018-02-19 10:24:37
【问题描述】:

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

有什么想法吗?

【问题讨论】:

  • 您需要使用Path 对象还是可以模拟整个事情?
  • 我需要Path 对象...
  • 不要修补实例。修补

标签: python unit-testing mocking pathlib


【解决方案1】:

您需要修补,而不是实例。修补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__ 来保持低内存占用,这具有其实例不支持任意属性分配的副作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-03
    • 2010-12-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    相关资源
    最近更新 更多