【问题标题】:Unable to mock open, even when using the example from the documentation即使使用文档中的示例,也无法模拟打开
【发布时间】:2016-08-25 21:33:24
【问题描述】:

我直接从 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。

【问题讨论】:

    标签: python python-3.x io mocking


    【解决方案1】:

    我想通了。

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

    跳过文档中的此信息。

    【讨论】:

      【解决方案2】:

      嗯,__main__ 是您运行脚本时默认给出的模块名称。

      将代码粘贴到 python 文件中并调用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-04
        • 1970-01-01
        • 2019-04-20
        • 2011-10-29
        相关资源
        最近更新 更多