Pylint - run on source directories (abc only for now) (#4647)

This commit is contained in:
Bert Blommers 2021-12-01 22:06:58 -01:00 committed by GitHub
parent 29406ed74e
commit c6815c1a4b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 228 additions and 284 deletions

View File

@ -18,7 +18,7 @@ init:
lint: lint:
flake8 moto flake8 moto
black --check moto/ tests/ black --check moto/ tests/
pylint -j 0 tests pylint -j 0 moto/a* moto/b* moto/c* tests
format: format:
black moto/ tests/ black moto/ tests/

View File

@ -405,7 +405,7 @@ class CertBundle(BaseModel):
class AWSCertificateManagerBackend(BaseBackend): class AWSCertificateManagerBackend(BaseBackend):
def __init__(self, region): def __init__(self, region):
super(AWSCertificateManagerBackend, self).__init__() super().__init__()
self.region = region self.region = region
self._certificates = {} self._certificates = {}
self._idempotency_tokens = {} self._idempotency_tokens = {}

View File

@ -19,7 +19,7 @@ class ConflictException(JsonRESTError):
class AwsProxyNotAllowed(BadRequestException): class AwsProxyNotAllowed(BadRequestException):
def __init__(self): def __init__(self):
super(AwsProxyNotAllowed, self).__init__( super().__init__(
"BadRequestException", "BadRequestException",
"Integrations of type 'AWS_PROXY' currently only supports Lambda function and Firehose stream invocations.", "Integrations of type 'AWS_PROXY' currently only supports Lambda function and Firehose stream invocations.",
) )
@ -27,28 +27,28 @@ class AwsProxyNotAllowed(BadRequestException):
class CrossAccountNotAllowed(AccessDeniedException): class CrossAccountNotAllowed(AccessDeniedException):
def __init__(self): def __init__(self):
super(CrossAccountNotAllowed, self).__init__( super().__init__(
"AccessDeniedException", "Cross-account pass role is not allowed." "AccessDeniedException", "Cross-account pass role is not allowed."
) )
class RoleNotSpecified(BadRequestException): class RoleNotSpecified(BadRequestException):
def __init__(self): def __init__(self):
super(RoleNotSpecified, self).__init__( super().__init__(
"BadRequestException", "Role ARN must be specified for AWS integrations" "BadRequestException", "Role ARN must be specified for AWS integrations"
) )
class IntegrationMethodNotDefined(BadRequestException): class IntegrationMethodNotDefined(BadRequestException):
def __init__(self): def __init__(self):
super(IntegrationMethodNotDefined, self).__init__( super().__init__(
"BadRequestException", "Enumeration value for HttpMethod must be non-empty" "BadRequestException", "Enumeration value for HttpMethod must be non-empty"
) )
class InvalidResourcePathException(BadRequestException): class InvalidResourcePathException(BadRequestException):
def __init__(self): def __init__(self):
super(InvalidResourcePathException, self).__init__( super().__init__(
"BadRequestException", "BadRequestException",
"Resource's path part only allow a-zA-Z0-9._- and curly braces at the beginning and the end and an optional plus sign before the closing brace.", "Resource's path part only allow a-zA-Z0-9._- and curly braces at the beginning and the end and an optional plus sign before the closing brace.",
) )
@ -56,51 +56,43 @@ class InvalidResourcePathException(BadRequestException):
class InvalidHttpEndpoint(BadRequestException): class InvalidHttpEndpoint(BadRequestException):
def __init__(self): def __init__(self):
super(InvalidHttpEndpoint, self).__init__( super().__init__(
"BadRequestException", "Invalid HTTP endpoint specified for URI" "BadRequestException", "Invalid HTTP endpoint specified for URI"
) )
class InvalidArn(BadRequestException): class InvalidArn(BadRequestException):
def __init__(self): def __init__(self):
super(InvalidArn, self).__init__( super().__init__("BadRequestException", "Invalid ARN specified in the request")
"BadRequestException", "Invalid ARN specified in the request"
)
class InvalidIntegrationArn(BadRequestException): class InvalidIntegrationArn(BadRequestException):
def __init__(self): def __init__(self):
super(InvalidIntegrationArn, self).__init__( super().__init__(
"BadRequestException", "AWS ARN for integration must contain path or action" "BadRequestException", "AWS ARN for integration must contain path or action"
) )
class InvalidRequestInput(BadRequestException): class InvalidRequestInput(BadRequestException):
def __init__(self): def __init__(self):
super(InvalidRequestInput, self).__init__( super().__init__("BadRequestException", "Invalid request input")
"BadRequestException", "Invalid request input"
)
class NoIntegrationDefined(NotFoundException): class NoIntegrationDefined(NotFoundException):
def __init__(self): def __init__(self):
super(NoIntegrationDefined, self).__init__( super().__init__("NotFoundException", "No integration defined for method")
"NotFoundException", "No integration defined for method"
)
class NoIntegrationResponseDefined(NotFoundException): class NoIntegrationResponseDefined(NotFoundException):
code = 404 code = 404
def __init__(self, code=None): def __init__(self, code=None):
super(NoIntegrationResponseDefined, self).__init__( super().__init__("NotFoundException", "Invalid Response status code specified")
"NotFoundException", "Invalid Response status code specified"
)
class NoMethodDefined(BadRequestException): class NoMethodDefined(BadRequestException):
def __init__(self): def __init__(self):
super(NoMethodDefined, self).__init__( super().__init__(
"BadRequestException", "The REST API doesn't contain any methods" "BadRequestException", "The REST API doesn't contain any methods"
) )
@ -109,61 +101,49 @@ class AuthorizerNotFoundException(NotFoundException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(AuthorizerNotFoundException, self).__init__( super().__init__("NotFoundException", "Invalid Authorizer identifier specified")
"NotFoundException", "Invalid Authorizer identifier specified"
)
class StageNotFoundException(NotFoundException): class StageNotFoundException(NotFoundException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(StageNotFoundException, self).__init__( super().__init__("NotFoundException", "Invalid stage identifier specified")
"NotFoundException", "Invalid stage identifier specified"
)
class ApiKeyNotFoundException(NotFoundException): class ApiKeyNotFoundException(NotFoundException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(ApiKeyNotFoundException, self).__init__( super().__init__("NotFoundException", "Invalid API Key identifier specified")
"NotFoundException", "Invalid API Key identifier specified"
)
class UsagePlanNotFoundException(NotFoundException): class UsagePlanNotFoundException(NotFoundException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(UsagePlanNotFoundException, self).__init__( super().__init__("NotFoundException", "Invalid Usage Plan ID specified")
"NotFoundException", "Invalid Usage Plan ID specified"
)
class ApiKeyAlreadyExists(JsonRESTError): class ApiKeyAlreadyExists(JsonRESTError):
code = 409 code = 409
def __init__(self): def __init__(self):
super(ApiKeyAlreadyExists, self).__init__( super().__init__("ConflictException", "API Key already exists")
"ConflictException", "API Key already exists"
)
class InvalidDomainName(BadRequestException): class InvalidDomainName(BadRequestException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(InvalidDomainName, self).__init__( super().__init__("BadRequestException", "No Domain Name specified")
"BadRequestException", "No Domain Name specified"
)
class DomainNameNotFound(NotFoundException): class DomainNameNotFound(NotFoundException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(DomainNameNotFound, self).__init__( super().__init__(
"NotFoundException", "Invalid domain name identifier specified" "NotFoundException", "Invalid domain name identifier specified"
) )
@ -172,52 +152,42 @@ class InvalidRestApiId(BadRequestException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(InvalidRestApiId, self).__init__( super().__init__("BadRequestException", "No Rest API Id specified")
"BadRequestException", "No Rest API Id specified"
)
class InvalidModelName(BadRequestException): class InvalidModelName(BadRequestException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(InvalidModelName, self).__init__( super().__init__("BadRequestException", "No Model Name specified")
"BadRequestException", "No Model Name specified"
)
class RestAPINotFound(NotFoundException): class RestAPINotFound(NotFoundException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(RestAPINotFound, self).__init__( super().__init__("NotFoundException", "Invalid Rest API Id specified")
"NotFoundException", "Invalid Rest API Id specified"
)
class RequestValidatorNotFound(BadRequestException): class RequestValidatorNotFound(BadRequestException):
code = 400 code = 400
def __init__(self): def __init__(self):
super(RequestValidatorNotFound, self).__init__( super().__init__("NotFoundException", "Invalid Request Validator Id specified")
"NotFoundException", "Invalid Request Validator Id specified"
)
class ModelNotFound(NotFoundException): class ModelNotFound(NotFoundException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(ModelNotFound, self).__init__( super().__init__("NotFoundException", "Invalid Model Name specified")
"NotFoundException", "Invalid Model Name specified"
)
class ApiKeyValueMinLength(BadRequestException): class ApiKeyValueMinLength(BadRequestException):
code = 400 code = 400
def __init__(self): def __init__(self):
super(ApiKeyValueMinLength, self).__init__( super().__init__(
"BadRequestException", "API Key value should be at least 20 characters" "BadRequestException", "API Key value should be at least 20 characters"
) )
@ -226,16 +196,14 @@ class MethodNotFoundException(NotFoundException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(MethodNotFoundException, self).__init__( super().__init__("NotFoundException", "Invalid Method identifier specified")
"NotFoundException", "Invalid Method identifier specified"
)
class InvalidBasePathException(BadRequestException): class InvalidBasePathException(BadRequestException):
code = 400 code = 400
def __init__(self): def __init__(self):
super(InvalidBasePathException, self).__init__( super().__init__(
"BadRequestException", "BadRequestException",
"API Gateway V1 doesn't support the slash character (/) in base path mappings. " "API Gateway V1 doesn't support the slash character (/) in base path mappings. "
"To create a multi-level base path mapping, use API Gateway V2.", "To create a multi-level base path mapping, use API Gateway V2.",
@ -246,23 +214,19 @@ class InvalidRestApiIdForBasePathMappingException(BadRequestException):
code = 400 code = 400
def __init__(self): def __init__(self):
super(InvalidRestApiIdForBasePathMappingException, self).__init__( super().__init__("BadRequestException", "Invalid REST API identifier specified")
"BadRequestException", "Invalid REST API identifier specified"
)
class InvalidStageException(BadRequestException): class InvalidStageException(BadRequestException):
code = 400 code = 400
def __init__(self): def __init__(self):
super(InvalidStageException, self).__init__( super().__init__("BadRequestException", "Invalid stage identifier specified")
"BadRequestException", "Invalid stage identifier specified"
)
class BasePathConflictException(ConflictException): class BasePathConflictException(ConflictException):
def __init__(self): def __init__(self):
super(BasePathConflictException, self).__init__( super().__init__(
"ConflictException", "Base path already exists for this domain name" "ConflictException", "Base path already exists for this domain name"
) )
@ -271,6 +235,6 @@ class BasePathNotFoundException(NotFoundException):
code = 404 code = 404
def __init__(self): def __init__(self):
super(BasePathNotFoundException, self).__init__( super().__init__(
"NotFoundException", "Invalid base path mapping identifier specified" "NotFoundException", "Invalid base path mapping identifier specified"
) )

View File

@ -60,7 +60,7 @@ STAGE_URL = "https://{api_id}.execute-api.{region_name}.amazonaws.com/{stage_nam
class Deployment(CloudFormationModel, dict): class Deployment(CloudFormationModel, dict):
def __init__(self, deployment_id, name, description=""): def __init__(self, deployment_id, name, description=""):
super(Deployment, self).__init__() super().__init__()
self["id"] = deployment_id self["id"] = deployment_id
self["stageName"] = name self["stageName"] = name
self["description"] = description self["description"] = description
@ -121,7 +121,7 @@ class Integration(BaseModel, dict):
tls_config=None, tls_config=None,
cache_namespace=None, cache_namespace=None,
): ):
super(Integration, self).__init__() super().__init__()
self["type"] = integration_type self["type"] = integration_type
self["uri"] = uri self["uri"] = uri
self["httpMethod"] = http_method self["httpMethod"] = http_method
@ -158,7 +158,7 @@ class Integration(BaseModel, dict):
class MethodResponse(BaseModel, dict): class MethodResponse(BaseModel, dict):
def __init__(self, status_code, response_models=None, response_parameters=None): def __init__(self, status_code, response_models=None, response_parameters=None):
super(MethodResponse, self).__init__() super().__init__()
self["statusCode"] = status_code self["statusCode"] = status_code
self["responseModels"] = response_models self["responseModels"] = response_models
self["responseParameters"] = response_parameters self["responseParameters"] = response_parameters
@ -166,7 +166,7 @@ class MethodResponse(BaseModel, dict):
class Method(CloudFormationModel, dict): class Method(CloudFormationModel, dict):
def __init__(self, method_type, authorization_type, **kwargs): def __init__(self, method_type, authorization_type, **kwargs):
super(Method, self).__init__() super().__init__()
self.update( self.update(
dict( dict(
httpMethod=method_type, httpMethod=method_type,
@ -237,9 +237,9 @@ class Method(CloudFormationModel, dict):
class Resource(CloudFormationModel): class Resource(CloudFormationModel):
def __init__(self, id, region_name, api_id, path_part, parent_id): def __init__(self, resource_id, region_name, api_id, path_part, parent_id):
super(Resource, self).__init__() super().__init__()
self.id = id self.id = resource_id
self.region_name = region_name self.region_name = region_name
self.api_id = api_id self.api_id = api_id
self.path_part = path_part self.path_part = path_part
@ -383,9 +383,9 @@ class Resource(CloudFormationModel):
class Authorizer(BaseModel, dict): class Authorizer(BaseModel, dict):
def __init__(self, id, name, authorizer_type, **kwargs): def __init__(self, authorizer_id, name, authorizer_type, **kwargs):
super(Authorizer, self).__init__() super().__init__()
self["id"] = id self["id"] = authorizer_id
self["name"] = name self["name"] = name
self["type"] = authorizer_type self["type"] = authorizer_type
if kwargs.get("provider_arns"): if kwargs.get("provider_arns"):
@ -442,7 +442,7 @@ class Stage(BaseModel, dict):
tags=None, tags=None,
tracing_enabled=None, tracing_enabled=None,
): ):
super(Stage, self).__init__() super().__init__()
if variables is None: if variables is None:
variables = {} variables = {}
self["stageName"] = name self["stageName"] = name
@ -579,11 +579,11 @@ class ApiKey(BaseModel, dict):
enabled=False, enabled=False,
generateDistinctId=False, generateDistinctId=False,
value=None, value=None,
stageKeys=[], stageKeys=None,
tags=None, tags=None,
customerId=None, customerId=None,
): ):
super(ApiKey, self).__init__() super().__init__()
self["id"] = create_id() self["id"] = create_id()
self["value"] = ( self["value"] = (
value value
@ -595,7 +595,7 @@ class ApiKey(BaseModel, dict):
self["description"] = description self["description"] = description
self["enabled"] = enabled self["enabled"] = enabled
self["createdDate"] = self["lastUpdatedDate"] = int(time.time()) self["createdDate"] = self["lastUpdatedDate"] = int(time.time())
self["stageKeys"] = stageKeys self["stageKeys"] = stageKeys or []
self["tags"] = tags self["tags"] = tags
def update_operations(self, patch_operations): def update_operations(self, patch_operations):
@ -628,7 +628,7 @@ class UsagePlan(BaseModel, dict):
productCode=None, productCode=None,
tags=None, tags=None,
): ):
super(UsagePlan, self).__init__() super().__init__()
self["id"] = create_id() self["id"] = create_id()
self["name"] = name self["name"] = name
self["description"] = description self["description"] = description
@ -671,9 +671,9 @@ class RequestValidator(BaseModel, dict):
OP_REPLACE = "replace" OP_REPLACE = "replace"
OP_OP = "op" OP_OP = "op"
def __init__(self, id, name, validateRequestBody, validateRequestParameters): def __init__(self, _id, name, validateRequestBody, validateRequestParameters):
super(RequestValidator, self).__init__() super().__init__()
self[RequestValidator.PROP_ID] = id self[RequestValidator.PROP_ID] = _id
self[RequestValidator.PROP_NAME] = name self[RequestValidator.PROP_NAME] = name
self[RequestValidator.PROP_VALIDATE_REQUEST_BODY] = validateRequestBody self[RequestValidator.PROP_VALIDATE_REQUEST_BODY] = validateRequestBody
self[ self[
@ -706,11 +706,11 @@ class RequestValidator(BaseModel, dict):
class UsagePlanKey(BaseModel, dict): class UsagePlanKey(BaseModel, dict):
def __init__(self, id, type, name, value): def __init__(self, plan_id, plan_type, name, value):
super(UsagePlanKey, self).__init__() super().__init__()
self["id"] = id self["id"] = plan_id
self["name"] = name self["name"] = name
self["type"] = type self["type"] = plan_type
self["value"] = value self["value"] = value
@ -737,9 +737,9 @@ class RestAPI(CloudFormationModel):
OPERATION_VALUE = "value" OPERATION_VALUE = "value"
OPERATION_OP = "op" OPERATION_OP = "op"
def __init__(self, id, region_name, name, description, **kwargs): def __init__(self, api_id, region_name, name, description, **kwargs):
super(RestAPI, self).__init__() super().__init__()
self.id = id self.id = api_id
self.region_name = region_name self.region_name = region_name
self.name = name self.name = name
self.description = description self.description = description
@ -855,7 +855,7 @@ class RestAPI(CloudFormationModel):
def add_child(self, path, parent_id=None): def add_child(self, path, parent_id=None):
child_id = create_id() child_id = create_id()
child = Resource( child = Resource(
id=child_id, resource_id=child_id,
region_name=self.region_name, region_name=self.region_name,
api_id=self.id, api_id=self.id,
path_part=path, path_part=path,
@ -875,7 +875,7 @@ class RestAPI(CloudFormationModel):
): ):
model_id = create_id() model_id = create_id()
new_model = Model( new_model = Model(
id=model_id, model_id=model_id,
name=name, name=name,
description=description, description=description,
schema=schema, schema=schema,
@ -909,11 +909,11 @@ class RestAPI(CloudFormationModel):
api_id=self.id.upper(), region_name=self.region_name, stage_name=stage_name api_id=self.id.upper(), region_name=self.region_name, stage_name=stage_name
) )
for resource_id, resource in self.resources.items(): for resource in self.resources.values():
path = resource.get_path() path = resource.get_path()
path = "" if path == "/" else path path = "" if path == "/" else path
for http_method, method in resource.resource_methods.items(): for http_method in resource.resource_methods.keys():
for url in [stage_url_lower, stage_url_upper]: for url in [stage_url_lower, stage_url_upper]:
callback_response = responses.CallbackResponse( callback_response = responses.CallbackResponse(
url=url + path, url=url + path,
@ -926,7 +926,7 @@ class RestAPI(CloudFormationModel):
def create_authorizer( def create_authorizer(
self, self,
id, authorizer_id,
name, name,
authorizer_type, authorizer_type,
provider_arns=None, provider_arns=None,
@ -938,7 +938,7 @@ class RestAPI(CloudFormationModel):
authorizer_result_ttl=None, authorizer_result_ttl=None,
): ):
authorizer = Authorizer( authorizer = Authorizer(
id=id, authorizer_id=authorizer_id,
name=name, name=name,
authorizer_type=authorizer_type, authorizer_type=authorizer_type,
provider_arns=provider_arns, provider_arns=provider_arns,
@ -949,7 +949,7 @@ class RestAPI(CloudFormationModel):
identiy_validation_expression=identiy_validation_expression, identiy_validation_expression=identiy_validation_expression,
authorizer_result_ttl=authorizer_result_ttl, authorizer_result_ttl=authorizer_result_ttl,
) )
self.authorizers[id] = authorizer self.authorizers[authorizer_id] = authorizer
return authorizer return authorizer
def create_stage( def create_stage(
@ -1012,7 +1012,7 @@ class RestAPI(CloudFormationModel):
): ):
validator_id = create_id() validator_id = create_id()
request_validator = RequestValidator( request_validator = RequestValidator(
id=validator_id, _id=validator_id,
name=name, name=name,
validateRequestBody=validateRequestBody, validateRequestBody=validateRequestBody,
validateRequestParameters=validateRequestParameters, validateRequestParameters=validateRequestParameters,
@ -1040,7 +1040,7 @@ class RestAPI(CloudFormationModel):
class DomainName(BaseModel, dict): class DomainName(BaseModel, dict):
def __init__(self, domain_name, **kwargs): def __init__(self, domain_name, **kwargs):
super(DomainName, self).__init__() super().__init__()
self["domainName"] = domain_name self["domainName"] = domain_name
self["regionalDomainName"] = "d-%s.execute-api.%s.amazonaws.com" % ( self["regionalDomainName"] = "d-%s.execute-api.%s.amazonaws.com" % (
create_id(), create_id(),
@ -1077,9 +1077,9 @@ class DomainName(BaseModel, dict):
class Model(BaseModel, dict): class Model(BaseModel, dict):
def __init__(self, id, name, **kwargs): def __init__(self, model_id, name, **kwargs):
super(Model, self).__init__() super().__init__()
self["id"] = id self["id"] = model_id
self["name"] = name self["name"] = name
if kwargs.get("description"): if kwargs.get("description"):
self["description"] = kwargs.get("description") self["description"] = kwargs.get("description")
@ -1095,7 +1095,7 @@ class Model(BaseModel, dict):
class BasePathMapping(BaseModel, dict): class BasePathMapping(BaseModel, dict):
def __init__(self, domain_name, rest_api_id, **kwargs): def __init__(self, domain_name, rest_api_id, **kwargs):
super(BasePathMapping, self).__init__() super().__init__()
self["domain_name"] = domain_name self["domain_name"] = domain_name
self["restApiId"] = rest_api_id self["restApiId"] = rest_api_id
if kwargs.get("basePath"): if kwargs.get("basePath"):
@ -1135,7 +1135,7 @@ class APIGatewayBackend(BaseBackend):
""" """
def __init__(self, region_name): def __init__(self, region_name):
super(APIGatewayBackend, self).__init__() super().__init__()
self.apis = {} self.apis = {}
self.keys = {} self.keys = {}
self.usage_plans = {} self.usage_plans = {}
@ -1591,8 +1591,8 @@ class APIGatewayBackend(BaseBackend):
api_key = self.keys[key_id] api_key = self.keys[key_id]
usage_plan_key = UsagePlanKey( usage_plan_key = UsagePlanKey(
id=key_id, plan_id=key_id,
type=payload["keyType"], plan_type=payload["keyType"],
name=api_key["name"], name=api_key["name"],
value=api_key["value"], value=api_key["value"],
) )

View File

@ -289,9 +289,9 @@ class APIGatewayResponse(BaseResponse):
) )
authorizer_response = self.backend.create_authorizer( authorizer_response = self.backend.create_authorizer(
restapi_id, restapi_id=restapi_id,
name, name=name,
authorizer_type, authorizer_type=authorizer_type,
provider_arns=provider_arns, provider_arns=provider_arns,
auth_type=auth_type, auth_type=auth_type,
authorizer_uri=authorizer_uri, authorizer_uri=authorizer_uri,

View File

@ -3,6 +3,4 @@ from moto.core.exceptions import JsonRESTError
class AWSValidationException(JsonRESTError): class AWSValidationException(JsonRESTError):
def __init__(self, message, **kwargs): def __init__(self, message, **kwargs):
super(AWSValidationException, self).__init__( super().__init__("ValidationException", message, **kwargs)
"ValidationException", message, **kwargs
)

View File

@ -59,7 +59,7 @@ class ScalableDimensionValueSet(Enum):
class ApplicationAutoscalingBackend(BaseBackend): class ApplicationAutoscalingBackend(BaseBackend):
def __init__(self, region, ecs): def __init__(self, region, ecs):
super(ApplicationAutoscalingBackend, self).__init__() super().__init__()
self.region = region self.region = region
self.ecs_backend = ecs self.ecs_backend = ecs
self.targets = OrderedDict() self.targets = OrderedDict()
@ -124,7 +124,7 @@ class ApplicationAutoscalingBackend(BaseBackend):
"""Raises a ValidationException if an ECS service does not exist """Raises a ValidationException if an ECS service does not exist
for the specified resource ID. for the specified resource ID.
""" """
resource_type, cluster, service = r_id.split("/") _, cluster, service = r_id.split("/")
result, _ = self.ecs_backend.describe_services(cluster, [service]) result, _ = self.ecs_backend.describe_services(cluster, [service])
if len(result) != 1: if len(result) != 1:
raise AWSValidationException("ECS service doesn't exist: {}".format(r_id)) raise AWSValidationException("ECS service doesn't exist: {}".format(r_id))
@ -242,7 +242,7 @@ def _target_params_are_valid(namespace, r_id, dimension):
try: try:
valid_dimensions = [d.value for d in ScalableDimensionValueSet] valid_dimensions = [d.value for d in ScalableDimensionValueSet]
resource_type_exceptions = [r.value for r in ResourceTypeExceptionValueSet] resource_type_exceptions = [r.value for r in ResourceTypeExceptionValueSet]
d_namespace, d_resource_type, scaling_property = dimension.split(":") d_namespace, d_resource_type, _ = dimension.split(":")
if d_resource_type not in resource_type_exceptions: if d_resource_type not in resource_type_exceptions:
resource_type = _get_resource_type_from_resource_id(r_id) resource_type = _get_resource_type_from_resource_id(r_id)
else: else:

View File

@ -4,7 +4,7 @@ from werkzeug.exceptions import BadRequest
class AthenaClientError(BadRequest): class AthenaClientError(BadRequest):
def __init__(self, code, message): def __init__(self, code, message):
super(AthenaClientError, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{ {
"Error": { "Error": {

View File

@ -39,9 +39,7 @@ class WorkGroup(TaggableResourceMixin, BaseModel):
def __init__(self, athena_backend, name, configuration, description, tags): def __init__(self, athena_backend, name, configuration, description, tags):
self.region_name = athena_backend.region_name self.region_name = athena_backend.region_name
super(WorkGroup, self).__init__( super().__init__(self.region_name, "workgroup/{}".format(name), tags)
self.region_name, "workgroup/{}".format(name), tags
)
self.athena_backend = athena_backend self.athena_backend = athena_backend
self.name = name self.name = name
self.description = description self.description = description

View File

@ -43,10 +43,10 @@ class AthenaResponse(BaseResponse):
workgroup = self._get_param("WorkGroup") workgroup = self._get_param("WorkGroup")
if workgroup and not self.athena_backend.get_work_group(workgroup): if workgroup and not self.athena_backend.get_work_group(workgroup):
return self.error("WorkGroup does not exist", 400) return self.error("WorkGroup does not exist", 400)
id = self.athena_backend.start_query_execution( q_exec_id = self.athena_backend.start_query_execution(
query=query, context=context, config=config, workgroup=workgroup query=query, context=context, config=config, workgroup=workgroup
) )
return json.dumps({"QueryExecutionId": id}) return json.dumps({"QueryExecutionId": q_exec_id})
def get_query_execution(self): def get_query_execution(self):
exec_id = self._get_param("QueryExecutionId") exec_id = self._get_param("QueryExecutionId")

View File

@ -9,7 +9,7 @@ class ResourceContentionError(RESTError):
code = 500 code = 500
def __init__(self): def __init__(self):
super(ResourceContentionError, self).__init__( super().__init__(
"ResourceContentionError", "ResourceContentionError",
"You already have a pending update to an Auto Scaling resource (for example, a group, instance, or load balancer).", "You already have a pending update to an Auto Scaling resource (for example, a group, instance, or load balancer).",
) )
@ -17,11 +17,11 @@ class ResourceContentionError(RESTError):
class InvalidInstanceError(AutoscalingClientError): class InvalidInstanceError(AutoscalingClientError):
def __init__(self, instance_id): def __init__(self, instance_id):
super(InvalidInstanceError, self).__init__( super().__init__(
"ValidationError", "Instance [{0}] is invalid.".format(instance_id) "ValidationError", "Instance [{0}] is invalid.".format(instance_id)
) )
class ValidationError(AutoscalingClientError): class ValidationError(AutoscalingClientError):
def __init__(self, message): def __init__(self, message):
super(ValidationError, self).__init__("ValidationError", message) super().__init__("ValidationError", message)

View File

@ -5,21 +5,19 @@ from moto.core.exceptions import JsonRESTError
class LambdaClientError(ClientError): class LambdaClientError(ClientError):
def __init__(self, error, message): def __init__(self, error, message):
error_response = {"Error": {"Code": error, "Message": message}} error_response = {"Error": {"Code": error, "Message": message}}
super(LambdaClientError, self).__init__(error_response, None) super().__init__(error_response, None)
class CrossAccountNotAllowed(LambdaClientError): class CrossAccountNotAllowed(LambdaClientError):
def __init__(self): def __init__(self):
super(CrossAccountNotAllowed, self).__init__( super().__init__(
"AccessDeniedException", "Cross-account pass role is not allowed." "AccessDeniedException", "Cross-account pass role is not allowed."
) )
class InvalidParameterValueException(LambdaClientError): class InvalidParameterValueException(LambdaClientError):
def __init__(self, message): def __init__(self, message):
super(InvalidParameterValueException, self).__init__( super().__init__("InvalidParameterValueException", message)
"InvalidParameterValueException", message
)
class InvalidRoleFormat(LambdaClientError): class InvalidRoleFormat(LambdaClientError):
@ -29,13 +27,11 @@ class InvalidRoleFormat(LambdaClientError):
message = "1 validation error detected: Value '{0}' at 'role' failed to satisfy constraint: Member must satisfy regular expression pattern: {1}".format( message = "1 validation error detected: Value '{0}' at 'role' failed to satisfy constraint: Member must satisfy regular expression pattern: {1}".format(
role, InvalidRoleFormat.pattern role, InvalidRoleFormat.pattern
) )
super(InvalidRoleFormat, self).__init__("ValidationException", message) super().__init__("ValidationException", message)
class PreconditionFailedException(JsonRESTError): class PreconditionFailedException(JsonRESTError):
code = 412 code = 412
def __init__(self, message): def __init__(self, message):
super(PreconditionFailedException, self).__init__( super().__init__("PreconditionFailedException", message)
"PreconditionFailedException", message
)

View File

@ -948,8 +948,10 @@ class LambdaStorage(object):
def get_arn(self, arn): def get_arn(self, arn):
return self._arns.get(arn, None) return self._arns.get(arn, None)
def get_function_by_name_or_arn(self, input, qualifier=None): def get_function_by_name_or_arn(self, name_or_arn, qualifier=None):
return self.get_function_by_name(input, qualifier) or self.get_arn(input) return self.get_function_by_name(name_or_arn, qualifier) or self.get_arn(
name_or_arn
)
def put_function(self, fn): def put_function(self, fn):
""" """
@ -1226,7 +1228,7 @@ class LambdaBackend(BaseBackend):
if not esm: if not esm:
return False return False
for key, value in spec.items(): for key in spec.keys():
if key == "FunctionName": if key == "FunctionName":
func = self._lambdas.get_function_by_name_or_arn(spec[key]) func = self._lambdas.get_function_by_name_or_arn(spec[key])
esm.function_arn = func.function_arn esm.function_arn = func.function_arn

View File

@ -27,7 +27,7 @@ from moto.ec2.models import INSTANCE_TYPES as EC2_INSTANCE_TYPES
from moto.iam.exceptions import IAMNotFoundException from moto.iam.exceptions import IAMNotFoundException
from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID
from moto.core.utils import unix_time_millis from moto.core.utils import unix_time_millis
from moto.utilities.docker_utilities import DockerModel, parse_image_ref from moto.utilities.docker_utilities import DockerModel
from ..utilities.tagging_service import TaggingService from ..utilities.tagging_service import TaggingService
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -197,7 +197,7 @@ class JobDefinition(CloudFormationModel):
_type, _type,
container_properties, container_properties,
region_name, region_name,
tags={}, tags=None,
revision=0, revision=0,
retry_strategy=0, retry_strategy=0,
timeout=None, timeout=None,
@ -217,13 +217,13 @@ class JobDefinition(CloudFormationModel):
self._validate() self._validate()
self._update_arn() self._update_arn()
tags = self._format_tags(tags) tags = self._format_tags(tags or {})
# Validate the tags before proceeding. # Validate the tags before proceeding.
errmsg = self.tagger.validate_tags(tags or []) errmsg = self.tagger.validate_tags(tags)
if errmsg: if errmsg:
raise ValidationError(errmsg) raise ValidationError(errmsg)
self.tagger.tag_resource(self.arn, tags or []) self.tagger.tag_resource(self.arn, tags)
def _format_tags(self, tags): def _format_tags(self, tags):
return [{"Key": k, "Value": v} for k, v in tags.items()] return [{"Key": k, "Value": v} for k, v in tags.items()]
@ -546,9 +546,6 @@ class Job(threading.Thread, BaseModel, DockerModel):
self.job_started_at = datetime.datetime.now() self.job_started_at = datetime.datetime.now()
log_config = docker.types.LogConfig(type=docker.types.LogConfig.types.JSON) log_config = docker.types.LogConfig(type=docker.types.LogConfig.types.JSON)
image_repository, image_tag = parse_image_ref(image)
# avoid explicit pulling here, to allow using cached images
# self.docker_client.images.pull(image_repository, image_tag)
self.job_state = "STARTING" self.job_state = "STARTING"
container = self.docker_client.containers.run( container = self.docker_client.containers.run(
image, image,
@ -691,7 +688,7 @@ class Job(threading.Thread, BaseModel, DockerModel):
class BatchBackend(BaseBackend): class BatchBackend(BaseBackend):
def __init__(self, region_name=None): def __init__(self, region_name=None):
super(BatchBackend, self).__init__() super().__init__()
self.region_name = region_name self.region_name = region_name
self._compute_environments = {} self._compute_environments = {}

View File

@ -15,14 +15,14 @@ class ValidationError(BadRequest):
message = "Stack with id {0} does not exist".format(name_or_id) message = "Stack with id {0} does not exist".format(name_or_id)
template = Template(ERROR_RESPONSE) template = Template(ERROR_RESPONSE)
super(ValidationError, self).__init__() super().__init__()
self.description = template.render(code="ValidationError", message=message) self.description = template.render(code="ValidationError", message=message)
class MissingParameterError(BadRequest): class MissingParameterError(BadRequest):
def __init__(self, parameter_name): def __init__(self, parameter_name):
template = Template(ERROR_RESPONSE) template = Template(ERROR_RESPONSE)
super(MissingParameterError, self).__init__() super().__init__()
self.description = template.render( self.description = template.render(
code="Missing Parameter", code="Missing Parameter",
message="Missing parameter {0}".format(parameter_name), message="Missing parameter {0}".format(parameter_name),
@ -34,7 +34,7 @@ class ExportNotFound(BadRequest):
def __init__(self, export_name): def __init__(self, export_name):
template = Template(ERROR_RESPONSE) template = Template(ERROR_RESPONSE)
super(ExportNotFound, self).__init__() super().__init__()
self.description = template.render( self.description = template.render(
code="ExportNotFound", code="ExportNotFound",
message="No export named {0} found.".format(export_name), message="No export named {0} found.".format(export_name),
@ -44,7 +44,7 @@ class ExportNotFound(BadRequest):
class UnsupportedAttribute(ValidationError): class UnsupportedAttribute(ValidationError):
def __init__(self, resource, attr): def __init__(self, resource, attr):
template = Template(ERROR_RESPONSE) template = Template(ERROR_RESPONSE)
super(UnsupportedAttribute, self).__init__() super().__init__()
self.description = template.render( self.description = template.render(
code="ValidationError", code="ValidationError",
message=f"Template error: resource {resource} does not support attribute type {attr} in Fn::GetAtt", message=f"Template error: resource {resource} does not support attribute type {attr} in Fn::GetAtt",

View File

@ -4,8 +4,10 @@ import yaml
import uuid import uuid
from boto3 import Session from boto3 import Session
from collections import OrderedDict from collections import OrderedDict
from yaml.parser import ParserError # pylint:disable=c-extension-no-member
from yaml.scanner import ScannerError # pylint:disable=c-extension-no-member
from moto.core import BaseBackend, BaseModel from moto.core import BaseBackend, BaseModel
from moto.core.models import ACCOUNT_ID from moto.core.models import ACCOUNT_ID
from moto.core.utils import ( from moto.core.utils import (
@ -54,7 +56,11 @@ class FakeStackSet(BaseModel):
self.stack_instances = self.instances.stack_instances self.stack_instances = self.instances.stack_instances
self.operations = [] self.operations = []
def _create_operation(self, operation_id, action, status, accounts=[], regions=[]): def _create_operation(
self, operation_id, action, status, accounts=None, regions=None
):
accounts = accounts or []
regions = regions or []
operation = { operation = {
"OperationId": str(operation_id), "OperationId": str(operation_id),
"Action": action, "Action": action,
@ -309,7 +315,7 @@ class FakeStack(BaseModel):
yaml.add_multi_constructor("", yaml_tag_constructor) yaml.add_multi_constructor("", yaml_tag_constructor)
try: try:
self.template_dict = yaml.load(self.template, Loader=yaml.Loader) self.template_dict = yaml.load(self.template, Loader=yaml.Loader)
except (yaml.parser.ParserError, yaml.scanner.ScannerError): except (ParserError, ScannerError):
self.template_dict = json.loads(self.template) self.template_dict = json.loads(self.template)
@property @property
@ -418,7 +424,7 @@ class FakeChangeSet(BaseModel):
yaml.add_multi_constructor("", yaml_tag_constructor) yaml.add_multi_constructor("", yaml_tag_constructor)
try: try:
self.template_dict = yaml.load(self.template, Loader=yaml.Loader) self.template_dict = yaml.load(self.template, Loader=yaml.Loader)
except (yaml.parser.ParserError, yaml.scanner.ScannerError): except (ParserError, ScannerError):
self.template_dict = json.loads(self.template) self.template_dict = json.loads(self.template)
@property @property

View File

@ -14,39 +14,41 @@ import collections.abc as collections_abc
# the subclass's module hasn't been imported yet - then that subclass # the subclass's module hasn't been imported yet - then that subclass
# doesn't exist yet, and __subclasses__ won't find it. # doesn't exist yet, and __subclasses__ won't find it.
# So we import here to populate the list of subclasses. # So we import here to populate the list of subclasses.
from moto.apigateway import models as apigateway_models # noqa from moto.apigateway import models # noqa # pylint: disable=all
from moto.autoscaling import models as autoscaling_models # noqa from moto.autoscaling import models # noqa # pylint: disable=all
from moto.awslambda import models as awslambda_models # noqa from moto.awslambda import models # noqa # pylint: disable=all
from moto.batch import models as batch_models # noqa from moto.batch import models # noqa # pylint: disable=all
from moto.cloudformation.custom_model import CustomModel from moto.cloudformation.custom_model import CustomModel
from moto.cloudwatch import models as cloudwatch_models # noqa from moto.cloudwatch import models # noqa # pylint: disable=all
from moto.datapipeline import models as datapipeline_models # noqa from moto.datapipeline import models # noqa # pylint: disable=all
from moto.dynamodb2 import models as dynamodb2_models # noqa from moto.dynamodb2 import models # noqa # pylint: disable=all
from moto.ec2 import models as ec2_models from moto.ec2 import models as ec2_models
from moto.ecr import models as ecr_models # noqa from moto.ecr import models # noqa # pylint: disable=all
from moto.ecs import models as ecs_models # noqa from moto.ecs import models # noqa # pylint: disable=all
from moto.efs import models as efs_models # noqa from moto.efs import models # noqa # pylint: disable=all
from moto.elb import models as elb_models # noqa from moto.elb import models # noqa # pylint: disable=all
from moto.elbv2 import models as elbv2_models # noqa from moto.elbv2 import models # noqa # pylint: disable=all
from moto.events import models as events_models # noqa from moto.events import models # noqa # pylint: disable=all
from moto.iam import models as iam_models # noqa from moto.iam import models # noqa # pylint: disable=all
from moto.kinesis import models as kinesis_models # noqa from moto.kinesis import models # noqa # pylint: disable=all
from moto.kms import models as kms_models # noqa from moto.kms import models # noqa # pylint: disable=all
from moto.rds import models as rds_models # noqa from moto.rds import models # noqa # pylint: disable=all
from moto.rds2 import models as rds2_models # noqa from moto.rds2 import models # noqa # pylint: disable=all
from moto.redshift import models as redshift_models # noqa from moto.redshift import models # noqa # pylint: disable=all
from moto.route53 import models as route53_models # noqa from moto.route53 import models # noqa # pylint: disable=all
from moto.s3 import models as s3_models, s3_backend # noqa from moto.s3 import models # noqa # pylint: disable=all
from moto.s3.utils import bucket_and_name_from_url from moto.sagemaker import models # noqa # pylint: disable=all
from moto.sagemaker import models as sagemaker_models # noqa from moto.sns import models # noqa # pylint: disable=all
from moto.sns import models as sns_models # noqa from moto.sqs import models # noqa # pylint: disable=all
from moto.sqs import models as sqs_models # noqa from moto.stepfunctions import models # noqa # pylint: disable=all
from moto.stepfunctions import models as stepfunctions_models # noqa from moto.ssm import models # noqa # pylint: disable=all
from moto.ssm import models as ssm_models, ssm_backends # noqa
# End ugly list of imports # End ugly list of imports
from moto.core import ACCOUNT_ID, CloudFormationModel from moto.core import ACCOUNT_ID, CloudFormationModel
from moto.s3 import s3_backend
from moto.s3.utils import bucket_and_name_from_url
from moto.ssm import ssm_backends
from .utils import random_suffix from .utils import random_suffix
from .exceptions import ( from .exceptions import (
ExportNotFound, ExportNotFound,
@ -512,7 +514,7 @@ class ResourceMap(collections_abc.Mapping):
self._parsed_resources.update(self._template.get("Mappings", {})) self._parsed_resources.update(self._template.get("Mappings", {}))
def transform_mapping(self): def transform_mapping(self):
for k, v in self._template.get("Mappings", {}).items(): for v in self._template.get("Mappings", {}).values():
if "Fn::Transform" in v: if "Fn::Transform" in v:
name = v["Fn::Transform"]["Name"] name = v["Fn::Transform"]["Name"]
params = v["Fn::Transform"]["Parameters"] params = v["Fn::Transform"]["Parameters"]
@ -600,7 +602,7 @@ class ResourceMap(collections_abc.Mapping):
def validate_outputs(self): def validate_outputs(self):
outputs = self._template.get("Outputs") or {} outputs = self._template.get("Outputs") or {}
for key, value in outputs.items(): for value in outputs.values():
value = value.get("Value", {}) value = value.get("Value", {})
if "Fn::GetAtt" in value: if "Fn::GetAtt" in value:
resource_type = self._resource_json_map.get(value["Fn::GetAtt"][0])[ resource_type = self._resource_json_map.get(value["Fn::GetAtt"][0])[
@ -828,7 +830,7 @@ class OutputMap(collections_abc.Mapping):
def exports(self): def exports(self):
exports = [] exports = []
if self.outputs: if self.outputs:
for key, value in self._output_json_map.items(): for value in self._output_json_map.values():
if value.get("Export"): if value.get("Export"):
cleaned_name = clean_json( cleaned_name = clean_json(
value["Export"].get("Name"), self._resource_map value["Export"].get("Name"), self._resource_map

View File

@ -1,6 +1,8 @@
import json import json
import yaml import yaml
from urllib.parse import urlparse from urllib.parse import urlparse
from yaml.parser import ParserError # pylint:disable=c-extension-no-member
from yaml.scanner import ScannerError # pylint:disable=c-extension-no-member
from moto.core.responses import BaseResponse from moto.core.responses import BaseResponse
from moto.core.utils import amzn_request_id from moto.core.utils import amzn_request_id
@ -28,7 +30,7 @@ def get_template_summary_response_from_template(template_body):
try: try:
template_dict = yaml.load(template_body, Loader=yaml.Loader) template_dict = yaml.load(template_body, Loader=yaml.Loader)
except (yaml.parser.ParserError, yaml.scanner.ScannerError): except (ParserError, ScannerError):
template_dict = json.loads(template_body) template_dict = json.loads(template_body)
resources_types = get_resource_types(template_dict) resources_types = get_resource_types(template_dict)
@ -446,7 +448,7 @@ class CloudFormationResponse(BaseResponse):
pass pass
try: try:
description = yaml.load(template_body, Loader=yaml.Loader)["Description"] description = yaml.load(template_body, Loader=yaml.Loader)["Description"]
except (yaml.parser.ParserError, yaml.scanner.ScannerError, KeyError): except (ParserError, ScannerError, KeyError):
pass pass
template = self.response_template(VALIDATE_STACK_RESPONSE_TEMPLATE) template = self.response_template(VALIDATE_STACK_RESPONSE_TEMPLATE)
return template.render(description=description) return template.render(description=description)

View File

@ -7,34 +7,28 @@ class InvalidParameterCombinationException(JsonRESTError):
code = 400 code = 400
def __init__(self, message): def __init__(self, message):
super(InvalidParameterCombinationException, self).__init__( super().__init__("InvalidParameterCombinationException", message)
"InvalidParameterCombinationException", message
)
class S3BucketDoesNotExistException(JsonRESTError): class S3BucketDoesNotExistException(JsonRESTError):
code = 400 code = 400
def __init__(self, message): def __init__(self, message):
super(S3BucketDoesNotExistException, self).__init__( super().__init__("S3BucketDoesNotExistException", message)
"S3BucketDoesNotExistException", message
)
class InsufficientSnsTopicPolicyException(JsonRESTError): class InsufficientSnsTopicPolicyException(JsonRESTError):
code = 400 code = 400
def __init__(self, message): def __init__(self, message):
super(InsufficientSnsTopicPolicyException, self).__init__( super().__init__("InsufficientSnsTopicPolicyException", message)
"InsufficientSnsTopicPolicyException", message
)
class TrailNotFoundException(JsonRESTError): class TrailNotFoundException(JsonRESTError):
code = 400 code = 400
def __init__(self, name): def __init__(self, name):
super(TrailNotFoundException, self).__init__( super().__init__(
"TrailNotFoundException", "TrailNotFoundException",
f"Unknown trail: {name} for the user: {ACCOUNT_ID}", f"Unknown trail: {name} for the user: {ACCOUNT_ID}",
) )
@ -44,41 +38,35 @@ class InvalidTrailNameException(JsonRESTError):
code = 400 code = 400
def __init__(self, message): def __init__(self, message):
super(InvalidTrailNameException, self).__init__( super().__init__("InvalidTrailNameException", message)
"InvalidTrailNameException", message
)
class TrailNameTooShort(InvalidTrailNameException): class TrailNameTooShort(InvalidTrailNameException):
def __init__(self, actual_length): def __init__(self, actual_length):
super(TrailNameTooShort, self).__init__( super().__init__(
f"Trail name too short. Minimum allowed length: 3 characters. Specified name length: {actual_length} characters." f"Trail name too short. Minimum allowed length: 3 characters. Specified name length: {actual_length} characters."
) )
class TrailNameTooLong(InvalidTrailNameException): class TrailNameTooLong(InvalidTrailNameException):
def __init__(self, actual_length): def __init__(self, actual_length):
super(TrailNameTooLong, self).__init__( super().__init__(
f"Trail name too long. Maximum allowed length: 128 characters. Specified name length: {actual_length} characters." f"Trail name too long. Maximum allowed length: 128 characters. Specified name length: {actual_length} characters."
) )
class TrailNameNotStartingCorrectly(InvalidTrailNameException): class TrailNameNotStartingCorrectly(InvalidTrailNameException):
def __init__(self): def __init__(self):
super(TrailNameNotStartingCorrectly, self).__init__( super().__init__("Trail name must starts with a letter or number.")
"Trail name must starts with a letter or number."
)
class TrailNameNotEndingCorrectly(InvalidTrailNameException): class TrailNameNotEndingCorrectly(InvalidTrailNameException):
def __init__(self): def __init__(self):
super(TrailNameNotEndingCorrectly, self).__init__( super().__init__("Trail name must ends with a letter or number.")
"Trail name must ends with a letter or number."
)
class TrailNameInvalidChars(InvalidTrailNameException): class TrailNameInvalidChars(InvalidTrailNameException):
def __init__(self): def __init__(self):
super(TrailNameInvalidChars, self).__init__( super().__init__(
"Trail name or ARN can only contain uppercase letters, lowercase letters, numbers, periods (.), hyphens (-), and underscores (_)." "Trail name or ARN can only contain uppercase letters, lowercase letters, numbers, periods (.), hyphens (-), and underscores (_)."
) )

View File

@ -64,9 +64,9 @@ class MetricStat(object):
class MetricDataQuery(object): class MetricDataQuery(object):
def __init__( def __init__(
self, id, label, period, return_data, expression=None, metric_stat=None self, query_id, label, period, return_data, expression=None, metric_stat=None
): ):
self.id = id self.id = query_id
self.label = label self.label = label
self.period = period self.period = period
self.return_data = return_data self.return_data = return_data
@ -214,13 +214,13 @@ class MetricDatum(BaseModel):
] ]
self.unit = unit self.unit = unit
def filter(self, namespace, name, dimensions, already_present_metrics=[]): def filter(self, namespace, name, dimensions, already_present_metrics=None):
if namespace and namespace != self.namespace: if namespace and namespace != self.namespace:
return False return False
if name and name != self.name: if name and name != self.name:
return False return False
for metric in already_present_metrics: for metric in already_present_metrics or []:
if self.dimensions and are_dimensions_same( if self.dimensions and are_dimensions_same(
metric.dimensions, self.dimensions metric.dimensions, self.dimensions
): ):

View File

@ -55,7 +55,7 @@ class CloudWatchResponse(BaseResponse):
) )
metric_data_queries.append( metric_data_queries.append(
MetricDataQuery( MetricDataQuery(
id=metric.get("Id"), query_id=metric.get("Id"),
label=metric.get("Label"), label=metric.get("Label"),
period=metric.get("Period"), period=metric.get("Period"),
return_data=metric.get("ReturnData"), return_data=metric.get("ReturnData"),

View File

@ -5,7 +5,7 @@ class RepositoryNameExistsException(JsonRESTError):
code = 400 code = 400
def __init__(self, repository_name): def __init__(self, repository_name):
super(RepositoryNameExistsException, self).__init__( super().__init__(
"RepositoryNameExistsException", "RepositoryNameExistsException",
"Repository named {0} already exists".format(repository_name), "Repository named {0} already exists".format(repository_name),
) )
@ -15,7 +15,7 @@ class RepositoryDoesNotExistException(JsonRESTError):
code = 400 code = 400
def __init__(self, repository_name): def __init__(self, repository_name):
super(RepositoryDoesNotExistException, self).__init__( super().__init__(
"RepositoryDoesNotExistException", "RepositoryDoesNotExistException",
"{0} does not exist".format(repository_name), "{0} does not exist".format(repository_name),
) )
@ -25,7 +25,7 @@ class InvalidRepositoryNameException(JsonRESTError):
code = 400 code = 400
def __init__(self): def __init__(self):
super(InvalidRepositoryNameException, self).__init__( super().__init__(
"InvalidRepositoryNameException", "InvalidRepositoryNameException",
"The repository name is not valid. Repository names can be any valid " "The repository name is not valid. Repository names can be any valid "
"combination of letters, numbers, " "combination of letters, numbers, "

View File

@ -5,40 +5,34 @@ class InvalidStructureException(JsonRESTError):
code = 400 code = 400
def __init__(self, message): def __init__(self, message):
super(InvalidStructureException, self).__init__( super().__init__("InvalidStructureException", message)
"InvalidStructureException", message
)
class PipelineNotFoundException(JsonRESTError): class PipelineNotFoundException(JsonRESTError):
code = 400 code = 400
def __init__(self, message): def __init__(self, message):
super(PipelineNotFoundException, self).__init__( super().__init__("PipelineNotFoundException", message)
"PipelineNotFoundException", message
)
class ResourceNotFoundException(JsonRESTError): class ResourceNotFoundException(JsonRESTError):
code = 400 code = 400
def __init__(self, message): def __init__(self, message):
super(ResourceNotFoundException, self).__init__( super().__init__("ResourceNotFoundException", message)
"ResourceNotFoundException", message
)
class InvalidTagsException(JsonRESTError): class InvalidTagsException(JsonRESTError):
code = 400 code = 400
def __init__(self, message): def __init__(self, message):
super(InvalidTagsException, self).__init__("InvalidTagsException", message) super().__init__("InvalidTagsException", message)
class TooManyTagsException(JsonRESTError): class TooManyTagsException(JsonRESTError):
code = 400 code = 400
def __init__(self, arn): def __init__(self, arn):
super(TooManyTagsException, self).__init__( super().__init__(
"TooManyTagsException", "Tag limit exceeded for resource [{}].".format(arn) "TooManyTagsException", "Tag limit exceeded for resource [{}].".format(arn)
) )

View File

@ -5,7 +5,7 @@ from werkzeug.exceptions import BadRequest
class ResourceNotFoundError(BadRequest): class ResourceNotFoundError(BadRequest):
def __init__(self, message): def __init__(self, message):
super(ResourceNotFoundError, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{"message": message, "__type": "ResourceNotFoundException"} {"message": message, "__type": "ResourceNotFoundException"}
) )
@ -16,7 +16,7 @@ class InvalidNameException(BadRequest):
message = "1 validation error detected: Value '{}' at 'identityPoolName' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\w\\s+=,.@-]+" message = "1 validation error detected: Value '{}' at 'identityPoolName' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\w\\s+=,.@-]+"
def __init__(self, name): def __init__(self, name):
super(InvalidNameException, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{ {
"message": InvalidNameException.message.format(name), "message": InvalidNameException.message.format(name),

View File

@ -51,7 +51,7 @@ class CognitoIdentity(BaseModel):
class CognitoIdentityBackend(BaseBackend): class CognitoIdentityBackend(BaseBackend):
def __init__(self, region): def __init__(self, region):
super(CognitoIdentityBackend, self).__init__() super().__init__()
self.region = region self.region = region
self.identity_pools = OrderedDict() self.identity_pools = OrderedDict()
self.pools_identities = {} self.pools_identities = {}

View File

@ -5,7 +5,7 @@ from moto.core.exceptions import JsonRESTError
class ResourceNotFoundError(BadRequest): class ResourceNotFoundError(BadRequest):
def __init__(self, message): def __init__(self, message):
super(ResourceNotFoundError, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{"message": message, "__type": "ResourceNotFoundException"} {"message": message, "__type": "ResourceNotFoundException"}
) )
@ -13,7 +13,7 @@ class ResourceNotFoundError(BadRequest):
class UserNotFoundError(BadRequest): class UserNotFoundError(BadRequest):
def __init__(self, message): def __init__(self, message):
super(UserNotFoundError, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{"message": message, "__type": "UserNotFoundException"} {"message": message, "__type": "UserNotFoundException"}
) )
@ -21,7 +21,7 @@ class UserNotFoundError(BadRequest):
class UsernameExistsException(BadRequest): class UsernameExistsException(BadRequest):
def __init__(self, message): def __init__(self, message):
super(UsernameExistsException, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{"message": message, "__type": "UsernameExistsException"} {"message": message, "__type": "UsernameExistsException"}
) )
@ -29,7 +29,7 @@ class UsernameExistsException(BadRequest):
class GroupExistsException(BadRequest): class GroupExistsException(BadRequest):
def __init__(self, message): def __init__(self, message):
super(GroupExistsException, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{"message": message, "__type": "GroupExistsException"} {"message": message, "__type": "GroupExistsException"}
) )
@ -37,7 +37,7 @@ class GroupExistsException(BadRequest):
class NotAuthorizedError(BadRequest): class NotAuthorizedError(BadRequest):
def __init__(self, message): def __init__(self, message):
super(NotAuthorizedError, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{"message": message, "__type": "NotAuthorizedException"} {"message": message, "__type": "NotAuthorizedException"}
) )
@ -45,7 +45,7 @@ class NotAuthorizedError(BadRequest):
class UserNotConfirmedException(BadRequest): class UserNotConfirmedException(BadRequest):
def __init__(self, message): def __init__(self, message):
super(UserNotConfirmedException, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{"message": message, "__type": "UserNotConfirmedException"} {"message": message, "__type": "UserNotConfirmedException"}
) )
@ -53,7 +53,7 @@ class UserNotConfirmedException(BadRequest):
class ExpiredCodeException(BadRequest): class ExpiredCodeException(BadRequest):
def __init__(self, message): def __init__(self, message):
super(ExpiredCodeException, self).__init__() super().__init__()
self.description = json.dumps( self.description = json.dumps(
{"message": message, "__type": "ExpiredCodeException"} {"message": message, "__type": "ExpiredCodeException"}
) )
@ -62,6 +62,6 @@ class ExpiredCodeException(BadRequest):
class InvalidParameterException(JsonRESTError): class InvalidParameterException(JsonRESTError):
def __init__(self, msg=None): def __init__(self, msg=None):
self.code = 400 self.code = 400
super(InvalidParameterException, self).__init__( super().__init__(
"InvalidParameterException", msg or "A parameter is specified incorrectly." "InvalidParameterException", msg or "A parameter is specified incorrectly."
) )

View File

@ -421,7 +421,7 @@ class CognitoIdpUserPool(BaseModel):
return self.users.get(username) return self.users.get(username)
def create_jwt( def create_jwt(
self, client_id, username, token_use, expires_in=60 * 60, extra_data={} self, client_id, username, token_use, expires_in=60 * 60, extra_data=None
): ):
now = int(time.time()) now = int(time.time())
payload = { payload = {
@ -435,7 +435,7 @@ class CognitoIdpUserPool(BaseModel):
"exp": now + expires_in, "exp": now + expires_in,
"email": flatten_attrs(self._get_user(username).attributes).get("email"), "email": flatten_attrs(self._get_user(username).attributes).get("email"),
} }
payload.update(extra_data) payload.update(extra_data or {})
headers = {"kid": "dummy"} # KID as present in jwks-public.json headers = {"kid": "dummy"} # KID as present in jwks-public.json
return ( return (
@ -517,12 +517,12 @@ class CognitoIdpUserPoolDomain(BaseModel):
def _distribution_name(self): def _distribution_name(self):
if self.custom_domain_config and "CertificateArn" in self.custom_domain_config: if self.custom_domain_config and "CertificateArn" in self.custom_domain_config:
hash = hashlib.md5( unique_hash = hashlib.md5(
self.custom_domain_config["CertificateArn"].encode("utf-8") self.custom_domain_config["CertificateArn"].encode("utf-8")
).hexdigest() ).hexdigest()
return "{hash}.cloudfront.net".format(hash=hash[:16]) return f"{unique_hash[:16]}.cloudfront.net"
hash = hashlib.md5(self.user_pool_id.encode("utf-8")).hexdigest() unique_hash = hashlib.md5(self.user_pool_id.encode("utf-8")).hexdigest()
return "{hash}.amazoncognito.com".format(hash=hash[:16]) return f"{unique_hash[:16]}.amazoncognito.com"
def to_json(self, extended=True): def to_json(self, extended=True):
distribution = self._distribution_name() distribution = self._distribution_name()
@ -730,7 +730,7 @@ class CognitoResourceServer(BaseModel):
class CognitoIdpBackend(BaseBackend): class CognitoIdpBackend(BaseBackend):
def __init__(self, region): def __init__(self, region):
super(CognitoIdpBackend, self).__init__() super().__init__()
self.region = region self.region = region
self.user_pools = OrderedDict() self.user_pools = OrderedDict()
self.user_pool_domains = OrderedDict() self.user_pool_domains = OrderedDict()

View File

@ -50,7 +50,7 @@ class RESTError(HTTPException):
} }
def __init__(self, error_type, message, template="error", **kwargs): def __init__(self, error_type, message, template="error", **kwargs):
super(RESTError, self).__init__() super().__init__()
self.error_type = error_type self.error_type = error_type
self.message = message self.message = message
@ -80,7 +80,7 @@ class DryRunClientError(RESTError):
class JsonRESTError(RESTError): class JsonRESTError(RESTError):
def __init__(self, error_type, message, template="error_json", **kwargs): def __init__(self, error_type, message, template="error_json", **kwargs):
super(JsonRESTError, self).__init__(error_type, message, template, **kwargs) super().__init__(error_type, message, template, **kwargs)
self.description = json.dumps( self.description = json.dumps(
{"__type": self.error_type, "message": self.message} {"__type": self.error_type, "message": self.message}
) )
@ -94,7 +94,7 @@ class SignatureDoesNotMatchError(RESTError):
code = 403 code = 403
def __init__(self): def __init__(self):
super(SignatureDoesNotMatchError, self).__init__( super().__init__(
"SignatureDoesNotMatch", "SignatureDoesNotMatch",
"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.", "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.",
) )
@ -104,7 +104,7 @@ class InvalidClientTokenIdError(RESTError):
code = 403 code = 403
def __init__(self): def __init__(self):
super(InvalidClientTokenIdError, self).__init__( super().__init__(
"InvalidClientTokenId", "InvalidClientTokenId",
"The security token included in the request is invalid.", "The security token included in the request is invalid.",
) )
@ -114,7 +114,7 @@ class AccessDeniedError(RESTError):
code = 403 code = 403
def __init__(self, user_arn, action): def __init__(self, user_arn, action):
super(AccessDeniedError, self).__init__( super().__init__(
"AccessDenied", "AccessDenied",
"User: {user_arn} is not authorized to perform: {operation}".format( "User: {user_arn} is not authorized to perform: {operation}".format(
user_arn=user_arn, operation=action user_arn=user_arn, operation=action
@ -126,7 +126,7 @@ class AuthFailureError(RESTError):
code = 401 code = 401
def __init__(self): def __init__(self):
super(AuthFailureError, self).__init__( super().__init__(
"AuthFailure", "AuthFailure",
"AWS was not able to validate the provided access credentials", "AWS was not able to validate the provided access credentials",
) )
@ -136,10 +136,10 @@ class AWSError(Exception):
TYPE = None TYPE = None
STATUS = 400 STATUS = 400
def __init__(self, message, type=None, status=None): def __init__(self, message, exception_type=None, status=None):
self.message = message self.message = message
self.type = type if type is not None else self.TYPE self.type = exception_type or self.TYPE
self.status = status if status is not None else self.STATUS self.status = status or self.STATUS
def response(self): def response(self):
return ( return (
@ -154,7 +154,7 @@ class InvalidNextTokenException(JsonRESTError):
code = 400 code = 400
def __init__(self): def __init__(self):
super(InvalidNextTokenException, self).__init__( super().__init__(
"InvalidNextTokenException", "The nextToken provided is invalid" "InvalidNextTokenException", "The nextToken provided is invalid"
) )
@ -164,4 +164,4 @@ class InvalidToken(AWSError):
STATUS = 400 STATUS = 400
def __init__(self, message="Invalid token"): def __init__(self, message="Invalid token"):
super(InvalidToken, self).__init__("Invalid Token: {}".format(message)) super().__init__("Invalid Token: {}".format(message))

View File

@ -289,10 +289,7 @@ responses_mock.add_passthru("http")
def _find_first_match_legacy(self, request): def _find_first_match_legacy(self, request):
matches = [] matches = [match for match in self._matches if match.matches(request)]
for i, match in enumerate(self._matches):
if match.matches(request):
matches.append(match)
# Look for implemented callbacks first # Look for implemented callbacks first
implemented_matches = [ implemented_matches = [
@ -311,7 +308,7 @@ def _find_first_match_legacy(self, request):
def _find_first_match(self, request): def _find_first_match(self, request):
matches = [] matches = []
match_failed_reasons = [] match_failed_reasons = []
for i, match in enumerate(self._matches): for match in self._matches:
match_result, reason = match.matches(request) match_result, reason = match.matches(request)
if match_result: if match_result:
matches.append(match) matches.append(match)
@ -351,10 +348,10 @@ BOTOCORE_HTTP_METHODS = ["GET", "DELETE", "HEAD", "OPTIONS", "PATCH", "POST", "P
class MockRawResponse(BytesIO): class MockRawResponse(BytesIO):
def __init__(self, input): def __init__(self, response_input):
if isinstance(input, str): if isinstance(response_input, str):
input = input.encode("utf-8") response_input = response_input.encode("utf-8")
super(MockRawResponse, self).__init__(input) super().__init__(response_input)
def stream(self, **kwargs): def stream(self, **kwargs):
contents = self.read() contents = self.read()
@ -553,7 +550,7 @@ class ServerModeMockAWS(BaseMockAWS):
if "region_name" in kwargs: if "region_name" in kwargs:
return kwargs["region_name"] return kwargs["region_name"]
if type(args) == tuple and len(args) == 2: if type(args) == tuple and len(args) == 2:
service, region = args _, region = args
return region return region
return None return None
@ -565,7 +562,7 @@ class ServerModeMockAWS(BaseMockAWS):
class Model(type): class Model(type):
def __new__(self, clsname, bases, namespace): def __new__(self, clsname, bases, namespace):
cls = super(Model, self).__new__(self, clsname, bases, namespace) cls = super().__new__(self, clsname, bases, namespace)
cls.__models__ = {} cls.__models__ = {}
for name, value in namespace.items(): for name, value in namespace.items():
model = getattr(value, "__returns_model__", False) model = getattr(value, "__returns_model__", False)
@ -679,8 +676,8 @@ class CloudFormationModel(BaseModel):
class BaseBackend: class BaseBackend:
def _reset_model_refs(self): def _reset_model_refs(self):
# Remove all references to the models stored # Remove all references to the models stored
for service, models in model_data.items(): for models in model_data.values():
for model_name, model in models.items(): for model in models.values():
model.instances = [] model.instances = []
def reset(self): def reset(self):
@ -954,7 +951,7 @@ class MotoAPIBackend(BaseBackend):
for name, backends_ in backends.loaded_backends(): for name, backends_ in backends.loaded_backends():
if name == "moto_api": if name == "moto_api":
continue continue
for region_name, backend in backends_.items(): for backend in backends_.values():
backend.reset() backend.reset()
self.__init__() self.__init__()

View File

@ -82,7 +82,7 @@ class _TemplateEnvironmentMixin(object):
RIGHT_PATTERN = re.compile(r">[\s\n]+") RIGHT_PATTERN = re.compile(r">[\s\n]+")
def __init__(self): def __init__(self):
super(_TemplateEnvironmentMixin, self).__init__() super().__init__()
self.loader = DynamicDictLoader({}) self.loader = DynamicDictLoader({})
self.environment = Environment( self.environment = Environment(
loader=self.loader, autoescape=self.should_autoescape loader=self.loader, autoescape=self.should_autoescape
@ -237,7 +237,7 @@ class BaseResponse(_TemplateEnvironmentMixin, ActionAuthenticatorMixin):
target = request.headers.get("x-amz-target") or request.headers.get( target = request.headers.get("x-amz-target") or request.headers.get(
"X-Amz-Target" "X-Amz-Target"
) )
service, method = target.split(".") _, method = target.split(".")
input_spec = self.aws_service_spec.input_spec(method) input_spec = self.aws_service_spec.input_spec(method)
flat = flatten_json_request_body("", decoded, input_spec) flat = flatten_json_request_body("", decoded, input_spec)
for key, value in flat.items(): for key, value in flat.items():

View File

@ -207,8 +207,8 @@ def rfc_1123_datetime(datetime):
return datetime.strftime(RFC1123) return datetime.strftime(RFC1123)
def str_to_rfc_1123_datetime(str): def str_to_rfc_1123_datetime(value):
return datetime.datetime.strptime(str, RFC1123) return datetime.datetime.strptime(value, RFC1123)
def unix_time(dt=None): def unix_time(dt=None):
@ -320,7 +320,7 @@ def tags_from_query_string(
querystring_dict, prefix="Tag", key_suffix="Key", value_suffix="Value" querystring_dict, prefix="Tag", key_suffix="Key", value_suffix="Value"
): ):
response_values = {} response_values = {}
for key, value in querystring_dict.items(): for key in querystring_dict.keys():
if key.startswith(prefix) and key.endswith(key_suffix): if key.startswith(prefix) and key.endswith(key_suffix):
tag_index = key.replace(prefix + ".", "").replace("." + key_suffix, "") tag_index = key.replace(prefix + ".", "").replace("." + key_suffix, "")
tag_key = querystring_dict.get( tag_key = querystring_dict.get(
@ -405,11 +405,11 @@ def aws_api_matches(pattern, string):
""" """
# use a negative lookback regex to match stars that are not prefixed with a backslash # use a negative lookback regex to match stars that are not prefixed with a backslash
# and replace all stars not prefixed w/ a backslash with '.*' to take this from "glob" to PCRE syntax # and replace all stars not prefixed w/ a backslash with '.*' to take this from "glob" to PCRE syntax
pattern, n = re.subn(r"(?<!\\)\*", r".*", pattern) pattern, _ = re.subn(r"(?<!\\)\*", r".*", pattern)
# ? in the AWS glob form becomes .? in regex # ? in the AWS glob form becomes .? in regex
# also, don't substitute it if it is prefixed w/ a backslash # also, don't substitute it if it is prefixed w/ a backslash
pattern, m = re.subn(r"(?<!\\)\?", r".?", pattern) pattern, _ = re.subn(r"(?<!\\)\?", r".?", pattern)
# aws api seems to anchor # aws api seems to anchor
anchored_pattern = f"^{pattern}$" anchored_pattern = f"^{pattern}$"

View File

@ -15,4 +15,4 @@ exclude = moto/packages,dist
[pylint.'MESSAGES CONTROL'] [pylint.'MESSAGES CONTROL']
disable = W,C,R,E disable = W,C,R,E
# Check we have any tests with duplicate names (causing them to be skipped) # Check we have any tests with duplicate names (causing them to be skipped)
enable = function-redefined, redefined-builtin, unused-variable, dangerous-default-value, W0401, W0402, W0403, W0404, W0406, W0611 enable = function-redefined, redefined-builtin, unused-variable, dangerous-default-value, super-with-arguments, W0401, W0402, W0403, W0404, W0406, W0611

View File

@ -1017,7 +1017,7 @@ def test_boto3_update_settype_item_with_conditions():
"""A set with predictable iteration order""" """A set with predictable iteration order"""
def __init__(self, values): def __init__(self, values):
super(OrderedSet, self).__init__(values) super().__init__(values)
self.__ordered_values = values self.__ordered_values = values
def __iter__(self): def __iter__(self):

View File

@ -16,7 +16,7 @@ class AuthenticatedClient(FlaskClient):
kwargs["headers"] = kwargs.get("headers", {}) kwargs["headers"] = kwargs.get("headers", {})
kwargs["headers"]["Authorization"] = "Any authorization header" kwargs["headers"]["Authorization"] = "Any authorization header"
kwargs["content_length"] = 0 # Fixes content-length complaints. kwargs["content_length"] = 0 # Fixes content-length complaints.
return super(AuthenticatedClient, self).open(*args, **kwargs) return super().open(*args, **kwargs)
def authenticated_client(): def authenticated_client():

View File

@ -13,7 +13,7 @@ class AuthenticatedClient(FlaskClient):
kwargs["headers"] = kwargs.get("headers", {}) kwargs["headers"] = kwargs.get("headers", {})
kwargs["headers"]["Authorization"] = "Any authorization header" kwargs["headers"]["Authorization"] = "Any authorization header"
kwargs["content_length"] = 0 # Fixes content-length complaints. kwargs["content_length"] = 0 # Fixes content-length complaints.
return super(AuthenticatedClient, self).open(*args, **kwargs) return super().open(*args, **kwargs)
def authenticated_client(): def authenticated_client():