python - assert_called_with 其中 AttributeError 作为 arg 传递

python - assert_called_with where AttributeError is passed as arg

我正在尝试对名为 TargetException 的自定义异常进行单元测试。

此异常的参数之一本身就是一个异常。

这是我测试的相关部分:

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',))

在“预期调用”和“操作调用”中,存在相同的参数——至少在我看来是这样。

我是否需要通过其他方式传递 AttributeError 来解决错误?

问题是您比较了包含的异常的实例。由于被测函数中创建的AttributeError实例与测试中用于比较的实例不同,断言失败。

您可以做的是分别测试调用的参数以确保它们的类型正确:

@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

例如您分别测试 class 和参数的相关值。使用 assert_called_with 仅适用于 PODs,或者如果您已经知道被调用的实例(例如,如果它是单例或已知的模拟)。

基于 MrBean Bremen 的回答。

解决这个问题的另一种方法是将异常保存在 var 中并检查 var:

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