如何在单元测试中模拟parameterNotFoundBotO3异常?

2024-06-28 20:35:13 发布

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

我想测试一些错误处理逻辑,所以我想在单元测试中模拟特定的异常类型。我在模仿对boto3的调用,但是我想用这个mock来引发一个ParameterNotFound异常。我正在测试的代码follows this pattern

boto3_client = boto3.client('ssm')
try:
    temp_var = boto3_client.get_parameter(Name="Something not found")['Parameter']['Value']
except boto3_client.exceptions.ParameterNotFound:
    ... [logic I want to test]

我已经创建了一个unittest模拟,但是我不知道如何使它引发异常,因为这个ParameterNotFound异常。我尝试了以下方法,但没有成功,因为它在计算except子句时得到“exceptions must derivate from the base class”:

^{pr2}$

如何在单元测试中模拟parameterNotFoundBotO3异常?在


Tags: 代码client类型单元测试逻辑thisboto3mock
1条回答
网友
1楼 · 发布于 2024-06-28 20:35:13

我想问题是我误解了boto3是如何引发异常的。我在这里找到了一个解释:https://github.com/boto/boto3/issues/1262在“ClientError的结构”下

Structure of a ClientError

Within ClientError (but not BotoCoreError), there will be an operation_name attribute (should be a str) and a response attribute (should be a dict). The response attribute should have the following form (example from a malformed ec2.DescribeImages call):

还有这里:https://codeday.me/en/qa/20190306/12210.html

{
    "Error": {
        "Code": "InvalidParameterValue",
        "Message": "The filter 'asdfasdf' is invalid"
    },
    "ResponseMetadata": {
        "RequestId": "aaaabbbb-cccc-dddd-eeee-ffff00001111",
        "HTTPStatusCode": 400,
        "HTTPHeaders": {
            "transfer-encoding": "chunked",
            "date": "Fri, 01 Jan 2100 00:00:00 GMT",
            "connection": "close",
            "server": "AmazonEC2"
        },
        "RetryAttempts": 0
    }
}

听起来异常是作为一个ClientError抛出的,它有一个ParameterNotFound错误代码,所以我需要将其更改为

^{pr2}$

然后呢

except ClientError as e:

在嘲讽中,我需要引发一个ClientError,它的参数notfound作为代码:

raise botocore.exceptions.ClientError({"Error": {"Code": "ParameterNotFound","Message": "The parameter was not found"}}, {...})

相关问题 更多 >