【问题标题】:mock describe_subnets function boto3模拟 describe_subnets 函数 boto3
【发布时间】:2021-12-21 05:49:20
【问题描述】:

我需要帮助来模拟 boto3 describe_subnets 函数上的测试函数。

def check_belongsto_describe(list_subnet):
    ec2 = boto3.resource('ec2',region_name='us-east-1')
    ec2_client = ec2.meta.client
    response = ec2_client.describe_subnets(SubnetIds=list_subnet)
    return None

但是当它在 pytest 上运行时:

猴子补丁

def test_check_belongsto_az_monkeypatch(monkeypatch):
    def client_mock(service="ec2", region_name='us-east-1',    
        aws_access_key_id="testing",
        aws_secret_access_key="testing",
        aws_session_token="testing"):
        return MockClientBoto3()

    monkeypatch.setattr(boto3, "client", client_mock)
    list_subnet = ['testid1','testid2']
    az = 'us-east-1'
    response = fw_init.check_belongsto_describe(list_subnet)
    assert response == None

mock_ec2

@mock_ec2
def test_check_belongsto_az_mock():
    ec2 = boto3.resource('ec2',region_name='us-east-1',
    aws_access_key_id="testing",
    aws_secret_access_key="testing", 
    aws_session_token="testing")
    ec2_client = ec2.meta.client
    list_subnet = ['test1','test2']
    az = 'us-east-1'
    response = fw_init.check_belongsto_describe(list_subnet)
    assert response == None

我收到了这个错误:

botocore.exceptions.ClientError: An error occurred (AuthFailure) when calling the DescribeSubnets operation: AWS was not able to validate the provided access credentials

如何模拟、存根、测试或传递此函数才能验证 Auth 而不会失败或管理控制异常?

【问题讨论】:

  • 你能展示你正在模拟的功能吗?你为monkeypatch定义了一个函数,但是你在哪里使用它呢?
  • 问题需要明确,并且提供的代码至少应该在最小的尝试中是可重现的。提供的信息含糊不清。
  • 嗨@jordanm & Roxy,只需更新代码,感谢您的反馈。

标签: aws-lambda mocking pytest boto3 botocore


【解决方案1】:

它需要在模拟 describe_subnets 函数之前创建 VPC 和子网。

@mock_ec2
def test_subnets_boto3():
    ec2 = boto3.resource("ec2", region_name="us-east-1")
    vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
    subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock="10.0.0.0/18")
    list_subnet = [subnet.id]
    az = 'us-east-1'
    response = fw_init.check_belongsto_describe(list_subnet)
    assert response == None

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多