Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def assert_no_param_error_raised(self, client):
try:
self.make_api_call_with_missing_param(client)
except ParamValidationError:
self.fail("ParamValidationError shouldn't be raised "
"with validation disabled")
def test_gsi_unsupported_names(dynamodb):
# Unfortunately, the boto library tests for names shorter than the
# minimum length (3 characters) immediately, and failure results in
# ParamValidationError. But the other invalid names are passed to
# DynamoDB, which returns an HTTP response code, which results in a
# CientError exception.
with pytest.raises(ParamValidationError):
create_gsi(dynamodb, 'n')
with pytest.raises(ParamValidationError):
create_gsi(dynamodb, 'nn')
with pytest.raises(ClientError, match='ValidationException.*nnnnn'):
create_gsi(dynamodb, 'n' * 256)
with pytest.raises(ClientError, match='ValidationException.*nyh'):
create_gsi(dynamodb, 'nyh@test')
err = {'Error': {'Code': 400, 'Message': 'raising test exception'}}
raise ClientError(err, 'invoke')
req_keywords = {'FunctionName', 'InvocationType', 'Payload'}
key_diff = req_keywords.difference(set(kwargs))
if key_diff:
message = 'required keyword missing: {}'.format(', '.join(key_diff))
err = {'Error': {'Code': 400, 'Message': message}}
raise ClientError(err, 'invoke')
if not isinstance(kwargs['Payload'], (str, bytearray)):
if not hasattr(kwargs['Payload'], 'read'):
err = ('Invalid type for parameter Payload, value: {}, type: {}, '
'valid types: , , '
'file-like object').format(kwargs['Payload'], type(kwargs['Payload']))
raise ParamValidationError(response=err)
return {'ResponseMetadata': {'RequestId': '9af88643-7b3c-43cd-baae-addb73bb4d27'}}
def _validate_keys(dynamodb_data):
"""Helper method to check if query key empty or duplicated"""
result = []
if not dynamodb_data:
err_msg = {'Error': {'Code': 403, 'Message': 'Empty query keys'}}
raise ParamValidationError(report=err_msg)
deserializer = TypeDeserializer()
for raw_data in dynamodb_data:
for _, val in raw_data.iteritems():
python_data = deserializer.deserialize(val).lower()
if not python_data or python_data in result:
err_msg = {'Error': {'Code': 403, 'Message': 'Parameter Validation Error'}}
raise ParamValidationError(report=err_msg)
result.append(python_data)
with pytest.raises(ParamValidationError):
# wrong type
connector_args = dict(use_dns_cache=1)
AioConfig(connector_args)
with pytest.raises(ParamValidationError):
# wrong type
connector_args = dict(keepalive_timeout="1")
AioConfig(connector_args)
with pytest.raises(ParamValidationError):
# wrong type
connector_args = dict(force_close="1")
AioConfig(connector_args)
with pytest.raises(ParamValidationError):
# wrong type
connector_args = dict(ssl_context="1")
AioConfig(connector_args)
with pytest.raises(ParamValidationError):
# invalid key
connector_args = dict(foo="1")
AioConfig(connector_args)
# test merge
cfg = Config(read_timeout=75)
aio_cfg = AioConfig({'keepalive_timeout': 75})
aio_cfg.merge(cfg)
assert cfg.read_timeout == 75
assert aio_cfg.connector_args['keepalive_timeout'] == 75
def _validate_param(params, name, type=None):
"""Check that the param *name* is found in *params*, and if
*type* is set, validate that it has the proper type.
*type* may also be a tuple (multiple types) or a list
(multiple values to match)
"""
if name not in params:
raise ParamValidationError(
report='Missing required parameter in input: "%s"' % name)
if type:
if isinstance(type, list):
_validate_param_enum(params[name], type)
else:
_validate_param_type(params[name], type)
client_secret = os.environ["COGNITO_USER_POOL_CLIENT_SECRET"]
try:
cognito_client.sign_up(
ClientId = client_id,
SecretHash = generate_cognito_sign_up_secret_hash(new_username, client_id, client_secret),
Username = new_username,
Password = new_password,
UserAttributes = [
{
"Name": "email",
"Value": email_address
}
]
)
except botocore.exceptions.ParamValidationError as e:
raise APIGatewayException("Password does not meet complexity requirements.", 400)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidPasswordException':
raise APIGatewayException("Password does not meet complexity requirements.", 400)
elif e.response['Error']['Code'] == 'CodeDeliveryFailureException':
raise APIGatewayException("Unable to deliver code to the e-mail address specified.", 400)
return {
"registration-id": new_username,
"email-address": email_address
}
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except (botocore.exceptions.ClientError,
botocore.exceptions.WaiterError,
botocore.exceptions.ParamValidationError,
ConfigError) as e:
click.secho(str(e), fg='red')
except KeyboardInterrupt as e:
click.secho('Aborted.', fg='red')
def _validate_fixed_response_action(self, action, i, index):
status_code = action.data.get("fixed_response_config._status_code")
if status_code is None:
raise ParamValidationError(
report='Missing required parameter in Actions[%s].FixedResponseConfig: "StatusCode"'
% i
)
if not re.match(r"^(2|4|5)\d\d$", status_code):
raise InvalidStatusCodeActionTypeError(
"1 validation error detected: Value '%s' at 'actions.%s.member.fixedResponseConfig.statusCode' failed to satisfy constraint: \
Member must satisfy regular expression pattern: ^(2|4|5)\d\d$"
% (status_code, index)
)
content_type = action.data["fixed_response_config._content_type"]
if content_type and content_type not in [
"text/plain",
"text/css",
"text/html",
"application/javascript",
"application/json",
def update_tags(module, connection, group, tags):
changed = False
existing_tags = connection.list_tags_for_resource(ResourceName=group['DBParameterGroupArn'])['TagList']
to_update, to_delete = compare_aws_tags(boto3_tag_list_to_ansible_dict(existing_tags),
tags, module.params['purge_tags'])
if to_update:
try:
connection.add_tags_to_resource(ResourceName=group['DBParameterGroupArn'],
Tags=ansible_dict_to_boto3_tag_list(to_update))
changed = True
except botocore.exceptions.ClientError as e:
module.fail_json(msg="Couldn't add tags to parameter group: %s" % str(e),
exception=traceback.format_exc(),
**camel_dict_to_snake_dict(e.response))
except botocore.exceptions.ParamValidationError as e:
# Usually a tag value has been passed as an int or bool, needs to be a string
# The AWS exception message is reasonably ok for this purpose
module.fail_json(msg="Couldn't add tags to parameter group: %s." % str(e),
exception=traceback.format_exc())
if to_delete:
try:
connection.remove_tags_from_resource(ResourceName=group['DBParameterGroupArn'],
TagKeys=to_delete)
changed = True
except botocore.exceptions.ClientError as e:
module.fail_json(msg="Couldn't remove tags from parameter group: %s" % str(e),
exception=traceback.format_exc(),
**camel_dict_to_snake_dict(e.response))
return changed