在 Python 中模拟内置 read() 函数,因此它会抛出异常
Mocking builtin read() function in Python so it throws Exception
我正在尝试测试 class 的错误处理,我需要模拟 read()
引发 MemoryError
。这是一个简化的例子。
import mock
def memory_error_read():
raise MemoryError
def read_file_by_filename(filename):
try:
handle = open(filename)
content = handle.read()
except MemoryError:
raise Exception("%s is too big" % self.filename)
finally:
handle.close()
return content
@mock.patch("__builtin__.file.read", memory_error_read)
def testfunc():
try:
read_file_by_filename("/etc/passwd")
except Exception, e:
return
print("Should have received exception")
testfunc()
当我 运行 这样做时,我得到以下回溯。
# ./read_filename.py
Traceback (most recent call last):
File "./read_filename.py", line 34, in <module>
testfunc()
File "build/bdist.linux-i686/egg/mock.py", line 1214, in patched
File "build/bdist.linux-i686/egg/mock.py", line 1379, in __exit__
TypeError: can't set attributes of built-in/extension type 'file'
看来我无法修补内置读取功能。有办法欺骗它吗?
是否可以如我所愿?
回答
下面是根据 Ben 的建议更新后的代码。
from __future__ import with_statement
...
def test_func():
with mock.patch("__builtin__.open", new_callable=mock.mock_open) as mo:
mock_file = mo.return_value
mock_file.read.side_effect = MemoryError
try:
read_file_by_filename("/etc/passwd")
except Exception, e:
if "is too big" in str(e):
return
else:
raise
print("Should have caught an exception")
你看过mock_open了吗?
您应该能够 return 一个模拟对象,它对 read() 有异常引发的副作用。
我正在尝试测试 class 的错误处理,我需要模拟 read()
引发 MemoryError
。这是一个简化的例子。
import mock
def memory_error_read():
raise MemoryError
def read_file_by_filename(filename):
try:
handle = open(filename)
content = handle.read()
except MemoryError:
raise Exception("%s is too big" % self.filename)
finally:
handle.close()
return content
@mock.patch("__builtin__.file.read", memory_error_read)
def testfunc():
try:
read_file_by_filename("/etc/passwd")
except Exception, e:
return
print("Should have received exception")
testfunc()
当我 运行 这样做时,我得到以下回溯。
# ./read_filename.py
Traceback (most recent call last):
File "./read_filename.py", line 34, in <module>
testfunc()
File "build/bdist.linux-i686/egg/mock.py", line 1214, in patched
File "build/bdist.linux-i686/egg/mock.py", line 1379, in __exit__
TypeError: can't set attributes of built-in/extension type 'file'
看来我无法修补内置读取功能。有办法欺骗它吗? 是否可以如我所愿?
回答
下面是根据 Ben 的建议更新后的代码。
from __future__ import with_statement
...
def test_func():
with mock.patch("__builtin__.open", new_callable=mock.mock_open) as mo:
mock_file = mo.return_value
mock_file.read.side_effect = MemoryError
try:
read_file_by_filename("/etc/passwd")
except Exception, e:
if "is too big" in str(e):
return
else:
raise
print("Should have caught an exception")
你看过mock_open了吗?
您应该能够 return 一个模拟对象,它对 read() 有异常引发的副作用。