python断言_称为_,其中AttributeError作为arg传递

2024-09-30 18:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: pylibpackagesusrlocalwithlinesite
1条回答
网友
1楼 · 发布于 2024-09-30 18:16:30

问题是您比较了包含的异常的实例。由于在测试函数中创建的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,或者如果您已经知道被调用的实例(例如,如果它是单例或已知的mock)

相关问题 更多 >