我创建了一个删除Amazon Machine映像的函数,如下所示:
def deleteImage(self, resourceInterface: boto3.resource, imageId: str):
if (not(type(imageId) == str)):
raise TypeError
response = {
'imageID': imageId,
'returnCode': bool,
'errorMessage': []
}
try:
apiResponse = resourceInterface.Image(
imageId).deregister(DryRun=self.dryRunEnabled)
if (apiResponse['ResponseMetadata']['HTTPStatusCode'] == 200):
response['returnCode'] = 0
else:
response['returnCode'] = 1
response['errorMessage'] = apiResponse['ResponseMetadata']
except Exception as err:
response['returnCode'] = 1
response['errorMessage'] = err.args
return response
我的单元测试在这里:
def test_deleteImage(self):
imageId = 'ami-00992a771010f4653'
imageLifecycle = Lifecycle(self.lifeCycleRules, self.dryRunEnabled)
boto3 = MagicMock()
ec2Resource = boto3.resource('ec2')
ec2Resource.return_value = {
'ResponseMetadata': {'HTTPHeaders': {'content-length': '231',
'content-type': 'text/xml;charset=UTF-8',
'date': 'Tue, 19 Nov 2019 21:42:55 GMT',
'server': 'AmazonEC2'},
'HTTPStatusCode': 200,
'RequestId': 'f6fb8bcc-68b0-4683-9cb7-75e9bf6ac669',
'RetryAttempts': 0}
}
response = imageLifecycle.deleteImage(
ec2Resource, imageId)
self.assertEqual(response['returnCode'], 0)
这里发生的是将MagicMock对象分配给变量apiResponse
,但是我想要的是分配return_value
。
如何模拟boto3
命令并将我想要的值返回给apiResponse
?
apiResponse = resourceInterface.Image(imageId).deregister(DryRun=self.dryRunEnabled)