Skip to main content
 首页 » 编程设计

python之无法模拟打开,即使使用文档中的示例也是如此

2024年10月17日6zengkefu

我直接从 Python mock docs 中复制并粘贴了以下代码:

from unittest.mock import patch, mock_open 
 
with patch('__main__.open', mock_open(read_data='bibble')) as m: 
    with open('foo') as h: 
        result = h.read() 
 
m.assert_called_once_with('foo') 
assert result == 'bibble' 

当我运行它时,出现以下错误:

AttributeError: <module '__main__' from 'path/to/file'> does not have the attribute 'open' 

鉴于这是文档中给出的示例,我不确定还有什么地方可以求助。我正在运行 Python 3.4.5。

请您参考如下方法:

我想通了。

open 是内置的,所以我需要修补 builtins.open,而不是 __main__.open。

跳过文档中的此信息。