問題描述
假設(shè)這是代碼
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
上斷言它會通過.如何對調(diào)用者進(jìn)行斷言(在本例中為函數(shù) move
)?
If I assert on mock_rmtree
it will pass. How can I assert on the caller (in this case, the function move
)?
正如 aquavitae 指出的那樣,主要原因是復(fù)制粘貼錯誤,而且我一開始就斷言了一個元組.始終斷言正確的返回類型...
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...
推薦答案
您的示例中有錯字,缺少 '
.
You've got a typo in your example, missing a '
.
不完全清楚你在問什么,但如果我理解正確的話,你問的是如何測試在 move
中捕獲了引發(fā)的異常.一個問題是您正在修補 shutil.rmtree
,而不是 shutil.move
,但您不能確定 shutil.rmtree
是否會永遠(yuǎn)被稱為.shutil.move
僅在成功復(fù)制目錄時才實際調(diào)用 shutil.rmtree
,但是由于您將 self.src_f
復(fù)制到自身,因此不會發(fā)生.雖然這不是一個很好的修補方法,因為 shutil.move
將調(diào)用 shutil.rmtree
的假設(shè)根本無法保證,并且取決于實現(xiàn).
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.
至于如何測試,簡單檢查返回值是否符合預(yù)期:
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)
這篇關(guān)于模擬 - 如何在調(diào)用者上引發(fā)異常?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!