我正在尝试为在pathlib.Path上调用open方法的函数编写单元测试.我能够成功地模拟open方法而没有问题,但验证函数是否具有正确的行为是困难的.请参阅以下示例代码:
def test_my_function(self):
with patch.object(Path,'open') as mock_open:
my_function(*args) # This function calls Path.open
当我内省mock_open并查看_mock_mock_calls列表时,我无法找到正在写入的文件的字符串路径.通话记录如下所示:
[
call(mode='w'),call().__enter__(),call().__enter__().write('
有没有办法测试Path.open被调用时打开的路径?
最佳答案
您使用模拟对象替换了方法.这里使用模拟对象的问题是它不会绑定到Path()实例.它将被调用,但没有返回Path()实例的路径(没有双关语意).
原文链接:https://www.f2er.com/python/438962.html使用函数模拟open(),返回mock_open()
object以进一步跟踪’打开文件’的使用,在Path实例上访问时将绑定函数:
from unittest.mock import patch,mock_open
def test_my_function(self):
opener = mock_open()
def mocked_open(self,*args,**kwargs):
return opener(self,**kwargs)
with patch.object(Path,'open',mocked_open):
my_function(*args) # This function calls Path.open
现在任何Path().open()调用都会调用opener mock,记录所有文件交互和调用它的Path()对象:
>>> from pathlib import Path
>>> from unittest.mock import patch,mock_open
>>> opener = mock_open()
>>> def mocked_open(self,**kwargs):
... return opener(self,**kwargs)
...
>>> with patch.object(Path,mocked_open):
... print(Path.open)
... print(Path().open)
... with Path().open() as f:
... f.write('