问题描述
给出以下Python代码:
Given this Python code:
elif request.method == 'DELETE':
try:
os.remove(full_file)
return jsonify({'results':'purged %s' % full_file})
except OSError as e:
if e.errno != errno.ENOENT:
raise
return jsonify({'results':'file not present: %s' % full_file})
我想测试所有可能的路径,包括异常处理.使用Mock,可以很容易地引发一个异常,这是我使用以下代码完成的:
I want to test all possible paths, including the exception handling. Using Mock, it's easy enough to raise an exception, which I do with this code:
with patch('os.remove', new=Mock(side_effect=OSError(errno.ENOENT))):
self.assertRaises(OSError, self.app.delete, file_URL) # broken
Mock引发一个异常,该异常的打印值为2(ENOENT)-但 e.errno 设置为NONE.到目前为止,我还没有找到一种设置方法.结果是,异常总是被重新引发,并且在单元测试中,我从未到达最后一行代码.
Mock raises an exception, which has a printed value of 2 (ENOENT) - but e.errno is set to NONE. And so far, I have not found a way to set it. The result is, the exception always gets re-raised, and I never reach the last line of code, in my unit test.
我也尝试过创建一个带有errno集的虚拟类,并返回它.但是除非设置了* side_effect *,否则它不会引发异常,而且当我设置side_effect时,也不会获得object.errno作为返回值.
I've also tried creating a dummy class with errno set, and returning that. But unless it has *side_effect* set to be called, it doesn't raise an exception, and when I set side_effect, I don't get the object.errno as a return value.
有没有一种方法可以让Mock引发Exception,而该Exception对象具有 errno 属性集?
Is there a way to have Mock raise an Exception, where that Exception object has the errno attribute set?
推荐答案
将两个参数传递给OSError构造函数. (第一个应该是errno
).
Pass two arguments to OSError constructor. (First one should be errno
).
例如:
>>> OSError(2).errno
>>> OSError(2, 'message').errno
2
>>> OSError(2, 'message').strerror
'message'
这篇关于如何使用Python Mock引发异常-但将Errno设置为给定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!