模拟python2`file`obj的`fileno`方法

2024-03-28 16:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用mock.patchPython 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 ^{} as intended,在python2 file对象上, 在python2 file中不违背这种特殊限制?你知道吗


Tags: thepathpyimportobjectfoowithsys