Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_should_retry():
err_good = ClientError({
'Error': {
'Code': 'ProvisionedThroughputExceededException',
'Message': 'oops'
}
}, 'testing')
err_bad = ClientError({
'Error': {
'Code': 'Bangarang!',
'Message': 'oops'
}
}, 'testing')
assert should_retry(err_good) is True
assert should_retry(err_bad) is False
assert should_retry(AssertionError("foo")) is False
def test_get_s2_info_botoError(get_object):
"""Should work as expected
"""
get_object.side_effect = ClientError(
{'Error': {'Code': 500, 'Message': 'Error'}}, 'get_object')
bucket = 'sentinel-s2-l1c'
scene_path = 'tiles/38/S/NG/2017/10/9/1/'
full = True
s3 = None
request_pays = False
expected = {
'acquisition_date': '20171009',
'browseURL': 'https://roda.sentinel-hub.com/sentinel-s2-l1c/tiles/38/S/NG/2017/10/9/1/preview.jpg',
'grid_square': 'NG',
'latitude_band': 'S',
'num': '1',
'path': 'tiles/38/S/NG/2017/10/9/1/',
'sat': 'S2A',
def test_absent_with_failure(self):
self.conn.describe_elasticsearch_domain.return_value = {'DomainStatus': domain_ret}
self.conn.describe_elasticsearch_domain_config.return_value = {'DomainConfig': domain_ret}
self.conn.delete_elasticsearch_domain.side_effect = ClientError(error_content, 'delete_domain')
result = self.salt_states['boto_elasticsearch_domain.absent']('test', domain_ret['DomainName'])
self.assertFalse(result['result'])
self.assertTrue('An error occurred' in result['comment'])
def test_deploy_flow_register_task_definition(monkeypatch, runner_token):
boto3_client = MagicMock()
boto3_client.describe_task_definition.side_effect = ClientError({}, None)
boto3_client.run_task.return_value = {"tasks": [{"taskArn": "test"}]}
boto3_client.register_task_definition.return_value = {}
monkeypatch.setattr("boto3.client", MagicMock(return_value=boto3_client))
agent = FargateAgent()
agent.deploy_flow(
flow_run=GraphQLResult(
{
"flow": GraphQLResult(
{
"storage": Docker(
registry_url="test", image_name="name", image_tag="tag"
).serialize(),
"id": "id",
}
def test_that_when_deleting_api_resources_and_delete_resource_throws_error_the_delete_api_resources_method_returns_false(self):
'''
Tests False delete_resource side side_effect
'''
self.conn.get_resources.return_value = api_resources_ret
self.conn.delete_resource.side_effect = ClientError(error_content, 'delete_resource')
result = boto_apigateway.delete_api_resources(restApiId='rm06h9oac4', path='/api', **conn_parameters)
self.assertFalse(result.get('deleted'))
def test_upload_to_s3_with_multipart_upload_aborted_on_error(self):
self.args.bucket = self.bucket
self.args.key = self.key
self.bundle_mock.tell.return_value = (6 << 20)
self.bundle_mock.read.return_value = b'a' * (6 << 20)
self.push.s3.upload_part.side_effect = ClientError(
{'Error': {'Code': 'Error', 'Message': 'Error'}},
'UploadPart'
)
with self.assertRaises(ClientError):
self.push._upload_to_s3(self.args, self.bundle_mock)
self.assertFalse(self.push.s3.put_object.called)
self.push.s3.create_multipart_upload.assert_called_with(
Bucket=self.bucket,
Key=self.key
)
self.assertTrue(self.push.s3.upload_part.called)
self.assertFalse(self.push.s3.complete_multipart_upload.called)
self.push.s3.abort_multipart_upload.assert_called_with(
Bucket=self.bucket,
Key=self.key,
UploadId=self.upload_id
def properties(self):
"""Gets the properties of an external resource"""
params = self.describe_image_filters
try:
resources = \
self.client.describe_images(**params)
except ClientError:
pass
else:
images = [] if not resources else resources.get(IMAGES)
if len(images):
return images[0]
raise NonRecoverableError(
"Found no AMIs matching provided filters.")
stacks = ("glue-resources", "gluerunner-lambda", "step-functions-resources")
for stack in stacks:
stack_name = stack
cfn_client = boto3.client('cloudformation')
try:
response = cfn_client.describe_stacks(
StackName=stack_name
)
if response["Stacks"][0]:
print("Stack '%s' has the status '%s'" % (stack_name, response["Stacks"][0]["StackStatus"]))
except ClientError as e:
print("EXCEPTION: " + e.response["Error"]["Message"])
assessmentTargetArn=existing_target_arn,
assessmentTargetName=name,
resourceGroupArn=updated_resource_group_arn,
)
updated_target = camel_dict_to_snake_dict(
client.describe_assessment_targets(
assessmentTargetArns=[existing_target_arn],
).get('assessmentTargets')[0]
)
updated_target.update({'tags': ansible_dict_tags})
module.exit_json(changed=True, **updated_target),
except (
botocore.exceptions.BotoCoreError,
botocore.exceptions.ClientError,
) as e:
module.fail_json_aws(e, msg="trying to update target")
elif state == 'present' and not target_exists:
try:
new_resource_group_arn = client.create_resource_group(
resourceGroupTags=tags,
).get('resourceGroupArn')
new_target_arn = client.create_assessment_target(
assessmentTargetName=name,
resourceGroupArn=new_resource_group_arn,
).get('assessmentTargetArn')
new_target = camel_dict_to_snake_dict(
client.describe_assessment_targets(
matching = [x for x in tagged if key_match in str(x['Tags'][0])]
b3 = create_boto3_session()
for instance in matching:
i = instance['InstanceId']
if instance['State']['Name'] in ['running', 'pending', 'stopping',
'stopped']:
log.info("Handling Instance %s", i)
try:
ec2 = b3.client(
'ec2', instance['Placement']['AvailabilityZone'][:-1])
log.info("Removing Termination Protection on %s", i)
ec2.modify_instance_attribute(
InstanceId=i,
DisableApiTermination={'Value': False}
)
except ClientError as e:
raise e
if also_terminate:
try:
log.info("Attempting termination of %s", i)
ec2.terminate_instances(InstanceIds=[i])
except ClientError as e:
log.info("Couldn't terminate %s", i)
else:
log.info("Instance %s already killed", i)