如何使用mock.patch
在Python 2 file object上包装file.fileno
方法?你知道吗
当我尝试在file
实例上使用正常的mock.patch.object
时:
# file-fileno-mock.py
import sys
import tempfile
if sys.version_info < (3, 0):
import mock
else:
from unittest import mock
(foo_fileno, foo_file_path) = tempfile.mkstemp()
# Open the temporary file path and get a real file object.
with open(foo_file_path) as foo_file:
# Patch a single attribute on the real `foo_file` object.
with mock.patch.object(foo_file, 'fileno'):
# Access the `fileno` method and call it,
# which because of the mock wrapper will call a mock method instead.
fake_foo_fileno = foo_file.fileno()
assert fake_foo_fileno != foo_fileno
这在Python3中有效,但在Python2中会引发AttributeError
:
Traceback (most recent call last):
File "file-fileno-mock.py", line 15, in <module>
with mock.patch.object(foo_file, 'fileno'):
File "[…]/mock/mock.py", line 1460, in __enter__
setattr(self.target, self.attribute, new_attr)
AttributeError: 'file' object attribute 'fileno' is read-only
显然mock.patch
正试图写入foo_file.fileno
属性;python2file
类型不允许,而Python 3
equivalent允许。你知道吗
我如何use ^{file
对象上,
在python2 file
中不违背这种特殊限制?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐