即使使用文档中的示例,也无法模拟打开 [英] Unable to mock open, even when using the example from the documentation

查看:72
本文介绍了即使使用文档中的示例,也无法模拟打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我直接从Python 模拟文档:

I've copied and pasted the following code directly from the 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'

运行此命令时,出现以下错误:

When I run this I get the following error:

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

鉴于这是文档中给出的示例,所以我不确定该向何处转向.我正在运行Python 3.4.5.

Given that this is the example given in the documentation, I'm not sure where else to turn. I'm running Python 3.4.5.

推荐答案

我知道了.

open 是内置的,因此我需要修补 builtins.open ,而不是 __ main __.open .

open is a builtin, so I needed to patch builtins.open, not __main__.open.

跳过了文档中的此信息.

Skipped over this info in the docs.

这篇关于即使使用文档中的示例,也无法模拟打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆