模拟-如何在呼叫者上引发异常? [英] Mocking - How do I raise exception on the caller?

查看:60
本文介绍了模拟-如何在呼叫者上引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这是代码

def move(*args, **kwargs):   
    try:
        shutil.move(source, destination)
    except Exception as e:
        raise e

以及在我的tests.py

and in my 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)

说了

  File "unittests.py", line 84, in test_move_catch_exception
    self.src_f, self.src_f, **self.kwargs)
AssertionError: Exception not raised

如果我在mock_rmtree上断言,它将通过.如何在调用方上断言(在本例中为函数move)?

If I assert on mock_rmtree it will pass. How can I assert on the caller (in this case, the function move)?

正如 aquavitae 所指出的,主要原因是复制粘贴错误,而且我在一开始就声明了一个元组.始终用正确的返回类型声明...

As aquavitae pointed out, the primary reasons was copy-paste error, and also I was asserting a tuple in the beginning. Always asseert with the right return type...

推荐答案

示例中有错字,缺少'.

尚不清楚您要问的是什么,但是如果我对您的理解正确,那么您在问如何测试move中是否捕获了引发的异常.一个问题是您要修补shutil.rmtree,而不是shutil.move,但是不能确定是否会调用shutil.rmtree. shutil.move仅在成功复制目录后才实际调用shutil.rmtree,但是由于您正在将self.src_f复制到其自身,因此不会发生这种情况.不过,这不是修补它的好方法,因为无法保证shutil.move会完全调用shutil.rmtree的假设,并且取决于实现.

Its not entirely clear what you're asking, but if I understand you correctly, you're asking how to test that a raised exception is caught inside move. One problem is that you're patching shutil.rmtree, not shutil.move, but you can't be certain thatshutil.rmtree will ever be called. shutil.move only actually calls shutil.rmtree if it successfully copies a directory, but since you're copying self.src_f to itself, this doesn't happen. This is not a very good way of patching it though, because the assumption that shutil.move will call shutil.rmtree at all is not guaranteed and is implementation dependent.

关于如何测试它,只需检查返回值是否符合预期:

As for how to test it, simply check that the return value is as expected:

@patch.object(shutil, 'move')
def test_move_catch_exception(self, mock_move):
    ''' Tests moving a target hits exception. '''
    e = OSError('abc')
    mock_move.side_effect = e
    returns = move(self.src_f, self.src_f, **self.kwargs)
    assert returns == (False, e)

这篇关于模拟-如何在呼叫者上引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆