簡體   English   中英

python - assert_called_with 其中 AttributeError 作為 arg 傳遞

[英]python - assert_called_with where AttributeError is passed as arg

我正在嘗試對名為TargetException的自定義異常進行單元測試。

此異常的 arguments 之一本身就是一個異常。

這是我測試的相關部分:

mock_exception.assert_called_once_with(
    id,
    AttributeError('invalidAttribute',)
)

這是測試失敗消息:

  File "/usr/local/lib/python2.7/site-packages/mock/mock.py", line 948, in assert_called_once_with
    return self.assert_called_with(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/mock/mock.py", line 937, in assert_called_with
    six.raise_from(AssertionError(_error_message(cause)), cause)
  File "/usr/local/lib/python2.7/site-packages/six.py", line 718, in raise_from
    raise value
AssertionError: Expected call: TargetException(<testrow.TestRow object at 0x7fa2611e7050>, AttributeError('invalidAttribute',))
Actual call: TargetException(<testrow.TestRow object at 0x7fa2611e7050>, AttributeError('invalidAttribute',))

在“預期調用”和“操作調用”中,都存在相同的 arguments——至少在我看來是這樣。

我是否需要以不同的方式傳遞 AttributeError 來解決錯誤?

問題在於您比較了所包含異常的實例。 由於在test函數中創建的AttributeError實例與test中用於比較的實例不同,斷言失敗。

你可以做的是分別測試被調用的參數以確保它們是正確的類型:

@mock.patch('yourmodule.TargetException')
def test_exception(mock_exception):
    # call the tested function
    ...
    mock_exception.assert_called_once()
    assert len(mock_exception.call_args[0]) == 2  # shall be called with 2 positional args
    arg1 = mock_exception.call_args[0][0]  # first argument
    assert isinstance(arg1, testrow.TestRow)  # type of the first arg
    ... # more tests for arg1

    arg2 = mock_exception.call_args[0][1]  # second argument
    assert isinstance(arg2, AttributeError)  # type of the second arg
    assert str(arg2) == 'invalidAttribute'  # string value of the AttributeError

例如,您分別測試類和參數的相關值。 使用assert_called_with僅適用於 POD,或者如果已經知道被調用的實例(例如,如果它是單例或已知的模擬)。

建立在 MrBean Bremen 的回答之上。

解決這個問題的另一種方法是將異常保存在 var 中並檢查 var:

ex = AttributeError('invalidAttribute',)
...
def foo():
    raise ex
...
mock_exception.assert_called_once_with(
    id,
    ex
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM