【问题标题】:python - assert_called_with where AttributeError is passed as argpython - assert_called_with 其中 AttributeError 作为 arg 传递
【发布时间】:2020-09-23 19:13:00
【问题描述】:

我正在尝试对名为 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 来解决错误?

【问题讨论】:

标签: python unit-testing exception attributeerror python-mock


【解决方案1】:

问题在于您比较了包含的异常的实例。由于被测函数中创建的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

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

【讨论】:

    【解决方案2】:

    以 MrBean Bremen 的回答为基础。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 2018-08-07
      • 1970-01-01
      • 2018-11-27
      相关资源
      最近更新 更多