我需要帮助在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而不失败或管理控制异常?
发布于 2021-11-10 19:48:48
它需要在模拟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 == Nonehttps://stackoverflow.com/questions/69882618
复制相似问题