假设这是代码
def move(*args, **kwargs):
try:
shutil.move(source, destination)
except Exception as e:
raise e
Run Code Online (Sandbox Code Playgroud)
在我的tests.py中
@patch.object(shutil, 'move')
def test_move_catch_exception(self, mock_rmtree):
''' Tests moving a target hits exception. '''
mock_rmtree.side_effect = Exception('abc')
self.assertRaises(Exception, move,
self.src_f, self.src_f, **self.kwargs)
Run Code Online (Sandbox Code Playgroud)
它说这个
File "unittests.py", line 84, in test_move_catch_exception
self.src_f, self.src_f, **self.kwargs)
AssertionError: Exception not raised
Run Code Online (Sandbox Code Playgroud)
如果我坚持mock_rmtree
就会通过.如何在调用者上断言(在本例中为函数move
)?
如aquavitae所指出的,主要原因是复制粘贴错误,而且我在开始时也断言了一个元组.始终使用正确的返回类型...
我正在使用Python的mock
库.我知道如何通过遵循文档来模拟类实例方法:
>>> def some_function():
... instance = module.Foo()
... return instance.method()
...
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... result = some_function()
... assert result == 'the result'
Run Code Online (Sandbox Code Playgroud)
但是,尝试模拟类实例变量但不起作用(instance.labels
在以下示例中):
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... instance.labels = [1, 1, 2, 2]
... result = some_function()
... assert result == 'the result'
Run Code Online (Sandbox Code Playgroud)
基本上,我想instance.labels
下some_function
得到我想要的价值.任何提示?
鉴于此Python代码:
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})
Run Code Online (Sandbox Code Playgroud)
我想测试所有可能的路径,包括异常处理.使用Mock,很容易引发异常,我使用此代码:
with patch('os.remove', new=Mock(side_effect=OSError(errno.ENOENT))):
self.assertRaises(OSError, self.app.delete, file_URL) # broken
Run Code Online (Sandbox Code Playgroud)
模拟引发异常,其打印值为2(ENOENT) - 但e.errno设置为NONE.到目前为止,我还没有找到一种方法来设置它.结果是,异常总是被重新引发,我的单元测试中从未到达最后一行代码.
我也尝试使用errno set创建一个虚拟类,然后返回它.但除非它有*side_effect*设置为调用,否则它不会引发异常,当我设置side_effect时,我不会将object.errno作为返回值.
有没有办法让Mock引发一个Exception,那个Exception对象是否设置了errno属性?