From eed32a5f72fbdc0d33c4876d1b5439dfd1efd5d8 Mon Sep 17 00:00:00 2001 From: Bert Blommers Date: Fri, 11 Mar 2022 20:28:45 -0100 Subject: [PATCH] Pylint - Enable more rules on source and tests-directory (#4929) --- Makefile | 2 +- moto/acm/models.py | 4 +- moto/acm/responses.py | 8 +- moto/apigateway/exceptions.py | 2 +- .../integration_parsers/__init__.py | 7 ++ .../integration_parsers/aws_parser.py | 4 +- .../integration_parsers/http_parser.py | 4 +- .../integration_parsers/unknown_parser.py | 5 +- moto/apigateway/models.py | 14 ++- moto/apigatewayv2/models.py | 3 - moto/apigatewayv2/responses.py | 6 -- moto/autoscaling/models.py | 19 ++-- moto/autoscaling/responses.py | 8 +- moto/awslambda/models.py | 18 ++-- moto/awslambda/responses.py | 95 +++++++++---------- moto/batch/models.py | 36 +++---- moto/batch/responses.py | 26 +---- moto/cloudformation/custom_model.py | 2 +- moto/cloudformation/models.py | 27 +++--- moto/cloudformation/parsing.py | 2 +- moto/cloudformation/responses.py | 19 +--- moto/codecommit/models.py | 10 +- moto/codecommit/responses.py | 1 - moto/codepipeline/models.py | 10 +- moto/codepipeline/responses.py | 2 +- moto/cognitoidentity/models.py | 9 +- moto/cognitoidentity/responses.py | 2 - moto/cognitoidp/models.py | 7 +- moto/cognitoidp/responses.py | 12 +-- moto/config/models.py | 23 +++-- moto/config/responses.py | 6 +- moto/core/custom_responses_mock.py | 2 +- moto/core/exceptions.py | 4 +- moto/core/models.py | 6 +- moto/core/responses.py | 12 ++- moto/databrew/models.py | 5 +- moto/databrew/responses.py | 8 +- moto/datapipeline/models.py | 1 + moto/dax/models.py | 15 +-- moto/dax/responses.py | 21 +--- moto/dms/models.py | 30 +++--- moto/dms/responses.py | 36 +------ moto/dynamodb/models/__init__.py | 10 +- moto/dynamodb/parsing/expressions.py | 2 +- moto/dynamodb_v20111205/models.py | 10 +- moto/ec2/exceptions.py | 7 +- moto/ec2/models.py | 53 +++++------ moto/ec2/responses/amis.py | 7 +- .../egress_only_internet_gateways.py | 5 +- moto/ec2/responses/subnets.py | 1 - .../responses/transit_gateway_attachments.py | 6 -- moto/ecr/models.py | 15 ++- moto/ecr/responses.py | 7 +- moto/ecs/models.py | 25 +++-- moto/ecs/responses.py | 21 +--- moto/eks/exceptions.py | 2 +- moto/elastictranscoder/models.py | 22 ++--- moto/elastictranscoder/responses.py | 17 +--- moto/elb/models.py | 4 +- moto/elbv2/exceptions.py | 2 +- moto/elbv2/models.py | 4 +- moto/emr/models.py | 10 +- moto/emr/responses.py | 2 +- moto/emr/utils.py | 6 +- moto/es/models.py | 5 +- moto/es/responses.py | 6 +- moto/events/models.py | 14 +-- moto/events/responses.py | 4 +- moto/glacier/responses.py | 35 +++---- moto/guardduty/models.py | 4 +- moto/guardduty/responses.py | 3 +- moto/iam/models.py | 72 +++++++------- moto/iam/responses.py | 14 +-- moto/instance_metadata/responses.py | 4 +- moto/iot/models.py | 48 ++++++---- moto/iot/responses.py | 45 ++------- moto/iotdata/models.py | 2 +- moto/iotdata/responses.py | 3 +- moto/kinesis/models.py | 17 ++-- moto/kinesis/responses.py | 2 - moto/kinesisvideo/models.py | 10 +- moto/kinesisvideo/responses.py | 14 +-- moto/kinesisvideoarchivedmedia/models.py | 27 +----- moto/kinesisvideoarchivedmedia/responses.py | 39 +------- moto/kms/models.py | 8 +- moto/kms/responses.py | 2 - moto/logs/models.py | 70 +++----------- moto/logs/responses.py | 21 +--- moto/managedblockchain/exceptions.py | 6 +- moto/managedblockchain/responses.py | 52 ++++------ moto/mediaconnect/models.py | 4 +- moto/medialive/models.py | 14 +-- moto/medialive/responses.py | 8 -- moto/mediapackage/models.py | 4 +- moto/mediastore/models.py | 7 +- moto/mediastore/responses.py | 6 +- moto/mediastoredata/models.py | 17 ++-- moto/mediastoredata/responses.py | 15 +-- moto/mq/models.py | 1 - moto/mq/responses.py | 2 - moto/organizations/models.py | 4 +- moto/organizations/responses.py | 12 +-- moto/polly/models.py | 10 +- moto/polly/responses.py | 7 +- moto/rds/models.py | 14 +-- moto/rds/responses.py | 3 +- moto/redshift/models.py | 4 +- moto/resourcegroups/models.py | 11 +-- moto/resourcegroups/responses.py | 18 +--- moto/resourcegroupstaggingapi/models.py | 6 +- moto/route53/models.py | 10 +- moto/route53/responses.py | 3 +- moto/s3/models.py | 15 +-- moto/s3/responses.py | 43 ++++----- moto/s3control/responses.py | 4 +- moto/sagemaker/models.py | 27 ++---- moto/sagemaker/responses.py | 27 +++--- moto/sdb/models.py | 8 +- moto/sdb/responses.py | 16 +--- moto/secretsmanager/models.py | 5 +- moto/server.py | 2 +- moto/sns/models.py | 4 +- moto/sqs/models.py | 4 +- moto/ssm/models.py | 22 ++--- moto/ssm/responses.py | 21 ++-- moto/stepfunctions/models.py | 4 +- moto/sts/models.py | 6 +- moto/sts/responses.py | 4 +- moto/support/models.py | 18 ++-- moto/support/responses.py | 15 +-- moto/swf/models/__init__.py | 4 +- moto/swf/responses.py | 13 +-- moto/textract/models.py | 18 ++-- moto/textract/responses.py | 18 +--- moto/timestreamwrite/models.py | 2 +- moto/timestreamwrite/responses.py | 3 +- moto/xray/models.py | 11 +-- moto/xray/responses.py | 10 +- setup.cfg | 4 +- tests/test_acm/test_acm.py | 17 ++-- tests/test_appsync/test_appsync_schema.py | 12 +-- tests/test_core/test_decorator_calls.py | 6 +- tests/test_core/test_importorder.py | 16 +++- tests/test_dynamodb_v20111205/test_server.py | 2 +- .../test_servermode.py | 2 +- tests/test_ec2/test_account_attributes.py | 2 +- tests/test_ec2/test_ec2_integration.py | 2 +- tests/test_ec2/test_egress_only_igw.py | 2 +- tests/test_ec2/test_route_tables.py | 2 +- tests/test_ecr/test_ecr_policy_validation.py | 6 +- tests/test_efs/test_file_system.py | 4 +- tests/test_efs/test_mount_target.py | 14 ++- tests/test_efs/test_server.py | 4 +- tests/test_eks/test_eks.py | 6 +- tests/test_elasticbeanstalk/test_eb.py | 2 +- .../test_emrcontainers/test_emrcontainers.py | 8 +- tests/test_iam/test_iam.py | 2 +- tests/test_iam/test_iam_account_aliases.py | 2 +- tests/test_iam/test_iam_cloudformation.py | 2 +- tests/test_iam/test_iam_policies.py | 2 +- tests/test_iam/test_server.py | 2 +- tests/test_kms/test_kms_boto3.py | 13 +-- tests/test_logs/test_logs.py | 18 +--- tests/test_s3/test_s3.py | 20 ++-- tests/test_s3/test_s3_cloudformation.py | 2 +- tests/test_s3/test_s3_config.py | 6 +- tests/test_s3/test_s3_metadata.py | 2 +- tests/test_s3/test_s3_multipart.py | 4 +- tests/test_s3/test_s3_storageclass.py | 2 +- tests/test_s3/test_s3_utils.py | 2 +- tests/test_s3/test_server.py | 2 +- tests/test_sns/test_subscriptions_boto3.py | 9 +- tests/test_ssm/test_ssm_parameterstore.py | 12 +-- tests/test_utilities/test_docker_utilities.py | 2 +- tests/test_utilities/test_threaded_server.py | 4 +- tests/test_xray/test_xray_client.py | 2 +- 176 files changed, 795 insertions(+), 1228 deletions(-) diff --git a/Makefile b/Makefile index 0942c8d96..46361c45e 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ init: lint: @echo "Running flake8..." - flake8 moto + flake8 moto tests @echo "Running black... " @echo "(Make sure you have black-22.1.0 installed, as other versions will produce different results)" black --check moto/ tests/ diff --git a/moto/acm/models.py b/moto/acm/models.py index eeb6e27bb..99f5b4f44 100644 --- a/moto/acm/models.py +++ b/moto/acm/models.py @@ -535,11 +535,13 @@ class AWSCertificateManagerBackend(BaseBackend): def request_certificate( self, domain_name, - domain_validation_options, idempotency_token, subject_alt_names, tags=None, ): + """ + The parameter DomainValidationOptions has not yet been implemented + """ if idempotency_token is not None: arn = self._get_arn_from_idempotency_token(idempotency_token) if arn and self._certificates[arn].tags.equals(tags): diff --git a/moto/acm/responses.py b/moto/acm/responses.py index 80dcfd878..d52ea38d0 100644 --- a/moto/acm/responses.py +++ b/moto/acm/responses.py @@ -23,8 +23,8 @@ class AWSCertificateManagerResponse(BaseResponse): except ValueError: return {} - def _get_param(self, param, default=None): - return self.request_params.get(param, default) + def _get_param(self, param_name, if_none=None): + return self.request_params.get(param_name, if_none) def add_tags_to_certificate(self): arn = self._get_param("CertificateArn") @@ -205,9 +205,6 @@ class AWSCertificateManagerResponse(BaseResponse): def request_certificate(self): domain_name = self._get_param("DomainName") - domain_validation_options = self._get_param( - "DomainValidationOptions" - ) # is ignored atm idempotency_token = self._get_param("IdempotencyToken") subject_alt_names = self._get_param("SubjectAlternativeNames") tags = self._get_param("Tags") # Optional @@ -225,7 +222,6 @@ class AWSCertificateManagerResponse(BaseResponse): try: arn = self.acm_backend.request_certificate( domain_name, - domain_validation_options, idempotency_token, subject_alt_names, tags, diff --git a/moto/apigateway/exceptions.py b/moto/apigateway/exceptions.py index 8f3faa011..735492242 100644 --- a/moto/apigateway/exceptions.py +++ b/moto/apigateway/exceptions.py @@ -85,7 +85,7 @@ class NoIntegrationDefined(NotFoundException): class NoIntegrationResponseDefined(NotFoundException): code = 404 - def __init__(self, code=None): + def __init__(self): super().__init__("Invalid Response status code specified") diff --git a/moto/apigateway/integration_parsers/__init__.py b/moto/apigateway/integration_parsers/__init__.py index e69de29bb..f9fa1db79 100644 --- a/moto/apigateway/integration_parsers/__init__.py +++ b/moto/apigateway/integration_parsers/__init__.py @@ -0,0 +1,7 @@ +import abc + + +class IntegrationParser: + @abc.abstractmethod + def invoke(self, request, integration): + pass diff --git a/moto/apigateway/integration_parsers/aws_parser.py b/moto/apigateway/integration_parsers/aws_parser.py index 37f5e963e..2aa644197 100644 --- a/moto/apigateway/integration_parsers/aws_parser.py +++ b/moto/apigateway/integration_parsers/aws_parser.py @@ -1,7 +1,9 @@ import requests +from . import IntegrationParser -class TypeAwsParser: + +class TypeAwsParser(IntegrationParser): def invoke(self, request, integration): # integration.uri = arn:aws:apigateway:{region}:{subdomain.service|service}:path|action/{service_api} # example value = 'arn:aws:apigateway:us-west-2:dynamodb:action/PutItem' diff --git a/moto/apigateway/integration_parsers/http_parser.py b/moto/apigateway/integration_parsers/http_parser.py index 1c25a6792..574558465 100644 --- a/moto/apigateway/integration_parsers/http_parser.py +++ b/moto/apigateway/integration_parsers/http_parser.py @@ -1,7 +1,9 @@ import requests +from . import IntegrationParser -class TypeHttpParser: + +class TypeHttpParser(IntegrationParser): """ Parse invocations to a APIGateway resource with integration type HTTP """ diff --git a/moto/apigateway/integration_parsers/unknown_parser.py b/moto/apigateway/integration_parsers/unknown_parser.py index d9d60f412..c008daff2 100644 --- a/moto/apigateway/integration_parsers/unknown_parser.py +++ b/moto/apigateway/integration_parsers/unknown_parser.py @@ -1,4 +1,7 @@ -class TypeUnknownParser: +from . import IntegrationParser + + +class TypeUnknownParser(IntegrationParser): """ Parse invocations to a APIGateway resource with an unknown integration type """ diff --git a/moto/apigateway/models.py b/moto/apigateway/models.py index fe232d362..7525b2291 100644 --- a/moto/apigateway/models.py +++ b/moto/apigateway/models.py @@ -152,7 +152,7 @@ class Integration(BaseModel, dict): def get_integration_response(self, status_code): result = self.get("integrationResponses", {}).get(status_code) if not result: - raise NoIntegrationResponseDefined(status_code) + raise NoIntegrationResponseDefined() return result def delete_integration_response(self, status_code): @@ -597,7 +597,7 @@ class ApiKey(BaseModel, dict): name=None, description=None, enabled=False, - generateDistinctId=False, + generateDistinctId=False, # pylint: disable=unused-argument value=None, stageKeys=None, tags=None, @@ -605,10 +605,8 @@ class ApiKey(BaseModel, dict): ): super().__init__() self["id"] = create_id() - self["value"] = ( - value - if value - else "".join(random.sample(string.ascii_letters + string.digits, 40)) + self["value"] = value or "".join( + random.sample(string.ascii_letters + string.digits, 40) ) self["name"] = name self["customerId"] = customerId @@ -846,8 +844,8 @@ class RestAPI(CloudFormationModel): self.description = "" @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["RootResourceId"] + def has_cfn_attr(cls, attr): + return attr in ["RootResourceId"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException diff --git a/moto/apigatewayv2/models.py b/moto/apigatewayv2/models.py index 031473d60..46222bad9 100644 --- a/moto/apigatewayv2/models.py +++ b/moto/apigatewayv2/models.py @@ -996,16 +996,13 @@ class ApiGatewayV2Backend(BaseBackend): self, api_key_selection_expression, cors_configuration, - credentials_arn, description, disable_schema_validation, disable_execute_api_endpoint, name, protocol_type, - route_key, route_selection_expression, tags, - target, version, ): """ diff --git a/moto/apigatewayv2/responses.py b/moto/apigatewayv2/responses.py index f027da260..e15fa4010 100644 --- a/moto/apigatewayv2/responses.py +++ b/moto/apigatewayv2/responses.py @@ -206,16 +206,13 @@ class ApiGatewayV2Response(BaseResponse): api_key_selection_expression = params.get("apiKeySelectionExpression") cors_configuration = params.get("corsConfiguration") - credentials_arn = params.get("credentialsArn") description = params.get("description") disable_schema_validation = params.get("disableSchemaValidation") disable_execute_api_endpoint = params.get("disableExecuteApiEndpoint") name = params.get("name") protocol_type = params.get("protocolType") - route_key = params.get("routeKey") route_selection_expression = params.get("routeSelectionExpression") tags = params.get("tags") - target = params.get("target") version = params.get("version") if protocol_type not in ["HTTP", "WEBSOCKET"]: @@ -224,16 +221,13 @@ class ApiGatewayV2Response(BaseResponse): api = self.apigatewayv2_backend.create_api( api_key_selection_expression=api_key_selection_expression, cors_configuration=cors_configuration, - credentials_arn=credentials_arn, description=description, disable_schema_validation=disable_schema_validation, disable_execute_api_endpoint=disable_execute_api_endpoint, name=name, protocol_type=protocol_type, - route_key=route_key, route_selection_expression=route_selection_expression, tags=tags, - target=target, version=version, ) return 200, {}, json.dumps(api.to_json()) diff --git a/moto/autoscaling/models.py b/moto/autoscaling/models.py index ec1653499..c9e6f9674 100644 --- a/moto/autoscaling/models.py +++ b/moto/autoscaling/models.py @@ -521,11 +521,8 @@ class FakeAutoScalingGroup(CloudFormationModel): launch_config_name, launch_template, vpc_zone_identifier, - default_cooldown, health_check_period, health_check_type, - placement_group, - termination_policies, new_instances_protected_from_scale_in=None, ): self._set_azs_and_vpcs(availability_zones, vpc_zone_identifier, update=True) @@ -808,13 +805,13 @@ class AutoScalingBackend(BaseBackend): launch_config_name, launch_template, vpc_zone_identifier, - default_cooldown, health_check_period, health_check_type, - placement_group, - termination_policies, new_instances_protected_from_scale_in=None, ): + """ + The parameter DefaultCooldown, PlacementGroup, TerminationPolicies are not yet implemented + """ # TODO: Add MixedInstancesPolicy once implemented. # Verify only a single launch config-like parameter is provided. if launch_config_name and launch_template: @@ -832,11 +829,8 @@ class AutoScalingBackend(BaseBackend): launch_config_name=launch_config_name, launch_template=launch_template, vpc_zone_identifier=vpc_zone_identifier, - default_cooldown=default_cooldown, health_check_period=health_check_period, health_check_type=health_check_type, - placement_group=placement_group, - termination_policies=termination_policies, new_instances_protected_from_scale_in=new_instances_protected_from_scale_in, ) return group @@ -888,9 +882,10 @@ class AutoScalingBackend(BaseBackend): self.update_attached_elbs(group.name) self.update_attached_target_groups(group.name) - def set_instance_health( - self, instance_id, health_status, should_respect_grace_period - ): + def set_instance_health(self, instance_id, health_status): + """ + The ShouldRespectGracePeriod-parameter is not yet implemented + """ instance = self.ec2_backend.get_instance(instance_id) instance_state = next( instance_state diff --git a/moto/autoscaling/responses.py b/moto/autoscaling/responses.py index 88a60c28c..0ec7857e1 100644 --- a/moto/autoscaling/responses.py +++ b/moto/autoscaling/responses.py @@ -114,10 +114,7 @@ class AutoScalingResponse(BaseResponse): health_status = self._get_param("HealthStatus") if health_status not in ["Healthy", "Unhealthy"]: raise ValueError("Valid instance health states are: [Healthy, Unhealthy]") - should_respect_grace_period = self._get_param("ShouldRespectGracePeriod") - self.autoscaling_backend.set_instance_health( - instance_id, health_status, should_respect_grace_period - ) + self.autoscaling_backend.set_instance_health(instance_id, health_status) template = self.response_template(SET_INSTANCE_HEALTH_TEMPLATE) return template.render() @@ -200,11 +197,8 @@ class AutoScalingResponse(BaseResponse): launch_config_name=self._get_param("LaunchConfigurationName"), launch_template=self._get_dict_param("LaunchTemplate."), vpc_zone_identifier=self._get_param("VPCZoneIdentifier"), - default_cooldown=self._get_int_param("DefaultCooldown"), health_check_period=self._get_int_param("HealthCheckGracePeriod"), health_check_type=self._get_param("HealthCheckType"), - placement_group=self._get_param("PlacementGroup"), - termination_policies=self._get_multi_param("TerminationPolicies.member"), new_instances_protected_from_scale_in=self._get_bool_param( "NewInstancesProtectedFromScaleIn", None ), diff --git a/moto/awslambda/models.py b/moto/awslambda/models.py index 7df771d04..8ee60f81c 100644 --- a/moto/awslambda/models.py +++ b/moto/awslambda/models.py @@ -312,7 +312,7 @@ class Layer(object): class LambdaFunction(CloudFormationModel, DockerModel): - def __init__(self, spec, region, validate_s3=True, version=1): + def __init__(self, spec, region, version=1): DockerModel.__init__(self) # required self.region = region @@ -547,14 +547,12 @@ class LambdaFunction(CloudFormationModel, DockerModel): except Exception: return s - def _invoke_lambda(self, code, event=None, context=None): + def _invoke_lambda(self, event=None): # Create the LogGroup if necessary, to write the result to self.logs_backend.ensure_log_group(self.logs_group_name, []) # TODO: context not yet implemented if event is None: event = dict() - if context is None: - context = {} output = None try: @@ -670,7 +668,7 @@ class LambdaFunction(CloudFormationModel, DockerModel): for line in output.splitlines() ] self.logs_backend.put_log_events( - self.logs_group_name, log_stream_name, log_events, None + self.logs_group_name, log_stream_name, log_events ) def invoke(self, body, request_headers, response_headers): @@ -681,7 +679,7 @@ class LambdaFunction(CloudFormationModel, DockerModel): body = "{}" # Get the invocation type: - res, errored, logs = self._invoke_lambda(code=self.code, event=body) + res, errored, logs = self._invoke_lambda(event=body) inv_type = request_headers.get("x-amz-invocation-type", "RequestResponse") if inv_type == "RequestResponse": encoded = base64.b64encode(logs.encode("utf-8")) @@ -746,8 +744,8 @@ class LambdaFunction(CloudFormationModel, DockerModel): return fn @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -758,7 +756,7 @@ class LambdaFunction(CloudFormationModel, DockerModel): @classmethod def update_from_cloudformation_json( - cls, new_resource_name, cloudformation_json, original_resource, region_name + cls, original_resource, new_resource_name, cloudformation_json, region_name ): updated_props = cloudformation_json["Properties"] original_resource.update_configuration(updated_props) @@ -879,7 +877,7 @@ class EventSourceMapping(CloudFormationModel): @classmethod def update_from_cloudformation_json( - cls, new_resource_name, cloudformation_json, original_resource, region_name + cls, original_resource, new_resource_name, cloudformation_json, region_name ): properties = cloudformation_json["Properties"] event_source_uuid = original_resource.uuid diff --git a/moto/awslambda/responses.py b/moto/awslambda/responses.py index 695260117..2ea3670a1 100644 --- a/moto/awslambda/responses.py +++ b/moto/awslambda/responses.py @@ -1,10 +1,7 @@ import json import sys -try: - from urllib import unquote -except ImportError: - from urllib.parse import unquote +from urllib.parse import unquote from functools import wraps from moto.core.utils import amz_crc32, amzn_request_id, path_url @@ -46,9 +43,9 @@ class LambdaResponse(BaseResponse): def root(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "GET": - return self._list_functions(request, full_url, headers) + return self._list_functions() elif request.method == "POST": - return self._create_function(request, full_url, headers) + return self._create_function() else: raise ValueError("Cannot handle request") @@ -60,7 +57,7 @@ class LambdaResponse(BaseResponse): function_name = querystring.get("FunctionName", [None])[0] return self._list_event_source_mappings(event_source_arn, function_name) elif request.method == "POST": - return self._create_event_source_mapping(request, full_url, headers) + return self._create_event_source_mapping() else: raise ValueError("Cannot handle request") @@ -80,21 +77,21 @@ class LambdaResponse(BaseResponse): def list_layers(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "GET": - return self._list_layers(request, headers) + return self._list_layers() def layers_versions(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "GET": - return self._get_layer_versions(request, full_url, headers) + return self._get_layer_versions() if request.method == "POST": - return self._publish_layer_version(request, full_url, headers) + return self._publish_layer_version() def function(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "GET": - return self._get_function(request, full_url, headers) + return self._get_function() elif request.method == "DELETE": - return self._delete_function(request, full_url, headers) + return self._delete_function() else: raise ValueError("Cannot handle request") @@ -108,7 +105,7 @@ class LambdaResponse(BaseResponse): return self._list_versions_by_function(function_name) elif request.method == "POST": - return self._publish_function(request, full_url, headers) + return self._publish_function() else: raise ValueError("Cannot handle request") @@ -117,7 +114,7 @@ class LambdaResponse(BaseResponse): def invoke(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "POST": - return self._invoke(request, full_url) + return self._invoke(request) else: raise ValueError("Cannot handle request") @@ -126,18 +123,18 @@ class LambdaResponse(BaseResponse): def invoke_async(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "POST": - return self._invoke_async(request, full_url) + return self._invoke_async() else: raise ValueError("Cannot handle request") def tag(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "GET": - return self._list_tags(request, full_url) + return self._list_tags() elif request.method == "POST": - return self._tag_resource(request, full_url) + return self._tag_resource() elif request.method == "DELETE": - return self._untag_resource(request, full_url) + return self._untag_resource() else: raise ValueError("Cannot handle {0} request".format(request.method)) @@ -145,20 +142,20 @@ class LambdaResponse(BaseResponse): def policy(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "GET": - return self._get_policy(request, full_url, headers) + return self._get_policy(request) elif request.method == "POST": - return self._add_policy(request, full_url, headers) + return self._add_policy(request) elif request.method == "DELETE": - return self._del_policy(request, full_url, headers, self.querystring) + return self._del_policy(request, self.querystring) else: raise ValueError("Cannot handle {0} request".format(request.method)) def configuration(self, request, full_url, headers): self.setup_class(request, full_url, headers) if request.method == "PUT": - return self._put_configuration(request) + return self._put_configuration() if request.method == "GET": - return self._get_function_configuration(request, full_url, headers) + return self._get_function_configuration() else: raise ValueError("Cannot handle request") @@ -179,15 +176,15 @@ class LambdaResponse(BaseResponse): self.setup_class(request, full_url, headers) if http_method == "GET": - return self._get_function_concurrency(request) + return self._get_function_concurrency() elif http_method == "DELETE": - return self._delete_function_concurrency(request) + return self._delete_function_concurrency() elif http_method == "PUT": - return self._put_function_concurrency(request) + return self._put_function_concurrency() else: raise ValueError("Cannot handle request") - def _add_policy(self, request, full_url, headers): + def _add_policy(self, request): path = request.path if hasattr(request, "path") else path_url(request.url) function_name = unquote(path.split("/")[-2]) if self.lambda_backend.get_function(function_name): @@ -197,7 +194,7 @@ class LambdaResponse(BaseResponse): else: return 404, {}, "{}" - def _get_policy(self, request, full_url, headers): + def _get_policy(self, request): path = request.path if hasattr(request, "path") else path_url(request.url) function_name = unquote(path.split("/")[-2]) if self.lambda_backend.get_function(function_name): @@ -206,7 +203,7 @@ class LambdaResponse(BaseResponse): else: return 404, {}, "{}" - def _del_policy(self, request, full_url, headers, querystring): + def _del_policy(self, request, querystring): path = request.path if hasattr(request, "path") else path_url(request.url) function_name = unquote(path.split("/")[-3]) statement_id = path.split("/")[-1].split("?")[0] @@ -217,7 +214,7 @@ class LambdaResponse(BaseResponse): else: return 404, {}, "{}" - def _invoke(self, request, full_url): + def _invoke(self, request): response_headers = {} # URL Decode in case it's a ARN: @@ -251,7 +248,7 @@ class LambdaResponse(BaseResponse): else: return 404, response_headers, "{}" - def _invoke_async(self, request, full_url): + def _invoke_async(self): response_headers = {} function_name = unquote(self.path.rsplit("/", 3)[-3]) @@ -264,7 +261,7 @@ class LambdaResponse(BaseResponse): else: return 404, response_headers, "{}" - def _list_functions(self, request, full_url, headers): + def _list_functions(self): querystring = self.querystring func_version = querystring.get("FunctionVersion", [None])[0] result = {"Functions": []} @@ -286,12 +283,12 @@ class LambdaResponse(BaseResponse): return 200, {}, json.dumps(result) - def _create_function(self, request, full_url, headers): + def _create_function(self): fn = self.lambda_backend.create_function(self.json_body) config = fn.get_configuration() return 201, {}, json.dumps(config) - def _create_event_source_mapping(self, request, full_url, headers): + def _create_event_source_mapping(self): fn = self.lambda_backend.create_event_source_mapping(self.json_body) config = fn.get_configuration() return 201, {}, json.dumps(config) @@ -326,7 +323,7 @@ class LambdaResponse(BaseResponse): else: return 404, {}, "{}" - def _publish_function(self, request, full_url, headers): + def _publish_function(self): function_name = self.path.rsplit("/", 2)[-2] description = self._get_param("Description") @@ -337,7 +334,7 @@ class LambdaResponse(BaseResponse): else: return 404, {}, "{}" - def _delete_function(self, request, full_url, headers): + def _delete_function(self): function_name = unquote(self.path.rsplit("/", 1)[-1]) qualifier = self._get_param("Qualifier", None) @@ -354,7 +351,7 @@ class LambdaResponse(BaseResponse): configuration["FunctionArn"] += ":$LATEST" return configuration - def _get_function(self, request, full_url, headers): + def _get_function(self): function_name = unquote(self.path.rsplit("/", 1)[-1]) qualifier = self._get_param("Qualifier", None) @@ -369,7 +366,7 @@ class LambdaResponse(BaseResponse): else: return 404, {"x-amzn-ErrorType": "ResourceNotFoundException"}, "{}" - def _get_function_configuration(self, request, full_url, headers): + def _get_function_configuration(self): function_name = unquote(self.path.rsplit("/", 2)[-2]) qualifier = self._get_param("Qualifier", None) @@ -390,7 +387,7 @@ class LambdaResponse(BaseResponse): else: return self.default_region - def _list_tags(self, request, full_url): + def _list_tags(self): function_arn = unquote(self.path.rsplit("/", 1)[-1]) fn = self.lambda_backend.get_function_by_arn(function_arn) @@ -399,7 +396,7 @@ class LambdaResponse(BaseResponse): else: return 404, {}, "{}" - def _tag_resource(self, request, full_url): + def _tag_resource(self): function_arn = unquote(self.path.rsplit("/", 1)[-1]) if self.lambda_backend.tag_resource(function_arn, self.json_body["Tags"]): @@ -407,7 +404,7 @@ class LambdaResponse(BaseResponse): else: return 404, {}, "{}" - def _untag_resource(self, request, full_url): + def _untag_resource(self): function_arn = unquote(self.path.rsplit("/", 1)[-1]) tag_keys = self.querystring["tagKeys"] @@ -416,7 +413,7 @@ class LambdaResponse(BaseResponse): else: return 404, {}, "{}" - def _put_configuration(self, request): + def _put_configuration(self): function_name = unquote(self.path.rsplit("/", 2)[-2]) qualifier = self._get_param("Qualifier", None) resp = self.lambda_backend.update_function_configuration( @@ -445,7 +442,7 @@ class LambdaResponse(BaseResponse): resp = self.lambda_backend.get_code_signing_config(function_name) return 200, {}, json.dumps(resp) - def _get_function_concurrency(self, request): + def _get_function_concurrency(self): path_function_name = unquote(self.path.rsplit("/", 2)[-2]) function_name = self.lambda_backend.get_function(path_function_name) @@ -455,7 +452,7 @@ class LambdaResponse(BaseResponse): resp = self.lambda_backend.get_function_concurrency(path_function_name) return 200, {}, json.dumps({"ReservedConcurrentExecutions": resp}) - def _delete_function_concurrency(self, request): + def _delete_function_concurrency(self): path_function_name = unquote(self.path.rsplit("/", 2)[-2]) function_name = self.lambda_backend.get_function(path_function_name) @@ -466,7 +463,7 @@ class LambdaResponse(BaseResponse): return 204, {}, "{}" - def _put_function_concurrency(self, request): + def _put_function_concurrency(self): path_function_name = unquote(self.path.rsplit("/", 2)[-2]) function = self.lambda_backend.get_function(path_function_name) @@ -480,11 +477,11 @@ class LambdaResponse(BaseResponse): return 200, {}, json.dumps({"ReservedConcurrentExecutions": resp}) - def _list_layers(self, request, headers): + def _list_layers(self): layers = self.lambda_backend.list_layers() - return (200, {}, json.dumps({"Layers": layers})) + return 200, {}, json.dumps({"Layers": layers}) - def _get_layer_versions(self, request, full_url, headers): + def _get_layer_versions(self): layer_name = self.path.rsplit("/", 2)[-2] layer_versions = self.lambda_backend.get_layer_versions(layer_name) return ( @@ -495,7 +492,7 @@ class LambdaResponse(BaseResponse): ), ) - def _publish_layer_version(self, request, full_url, headers): + def _publish_layer_version(self): spec = self.json_body if "LayerName" not in spec: spec["LayerName"] = self.path.rsplit("/", 2)[-2] diff --git a/moto/batch/models.py b/moto/batch/models.py index 6f002ff7e..ff2736e30 100644 --- a/moto/batch/models.py +++ b/moto/batch/models.py @@ -703,7 +703,7 @@ class Job(threading.Thread, BaseModel, DockerModel): self.log_stream_name = stream_name self._log_backend.ensure_log_group(log_group, None) self._log_backend.create_log_stream(log_group, stream_name) - self._log_backend.put_log_events(log_group, stream_name, logs, None) + self._log_backend.put_log_events(log_group, stream_name, logs) result = container.wait() or {} self.exit_code = result.get("StatusCode", 0) @@ -961,9 +961,10 @@ class BatchBackend(BaseBackend): except KeyError: return None - def describe_compute_environments( - self, environments=None, max_results=None, next_token=None - ): + def describe_compute_environments(self, environments=None): + """ + Pagination is not yet implemented + """ envs = set() if environments is not None: envs = set(environments) @@ -1329,7 +1330,10 @@ class BatchBackend(BaseBackend): return queue_name, queue.arn - def describe_job_queues(self, job_queues=None, max_results=None, next_token=None): + def describe_job_queues(self, job_queues=None): + """ + Pagination is not yet implemented + """ envs = set() if job_queues is not None: envs = set(job_queues) @@ -1465,13 +1469,11 @@ class BatchBackend(BaseBackend): self._job_definitions[job_def.arn].deregister() def describe_job_definitions( - self, - job_def_name=None, - job_def_list=None, - status=None, - max_results=None, - next_token=None, + self, job_def_name=None, job_def_list=None, status=None ): + """ + Pagination is not yet implemented + """ jobs = [] # As a job name can reference multiple revisions, we get a list of them @@ -1499,14 +1501,13 @@ class BatchBackend(BaseBackend): job_name, job_def_id, job_queue, - parameters=None, - retries=None, depends_on=None, container_overrides=None, timeout=None, ): - # TODO parameters, retries (which is a dict raw from request), job dependencies and container overrides are ignored for now - + """ + Parameters RetryStrategy and Parameters are not yet implemented. + """ # Look for job definition job_def = self.get_job_definition(job_def_id) if job_def is None: @@ -1549,7 +1550,10 @@ class BatchBackend(BaseBackend): return result - def list_jobs(self, job_queue, job_status=None, max_results=None, next_token=None): + def list_jobs(self, job_queue, job_status=None): + """ + Pagination is not yet implemented + """ jobs = [] job_queue = self.get_job_queue(job_queue) diff --git a/moto/batch/responses.py b/moto/batch/responses.py index 5fd126837..6431dda0c 100644 --- a/moto/batch/responses.py +++ b/moto/batch/responses.py @@ -66,12 +66,8 @@ class BatchResponse(BaseResponse): # DescribeComputeEnvironments def describecomputeenvironments(self): compute_environments = self._get_param("computeEnvironments") - max_results = self._get_param("maxResults") # Ignored, should be int - next_token = self._get_param("nextToken") # Ignored - envs = self.batch_backend.describe_compute_environments( - compute_environments, max_results=max_results, next_token=next_token - ) + envs = self.batch_backend.describe_compute_environments(compute_environments) result = {"computeEnvironments": envs} return json.dumps(result) @@ -134,12 +130,8 @@ class BatchResponse(BaseResponse): # DescribeJobQueues def describejobqueues(self): job_queues = self._get_param("jobQueues") - max_results = self._get_param("maxResults") # Ignored, should be int - next_token = self._get_param("nextToken") # Ignored - queues = self.batch_backend.describe_job_queues( - job_queues, max_results=max_results, next_token=next_token - ) + queues = self.batch_backend.describe_job_queues(job_queues) result = {"jobQueues": queues} return json.dumps(result) @@ -219,12 +211,10 @@ class BatchResponse(BaseResponse): def describejobdefinitions(self): job_def_name = self._get_param("jobDefinitionName") job_def_list = self._get_param("jobDefinitions") - max_results = self._get_param("maxResults") - next_token = self._get_param("nextToken") status = self._get_param("status") job_defs = self.batch_backend.describe_job_definitions( - job_def_name, job_def_list, status, max_results, next_token + job_def_name, job_def_list, status ) result = {"jobDefinitions": [job.describe() for job in job_defs]} @@ -237,8 +227,6 @@ class BatchResponse(BaseResponse): job_def = self._get_param("jobDefinition") job_name = self._get_param("jobName") job_queue = self._get_param("jobQueue") - parameters = self._get_param("parameters") - retries = self._get_param("retryStrategy") timeout = self._get_param("timeout") try: @@ -246,8 +234,6 @@ class BatchResponse(BaseResponse): job_name, job_def, job_queue, - parameters=parameters, - retries=retries, depends_on=depends_on, container_overrides=container_overrides, timeout=timeout, @@ -272,13 +258,9 @@ class BatchResponse(BaseResponse): def listjobs(self): job_queue = self._get_param("jobQueue") job_status = self._get_param("jobStatus") - max_results = self._get_param("maxResults") - next_token = self._get_param("nextToken") try: - jobs = self.batch_backend.list_jobs( - job_queue, job_status, max_results, next_token - ) + jobs = self.batch_backend.list_jobs(job_queue, job_status) except AWSError as err: return err.response() diff --git a/moto/cloudformation/custom_model.py b/moto/cloudformation/custom_model.py index 841d7172c..8e650d504 100644 --- a/moto/cloudformation/custom_model.py +++ b/moto/cloudformation/custom_model.py @@ -85,7 +85,7 @@ class CustomModel(CloudFormationModel): return custom_resource @classmethod - def has_cfn_attr(cls, attribute): + def has_cfn_attr(cls, attr): # pylint: disable=unused-argument # We don't know which attributes are supported for third-party resources return True diff --git a/moto/cloudformation/models.py b/moto/cloudformation/models.py index 337766716..760949409 100644 --- a/moto/cloudformation/models.py +++ b/moto/cloudformation/models.py @@ -129,7 +129,7 @@ class FakeStackSet(BaseModel): if not parameters: parameters = self.parameters - self.instances.create_instances(accounts, regions, parameters, operation_id) + self.instances.create_instances(accounts, regions, parameters) self._create_operation( operation_id=operation_id, action="CREATE", @@ -176,7 +176,7 @@ class FakeStackInstances(BaseModel): self.stackset_name = stackset_name self.stack_instances = [] - def create_instances(self, accounts, regions, parameters, operation_id): + def create_instances(self, accounts, regions, parameters): new_instances = [] for region in regions: for account in accounts: @@ -524,6 +524,12 @@ class CloudFormationBackend(BaseBackend): self.deleted_stacks = {} self.exports = OrderedDict() self.change_sets = OrderedDict() + self.region = region + + def reset(self): + region = self.region + self.__dict__ = {} + self.__init__(region) @staticmethod def default_vpc_endpoint_service(service_region, zones): @@ -561,7 +567,6 @@ class CloudFormationBackend(BaseBackend): parameters, tags=None, description=None, - region="us-east-1", admin_role=None, execution_role=None, ): @@ -651,18 +656,17 @@ class CloudFormationBackend(BaseBackend): name, template, parameters, - region_name, notification_arns=None, tags=None, role_arn=None, ): - stack_id = generate_stack_id(name, region_name) + stack_id = generate_stack_id(name, self.region) new_stack = FakeStack( stack_id=stack_id, name=name, template=template, parameters=parameters, - region_name=region_name, + region_name=self.region, notification_arns=notification_arns, tags=tags, role_arn=role_arn, @@ -685,7 +689,6 @@ class CloudFormationBackend(BaseBackend): template, parameters, description, - region_name, change_set_type, notification_arns=None, tags=None, @@ -698,13 +701,13 @@ class CloudFormationBackend(BaseBackend): else: raise ValidationError(stack_name) else: - stack_id = generate_stack_id(stack_name, region_name) + stack_id = generate_stack_id(stack_name, self.region) stack = FakeStack( stack_id=stack_id, name=stack_name, template={}, parameters=parameters, - region_name=region_name, + region_name=self.region, notification_arns=notification_arns, tags=tags, role_arn=role_arn, @@ -715,7 +718,7 @@ class CloudFormationBackend(BaseBackend): "REVIEW_IN_PROGRESS", resource_status_reason="User Initiated" ) - change_set_id = generate_changeset_id(change_set_name, region_name) + change_set_id = generate_changeset_id(change_set_name, self.region) new_change_set = FakeChangeSet( change_set_type=change_set_type, @@ -734,7 +737,7 @@ class CloudFormationBackend(BaseBackend): self.change_sets[change_set_id] = new_change_set return change_set_id, stack.stack_id - def delete_change_set(self, change_set_name, stack_name=None): + def delete_change_set(self, change_set_name): if change_set_name in self.change_sets: # This means arn was passed in del self.change_sets[change_set_name] @@ -745,7 +748,7 @@ class CloudFormationBackend(BaseBackend): break del self.change_sets[to_delete] - def describe_change_set(self, change_set_name, stack_name=None): + def describe_change_set(self, change_set_name): change_set = None if change_set_name in self.change_sets: # This means arn was passed in diff --git a/moto/cloudformation/parsing.py b/moto/cloudformation/parsing.py index 735e3433d..8e359418c 100644 --- a/moto/cloudformation/parsing.py +++ b/moto/cloudformation/parsing.py @@ -534,7 +534,7 @@ class ResourceMap(collections_abc.Mapping): # The Value in SSM parameters is the SSM parameter path # we need to use ssm_backend to retrieve the # actual value from parameter store - parameter = ssm_backends[self._region_name].get_parameter(value, False) + parameter = ssm_backends[self._region_name].get_parameter(value) actual_value = parameter.value if value_type.find("List") > 0: return actual_value.split(",") diff --git a/moto/cloudformation/responses.py b/moto/cloudformation/responses.py index 3b3d5317c..d0139350d 100644 --- a/moto/cloudformation/responses.py +++ b/moto/cloudformation/responses.py @@ -44,7 +44,7 @@ class CloudFormationResponse(BaseResponse): return cloudformation_backends[self.region] @classmethod - def cfnresponse(cls, *args, **kwargs): + def cfnresponse(cls, *args, **kwargs): # pylint: disable=unused-argument request, full_url, headers = args full_url += "&Action=ProcessCfnResponse" return cls.dispatch(request=request, full_url=full_url, headers=headers) @@ -136,7 +136,6 @@ class CloudFormationResponse(BaseResponse): name=stack_name, template=stack_body, parameters=parameters, - region_name=self.region, notification_arns=stack_notification_arns, tags=tags, role_arn=role_arn, @@ -186,7 +185,6 @@ class CloudFormationResponse(BaseResponse): template=stack_body, parameters=parameters, description=description, - region_name=self.region, notification_arns=stack_notification_arns, tags=tags, role_arn=role_arn, @@ -208,12 +206,9 @@ class CloudFormationResponse(BaseResponse): return template.render(stack_id=stack_id, change_set_id=change_set_id) def delete_change_set(self): - stack_name = self._get_param("StackName") change_set_name = self._get_param("ChangeSetName") - self.cloudformation_backend.delete_change_set( - change_set_name=change_set_name, stack_name=stack_name - ) + self.cloudformation_backend.delete_change_set(change_set_name=change_set_name) if self.request_json: return json.dumps( {"DeleteChangeSetResponse": {"DeleteChangeSetResult": {}}} @@ -223,10 +218,9 @@ class CloudFormationResponse(BaseResponse): return template.render() def describe_change_set(self): - stack_name = self._get_param("StackName") change_set_name = self._get_param("ChangeSetName") change_set = self.cloudformation_backend.describe_change_set( - change_set_name=change_set_name, stack_name=stack_name + change_set_name=change_set_name ) template = self.response_template(DESCRIBE_CHANGE_SET_RESPONSE_TEMPLATE) return template.render(change_set=change_set) @@ -457,7 +451,6 @@ class CloudFormationResponse(BaseResponse): stackset_name = self._get_param("StackSetName") stack_body = self._get_param("TemplateBody") template_url = self._get_param("TemplateURL") - # role_arn = self._get_param('RoleARN') parameters_list = self._get_list_prefix("Parameters.member") tags = dict( (item["key"], item["value"]) @@ -475,11 +468,7 @@ class CloudFormationResponse(BaseResponse): stack_body = self._get_stack_from_s3_url(template_url) stackset = self.cloudformation_backend.create_stack_set( - name=stackset_name, - template=stack_body, - parameters=parameters, - tags=tags - # role_arn=role_arn + name=stackset_name, template=stack_body, parameters=parameters, tags=tags ) if self.request_json: return json.dumps( diff --git a/moto/codecommit/models.py b/moto/codecommit/models.py index 1c6575ca7..8f018a168 100644 --- a/moto/codecommit/models.py +++ b/moto/codecommit/models.py @@ -34,6 +34,12 @@ class CodeCommit(BaseModel): class CodeCommitBackend(BaseBackend): def __init__(self, region=None): self.repositories = {} + self.region = region + + def reset(self): + region = self.region + self.__dict__ = {} + self.__init__(region) @staticmethod def default_vpc_endpoint_service(service_region, zones): @@ -42,13 +48,13 @@ class CodeCommitBackend(BaseBackend): service_region, zones, "codecommit" ) - def create_repository(self, region, repository_name, repository_description): + def create_repository(self, repository_name, repository_description): repository = self.repositories.get(repository_name) if repository: raise RepositoryNameExistsException(repository_name) self.repositories[repository_name] = CodeCommit( - region, repository_description, repository_name + self.region, repository_description, repository_name ) return self.repositories[repository_name].repository_metadata diff --git a/moto/codecommit/responses.py b/moto/codecommit/responses.py index 3c6fdc5ea..5ccd77127 100644 --- a/moto/codecommit/responses.py +++ b/moto/codecommit/responses.py @@ -26,7 +26,6 @@ class CodeCommitResponse(BaseResponse): raise InvalidRepositoryNameException() repository_metadata = self.codecommit_backend.create_repository( - self.region, self._get_param("repositoryName"), self._get_param("repositoryDescription"), ) diff --git a/moto/codepipeline/models.py b/moto/codepipeline/models.py index 03477378a..90308bd7d 100644 --- a/moto/codepipeline/models.py +++ b/moto/codepipeline/models.py @@ -69,6 +69,12 @@ class CodePipeline(BaseModel): class CodePipelineBackend(BaseBackend): def __init__(self, region=None): self.pipelines = {} + self.region = region + + def reset(self): + region_name = self.region + self.__dict__ = {} + self.__init__(region_name) @staticmethod def default_vpc_endpoint_service(service_region, zones): @@ -81,7 +87,7 @@ class CodePipelineBackend(BaseBackend): def iam_backend(self): return iam_backends["global"] - def create_pipeline(self, region, pipeline, tags): + def create_pipeline(self, pipeline, tags): if pipeline["name"] in self.pipelines: raise InvalidStructureException( "A pipeline with the name '{0}' already exists in account '{1}'".format( @@ -108,7 +114,7 @@ class CodePipelineBackend(BaseBackend): "Pipeline has only 1 stage(s). There should be a minimum of 2 stages in a pipeline" ) - self.pipelines[pipeline["name"]] = CodePipeline(region, pipeline) + self.pipelines[pipeline["name"]] = CodePipeline(self.region, pipeline) if tags: self.pipelines[pipeline["name"]].validate_tags(tags) diff --git a/moto/codepipeline/responses.py b/moto/codepipeline/responses.py index 0223dfae6..d18c67602 100644 --- a/moto/codepipeline/responses.py +++ b/moto/codepipeline/responses.py @@ -11,7 +11,7 @@ class CodePipelineResponse(BaseResponse): def create_pipeline(self): pipeline, tags = self.codepipeline_backend.create_pipeline( - self.region, self._get_param("pipeline"), self._get_param("tags") + self._get_param("pipeline"), self._get_param("tags") ) return json.dumps({"pipeline": pipeline, "tags": tags}) diff --git a/moto/cognitoidentity/models.py b/moto/cognitoidentity/models.py index 6da4141e9..e0ca6fdcf 100644 --- a/moto/cognitoidentity/models.py +++ b/moto/cognitoidentity/models.py @@ -120,7 +120,6 @@ class CognitoIdentityBackend(BaseBackend): identity_pool_id, identity_pool_name, allow_unauthenticated, - allow_classic, login_providers, provider_name, provider_arns, @@ -128,6 +127,9 @@ class CognitoIdentityBackend(BaseBackend): saml_providers, tags=None, ): + """ + The AllowClassic-parameter has not yet been implemented + """ pool = self.identity_pools[identity_pool_id] pool.identity_pool_name = pool.identity_pool_name or identity_pool_name if allow_unauthenticated is not None: @@ -183,7 +185,10 @@ class CognitoIdentityBackend(BaseBackend): ) return response - def list_identities(self, identity_pool_id, max_results=123): + def list_identities(self, identity_pool_id): + """ + The MaxResults-parameter has not yet been implemented + """ response = json.dumps(self.pools_identities[identity_pool_id]) return response diff --git a/moto/cognitoidentity/responses.py b/moto/cognitoidentity/responses.py index 4bd454e27..51b16bfec 100644 --- a/moto/cognitoidentity/responses.py +++ b/moto/cognitoidentity/responses.py @@ -31,7 +31,6 @@ class CognitoIdentityResponse(BaseResponse): pool_id = self._get_param("IdentityPoolId") pool_name = self._get_param("IdentityPoolName") allow_unauthenticated = self._get_bool_param("AllowUnauthenticatedIdentities") - allow_classic = self._get_bool_param("AllowClassicFlow") login_providers = self._get_param("SupportedLoginProviders") provider_name = self._get_param("DeveloperProviderName") provider_arns = self._get_param("OpenIdConnectProviderARNs") @@ -43,7 +42,6 @@ class CognitoIdentityResponse(BaseResponse): identity_pool_id=pool_id, identity_pool_name=pool_name, allow_unauthenticated=allow_unauthenticated, - allow_classic=allow_classic, login_providers=login_providers, provider_name=provider_name, provider_arns=provider_arns, diff --git a/moto/cognitoidp/models.py b/moto/cognitoidp/models.py index 68d060b78..a8af41c40 100644 --- a/moto/cognitoidp/models.py +++ b/moto/cognitoidp/models.py @@ -1463,7 +1463,7 @@ class CognitoIdpBackend(BaseBackend): user_pool.users[user.username] = user return user - def confirm_sign_up(self, client_id, username, confirmation_code): + def confirm_sign_up(self, client_id, username): user_pool = None for p in self.user_pools.values(): if client_id in p.clients: @@ -1616,7 +1616,10 @@ class CognitoIdpBackend(BaseBackend): else: raise NotAuthorizedError(access_token) - def verify_software_token(self, access_token, user_code): + def verify_software_token(self, access_token): + """ + The parameter UserCode has not yet been implemented + """ for user_pool in self.user_pools.values(): if access_token in user_pool.access_tokens: _, username = user_pool.access_tokens[access_token] diff --git a/moto/cognitoidp/responses.py b/moto/cognitoidp/responses.py index d0f5688b7..22a33ab97 100644 --- a/moto/cognitoidp/responses.py +++ b/moto/cognitoidp/responses.py @@ -532,9 +532,8 @@ class CognitoIdpResponse(BaseResponse): def confirm_sign_up(self): client_id = self._get_param("ClientId") username = self._get_param("Username") - confirmation_code = self._get_param("ConfirmationCode") cognitoidp_backends[self.region].confirm_sign_up( - client_id=client_id, username=username, confirmation_code=confirmation_code + client_id=client_id, username=username ) return "" @@ -556,10 +555,7 @@ class CognitoIdpResponse(BaseResponse): def verify_software_token(self): access_token = self._get_param("AccessToken") - user_code = self._get_param("UserCode") - result = cognitoidp_backends[self.region].verify_software_token( - access_token, user_code - ) + result = cognitoidp_backends[self.region].verify_software_token(access_token) return json.dumps(result) def set_user_mfa_preference(self): @@ -607,5 +603,7 @@ class CognitoIdpJsonWebKeyResponse(BaseResponse): ) as f: self.json_web_key = f.read() - def serve_json_web_key(self, request, full_url, headers): + def serve_json_web_key( + self, request, full_url, headers + ): # pylint: disable=unused-argument return 200, {"Content-Type": "application/json"}, self.json_web_key diff --git a/moto/config/models.py b/moto/config/models.py index d89fa6c88..3a2b73750 100644 --- a/moto/config/models.py +++ b/moto/config/models.py @@ -855,6 +855,12 @@ class ConfigBackend(BaseBackend): self.organization_conformance_packs = {} self.config_rules = {} self.config_schema = None + self.region = region + + def reset(self): + region = self.region + self.__dict__ = {} + self.__init__(region) @staticmethod def default_vpc_endpoint_service(service_region, zones): @@ -896,7 +902,7 @@ class ConfigBackend(BaseBackend): self.config_schema.shapes["MaximumExecutionFrequency"]["enum"], ) - def put_configuration_aggregator(self, config_aggregator, region): + def put_configuration_aggregator(self, config_aggregator): # Validate the name: if len(config_aggregator["ConfigurationAggregatorName"]) > 256: raise NameTooLongException( @@ -967,7 +973,7 @@ class ConfigBackend(BaseBackend): ): aggregator = ConfigAggregator( config_aggregator["ConfigurationAggregatorName"], - region, + self.region, account_sources=account_sources, org_source=org_source, tags=tags, @@ -1037,7 +1043,7 @@ class ConfigBackend(BaseBackend): del self.config_aggregators[config_aggregator] def put_aggregation_authorization( - self, current_region, authorized_account, authorized_region, tags + self, authorized_account, authorized_region, tags ): # Tag validation: tags = validate_tags(tags or []) @@ -1047,7 +1053,7 @@ class ConfigBackend(BaseBackend): agg_auth = self.aggregation_authorizations.get(key) if not agg_auth: agg_auth = ConfigAggregationAuthorization( - current_region, authorized_account, authorized_region, tags=tags + self.region, authorized_account, authorized_region, tags=tags ) self.aggregation_authorizations[ "{}/{}".format(authorized_account, authorized_region) @@ -1617,7 +1623,6 @@ class ConfigBackend(BaseBackend): def put_organization_conformance_pack( self, - region, name, template_s3_uri, template_body, @@ -1649,7 +1654,7 @@ class ConfigBackend(BaseBackend): ) else: pack = OrganizationConformancePack( - region=region, + region=self.region, name=name, delivery_s3_bucket=delivery_s3_bucket, delivery_s3_key_prefix=delivery_s3_key_prefix, @@ -1818,7 +1823,7 @@ class ConfigBackend(BaseBackend): ] } - def put_config_rule(self, region, config_rule, tags=None): + def put_config_rule(self, config_rule, tags=None): """Add/Update config rule for evaluating resource compliance. TBD - Only the "accounting" of config rules are handled at the @@ -1869,14 +1874,14 @@ class ConfigBackend(BaseBackend): ) # Update the current rule. - rule.modify_fields(region, config_rule, tags) + rule.modify_fields(self.region, config_rule, tags) else: # Create a new ConfigRule if the limit hasn't been reached. if len(self.config_rules) == ConfigRule.MAX_RULES: raise MaxNumberOfConfigRulesExceededException( rule_name, ConfigRule.MAX_RULES ) - rule = ConfigRule(region, config_rule, tags) + rule = ConfigRule(self.region, config_rule, tags) self.config_rules[rule_name] = rule return "" diff --git a/moto/config/responses.py b/moto/config/responses.py index 55e68649e..8c226b3d9 100644 --- a/moto/config/responses.py +++ b/moto/config/responses.py @@ -16,7 +16,7 @@ class ConfigResponse(BaseResponse): def put_configuration_aggregator(self): aggregator = self.config_backend.put_configuration_aggregator( - json.loads(self.body), self.region + json.loads(self.body) ) schema = {"ConfigurationAggregator": aggregator} return json.dumps(schema) @@ -37,7 +37,6 @@ class ConfigResponse(BaseResponse): def put_aggregation_authorization(self): agg_auth = self.config_backend.put_aggregation_authorization( - self.region, self._get_param("AuthorizedAccountId"), self._get_param("AuthorizedAwsRegion"), self._get_param("Tags"), @@ -170,7 +169,6 @@ class ConfigResponse(BaseResponse): def put_organization_conformance_pack(self): conformance_pack = self.config_backend.put_organization_conformance_pack( - region=self.region, name=self._get_param("OrganizationConformancePackName"), template_s3_uri=self._get_param("TemplateS3Uri"), template_body=self._get_param("TemplateBody"), @@ -223,7 +221,7 @@ class ConfigResponse(BaseResponse): def put_config_rule(self): self.config_backend.put_config_rule( - self.region, self._get_param("ConfigRule"), self._get_param("Tags") + self._get_param("ConfigRule"), self._get_param("Tags") ) return "" diff --git a/moto/core/custom_responses_mock.py b/moto/core/custom_responses_mock.py index b3e901b46..c75ff33e0 100644 --- a/moto/core/custom_responses_mock.py +++ b/moto/core/custom_responses_mock.py @@ -86,7 +86,7 @@ class CallbackResponse(responses.CallbackResponse): return False -def not_implemented_callback(request): +def not_implemented_callback(request): # pylint: disable=unused-argument status = 400 headers = {} response = "The method is not implemented" diff --git a/moto/core/exceptions.py b/moto/core/exceptions.py index 52c7fc01f..ce490894b 100644 --- a/moto/core/exceptions.py +++ b/moto/core/exceptions.py @@ -64,13 +64,13 @@ class RESTError(HTTPException): ) self.content_type = "application/xml" - def get_headers(self, *args, **kwargs): + def get_headers(self, *args, **kwargs): # pylint: disable=unused-argument return { "X-Amzn-ErrorType": self.error_type or "UnknownError", "Content-Type": self.content_type, } - def get_body(self, *args, **kwargs): + def get_body(self, *args, **kwargs): # pylint: disable=unused-argument return self.description diff --git a/moto/core/models.py b/moto/core/models.py index a14737a3a..c0ae85eb9 100644 --- a/moto/core/models.py +++ b/moto/core/models.py @@ -242,7 +242,7 @@ class MockRawResponse(BytesIO): response_input = response_input.encode("utf-8") super().__init__(response_input) - def stream(self, **kwargs): + def stream(self, **kwargs): # pylint: disable=unused-argument contents = self.read() while contents: yield contents @@ -335,7 +335,7 @@ class BotocoreEventMockAWS(BaseMockAWS): botocore_stubber.reset() reset_responses_mock(responses_mock) - def enable_patching(self, reset=True): + def enable_patching(self, reset=True): # pylint: disable=unused-argument botocore_stubber.enabled = True for method in BOTOCORE_HTTP_METHODS: for backend in self.backends_for_urls.values(): @@ -482,7 +482,7 @@ class InstanceTrackerMeta(type): class BaseModel(metaclass=InstanceTrackerMeta): - def __new__(cls, *args, **kwargs): + def __new__(cls, *args, **kwargs): # pylint: disable=unused-argument instance = super(BaseModel, cls).__new__(cls) cls.instances.append(instance) return instance diff --git a/moto/core/responses.py b/moto/core/responses.py index 8d3326d1f..5144a8bb6 100644 --- a/moto/core/responses.py +++ b/moto/core/responses.py @@ -811,7 +811,9 @@ class BaseResponse(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): class MotoAPIResponse(BaseResponse): - def reset_response(self, request, full_url, headers): + def reset_response( + self, request, full_url, headers + ): # pylint: disable=unused-argument if request.method == "POST": from .models import moto_api_backend @@ -819,7 +821,9 @@ class MotoAPIResponse(BaseResponse): return 200, {}, json.dumps({"status": "ok"}) return 400, {}, json.dumps({"Error": "Need to POST to reset Moto"}) - def reset_auth_response(self, request, full_url, headers): + def reset_auth_response( + self, request, full_url, headers + ): # pylint: disable=unused-argument if request.method == "POST": previous_initial_no_auth_action_count = ( settings.INITIAL_NO_AUTH_ACTION_COUNT @@ -840,7 +844,7 @@ class MotoAPIResponse(BaseResponse): ) return 400, {}, json.dumps({"Error": "Need to POST to reset Moto Auth"}) - def model_data(self, request, full_url, headers): + def model_data(self, request, full_url, headers): # pylint: disable=unused-argument from moto.core.models import model_data results = {} @@ -863,7 +867,7 @@ class MotoAPIResponse(BaseResponse): results[service][name].append(inst_result) return 200, {"Content-Type": "application/javascript"}, json.dumps(results) - def dashboard(self, request, full_url, headers): + def dashboard(self, request, full_url, headers): # pylint: disable=unused-argument from flask import render_template return render_template("dashboard.html") diff --git a/moto/databrew/models.py b/moto/databrew/models.py index 92a3ff586..6f085669b 100644 --- a/moto/databrew/models.py +++ b/moto/databrew/models.py @@ -41,7 +41,10 @@ class DataBrewBackend(BaseBackend): def list_recipes(self): return [self.recipes[key] for key in self.recipes] if self.recipes else [] - def get_recipe(self, recipe_name, version): + def get_recipe(self, recipe_name): + """ + The Version-parameter has not yet been implemented + """ if recipe_name not in self.recipes: raise RecipeNotFoundException(recipe_name) return self.recipes[recipe_name] diff --git a/moto/databrew/responses.py b/moto/databrew/responses.py index ae83b982c..c16f6eb95 100644 --- a/moto/databrew/responses.py +++ b/moto/databrew/responses.py @@ -59,11 +59,7 @@ class DataBrewResponse(BaseResponse): recipe_name = parsed_url.path.rstrip("/").rsplit("/", 1)[1] try: - return json.dumps( - self.databrew_backend.get_recipe(recipe_name, None).as_dict() - ) + recipe = self.databrew_backend.get_recipe(recipe_name) + return json.dumps(recipe.as_dict()) except DataBrewClientError as e: return e.code, e.get_headers(), e.get_body() - - -# 'DescribeRecipe' diff --git a/moto/datapipeline/models.py b/moto/datapipeline/models.py index b6e5c9b3b..420a1b993 100644 --- a/moto/datapipeline/models.py +++ b/moto/datapipeline/models.py @@ -104,6 +104,7 @@ class Pipeline(CloudFormationModel): class DataPipelineBackend(BaseBackend): def __init__(self, region=None): self.pipelines = OrderedDict() + self.region = region def create_pipeline(self, name, unique_id, **kwargs): pipeline = Pipeline(name, unique_id, **kwargs) diff --git a/moto/dax/models.py b/moto/dax/models.py index 489d148a0..ee5f8ffbb 100644 --- a/moto/dax/models.py +++ b/moto/dax/models.py @@ -186,16 +186,9 @@ class DAXBackend(BaseBackend): node_type, description, replication_factor, - availability_zones, - subnet_group_name, - security_group_ids, - preferred_maintenance_window, - notification_topic_arn, iam_role_arn, - parameter_group_name, tags, sse_specification, - cluster_endpoint_encryption_type, ): """ The following parameters are not yet processed: @@ -247,9 +240,10 @@ class DAXBackend(BaseBackend): raise ClusterNotFoundFault() return self._tagger.list_tags_for_resource(self.clusters[name].arn) - def increase_replication_factor( - self, cluster_name, new_replication_factor, availability_zones - ): + def increase_replication_factor(self, cluster_name, new_replication_factor): + """ + The AvailabilityZones-parameter is not yet implemented + """ if cluster_name not in self.clusters: raise ClusterNotFoundFault() self.clusters[cluster_name].increase_replication_factor(new_replication_factor) @@ -259,7 +253,6 @@ class DAXBackend(BaseBackend): self, cluster_name, new_replication_factor, - availability_zones, node_ids_to_remove, ): """ diff --git a/moto/dax/responses.py b/moto/dax/responses.py index 14cf39b66..914071eaf 100644 --- a/moto/dax/responses.py +++ b/moto/dax/responses.py @@ -17,16 +17,9 @@ class DAXResponse(BaseResponse): node_type = params.get("NodeType") description = params.get("Description") replication_factor = params.get("ReplicationFactor") - availability_zones = params.get("AvailabilityZones") - subnet_group_name = params.get("SubnetGroupName") - security_group_ids = params.get("SecurityGroupIds") - preferred_maintenance_window = params.get("PreferredMaintenanceWindow") - notification_topic_arn = params.get("NotificationTopicArn") iam_role_arn = params.get("IamRoleArn") - parameter_group_name = params.get("ParameterGroupName") tags = params.get("Tags", []) sse_specification = params.get("SSESpecification", {}) - cluster_endpoint_encryption_type = params.get("ClusterEndpointEncryptionType") self._validate_arn(iam_role_arn) self._validate_name(cluster_name) @@ -36,16 +29,9 @@ class DAXResponse(BaseResponse): node_type=node_type, description=description, replication_factor=replication_factor, - availability_zones=availability_zones, - subnet_group_name=subnet_group_name, - security_group_ids=security_group_ids, - preferred_maintenance_window=preferred_maintenance_window, - notification_topic_arn=notification_topic_arn, iam_role_arn=iam_role_arn, - parameter_group_name=parameter_group_name, tags=tags, sse_specification=sse_specification, - cluster_endpoint_encryption_type=cluster_endpoint_encryption_type, ) return json.dumps(dict(Cluster=cluster.to_json())) @@ -106,11 +92,8 @@ class DAXResponse(BaseResponse): params = json.loads(self.body) cluster_name = params.get("ClusterName") new_replication_factor = params.get("NewReplicationFactor") - availability_zones = params.get("AvailabilityZones") cluster = self.dax_backend.increase_replication_factor( - cluster_name=cluster_name, - new_replication_factor=new_replication_factor, - availability_zones=availability_zones, + cluster_name=cluster_name, new_replication_factor=new_replication_factor ) return json.dumps({"Cluster": cluster.to_json()}) @@ -118,12 +101,10 @@ class DAXResponse(BaseResponse): params = json.loads(self.body) cluster_name = params.get("ClusterName") new_replication_factor = params.get("NewReplicationFactor") - availability_zones = params.get("AvailabilityZones") node_ids_to_remove = params.get("NodeIdsToRemove") cluster = self.dax_backend.decrease_replication_factor( cluster_name=cluster_name, new_replication_factor=new_replication_factor, - availability_zones=availability_zones, node_ids_to_remove=node_ids_to_remove, ) return json.dumps({"Cluster": cluster.to_json()}) diff --git a/moto/dms/models.py b/moto/dms/models.py index d7646b125..9b62bda02 100644 --- a/moto/dms/models.py +++ b/moto/dms/models.py @@ -39,13 +39,11 @@ class DatabaseMigrationServiceBackend(BaseBackend): migration_type, table_mappings, replication_task_settings, - cdc_start_time, - cdc_start_position, - cdc_stop_position, - tags, - task_data, - resource_identifier, ): + """ + The following parameters are not yet implemented: + CDCStartTime, CDCStartPosition, CDCStopPosition, Tags, TaskData, ResourceIdentifier + """ replication_task = FakeReplicationTask( replication_task_identifier=replication_task_identifier, source_endpoint_arn=source_endpoint_arn, @@ -66,14 +64,11 @@ class DatabaseMigrationServiceBackend(BaseBackend): return replication_task - def start_replication_task( - self, - replication_task_arn, - start_replication_task_type, - cdc_start_time, - cdc_start_position, - cdc_stop_position, - ): + def start_replication_task(self, replication_task_arn): + """ + The following parameters have not yet been implemented: + StartReplicationTaskType, CDCStartTime, CDCStartPosition, CDCStopPosition + """ if not self.replication_tasks.get(replication_task_arn): raise ResourceNotFoundFault("Replication task could not be found.") @@ -95,13 +90,16 @@ class DatabaseMigrationServiceBackend(BaseBackend): return task - def describe_replication_tasks(self, filters, max_records, without_settings): + def describe_replication_tasks(self, filters, max_records): + """ + The parameter WithoutSettings has not yet been implemented + """ replication_tasks = filter_tasks(self.replication_tasks.values(), filters) if max_records and max_records > 0: replication_tasks = replication_tasks[:max_records] - return None, replication_tasks + return replication_tasks class FakeReplicationTask(BaseModel): diff --git a/moto/dms/responses.py b/moto/dms/responses.py index 2ceafd6ce..cf671f4e1 100644 --- a/moto/dms/responses.py +++ b/moto/dms/responses.py @@ -10,8 +10,6 @@ class DatabaseMigrationServiceResponse(BaseResponse): def dms_backend(self): return dms_backends[self.region] - # add methods from here - def create_replication_task(self): replication_task_identifier = self._get_param("ReplicationTaskIdentifier") source_endpoint_arn = self._get_param("SourceEndpointArn") @@ -20,12 +18,6 @@ class DatabaseMigrationServiceResponse(BaseResponse): migration_type = self._get_param("MigrationType") table_mappings = self._get_param("TableMappings") replication_task_settings = self._get_param("ReplicationTaskSettings") - cdc_start_time = self._get_param("CdcStartTime") - cdc_start_position = self._get_param("CdcStartPosition") - cdc_stop_position = self._get_param("CdcStopPosition") - tags = self._get_list_prefix("Tags.member") - task_data = self._get_param("TaskData") - resource_identifier = self._get_param("ResourceIdentifier") replication_task = self.dms_backend.create_replication_task( replication_task_identifier=replication_task_identifier, source_endpoint_arn=source_endpoint_arn, @@ -34,34 +26,18 @@ class DatabaseMigrationServiceResponse(BaseResponse): migration_type=migration_type, table_mappings=table_mappings, replication_task_settings=replication_task_settings, - cdc_start_time=cdc_start_time, - cdc_start_position=cdc_start_position, - cdc_stop_position=cdc_stop_position, - tags=tags, - task_data=task_data, - resource_identifier=resource_identifier, ) return json.dumps({"ReplicationTask": replication_task.to_dict()}) def start_replication_task(self): replication_task_arn = self._get_param("ReplicationTaskArn") - start_replication_task_type = self._get_param("StartReplicationTaskType") - cdc_start_time = self._get_param("CdcStartTime") - cdc_start_position = self._get_param("CdcStartPosition") - cdc_stop_position = self._get_param("CdcStopPosition") replication_task = self.dms_backend.start_replication_task( - replication_task_arn=replication_task_arn, - start_replication_task_type=start_replication_task_type, - cdc_start_time=cdc_start_time, - cdc_start_position=cdc_start_position, - cdc_stop_position=cdc_stop_position, + replication_task_arn=replication_task_arn ) return json.dumps({"ReplicationTask": replication_task.to_dict()}) - # add templates from here - def stop_replication_task(self): replication_task_arn = self._get_param("ReplicationTaskArn") replication_task = self.dms_backend.stop_replication_task( @@ -81,14 +57,10 @@ class DatabaseMigrationServiceResponse(BaseResponse): def describe_replication_tasks(self): filters = self._get_list_prefix("Filters.member") max_records = self._get_int_param("MaxRecords") - marker = self._get_param("Marker") - without_settings = self._get_param("WithoutSettings") - marker, replication_tasks = self.dms_backend.describe_replication_tasks( - filters=filters, max_records=max_records, without_settings=without_settings + replication_tasks = self.dms_backend.describe_replication_tasks( + filters=filters, max_records=max_records ) return json.dumps( - dict( - marker=marker, ReplicationTasks=[t.to_dict() for t in replication_tasks] - ) + dict(ReplicationTasks=[t.to_dict() for t in replication_tasks]) ) diff --git a/moto/dynamodb/models/__init__.py b/moto/dynamodb/models/__init__.py index 10e3515ef..7b3efa247 100644 --- a/moto/dynamodb/models/__init__.py +++ b/moto/dynamodb/models/__init__.py @@ -35,9 +35,9 @@ from moto.dynamodb.limits import HASH_KEY_MAX_LENGTH, RANGE_KEY_MAX_LENGTH class DynamoJsonEncoder(json.JSONEncoder): - def default(self, obj): - if hasattr(obj, "to_json"): - return obj.to_json() + def default(self, o): + if hasattr(o, "to_json"): + return o.to_json() def dynamo_json_dump(dynamo_object): @@ -483,8 +483,8 @@ class Table(CloudFormationModel): return ebs_key.arn @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn", "StreamArn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn", "StreamArn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException diff --git a/moto/dynamodb/parsing/expressions.py b/moto/dynamodb/parsing/expressions.py index 5657ebf3b..98354438f 100644 --- a/moto/dynamodb/parsing/expressions.py +++ b/moto/dynamodb/parsing/expressions.py @@ -52,7 +52,7 @@ class NestableExpressionParserMixin(object): in the originating expression. """ - def __init__(self, *args, **kwargs): + def __init__(self): self.target_clauses = deque() def _parse_target_clause(self, factory_class): diff --git a/moto/dynamodb_v20111205/models.py b/moto/dynamodb_v20111205/models.py index 7c311d48e..deefb21dd 100644 --- a/moto/dynamodb_v20111205/models.py +++ b/moto/dynamodb_v20111205/models.py @@ -10,9 +10,9 @@ from .comparisons import get_comparison_func class DynamoJsonEncoder(json.JSONEncoder): - def default(self, obj): - if hasattr(obj, "to_json"): - return obj.to_json() + def default(self, o): + if hasattr(o, "to_json"): + return o.to_json() def dynamo_json_dump(dynamo_object): @@ -297,8 +297,8 @@ class Table(CloudFormationModel): return item @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["StreamArn"] + def has_cfn_attr(cls, attr): + return attr in ["StreamArn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException diff --git a/moto/ec2/exceptions.py b/moto/ec2/exceptions.py index 32c656457..42980a9d8 100644 --- a/moto/ec2/exceptions.py +++ b/moto/ec2/exceptions.py @@ -277,10 +277,9 @@ class MalformedAMIIdError(EC2ClientError): class InvalidSnapshotIdError(EC2ClientError): - def __init__(self, snapshot_id): - super().__init__( - "InvalidSnapshot.NotFound", "" - ) # Note: AWS returns empty message for this, as of 2014.08.22. + def __init__(self): + # Note: AWS returns empty message for this, as of 2014.08.22. + super().__init__("InvalidSnapshot.NotFound", "") class InvalidSnapshotInUse(EC2ClientError): diff --git a/moto/ec2/models.py b/moto/ec2/models.py index 6be5f6610..5d4deba45 100644 --- a/moto/ec2/models.py +++ b/moto/ec2/models.py @@ -439,8 +439,8 @@ class NetworkInterface(TaggedEC2Resource, CloudFormationModel): return self._group_set @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["PrimaryPrivateIpAddress", "SecondaryPrivateIpAddresses"] + def has_cfn_attr(cls, attr): + return attr in ["PrimaryPrivateIpAddress", "SecondaryPrivateIpAddresses"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -902,7 +902,7 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): def physical_resource_id(self): return self.id - def start(self, *args, **kwargs): + def start(self): for nic in self.nics.values(): nic.start() @@ -912,7 +912,7 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): self._reason = "" self._state_reason = StateReason() - def stop(self, *args, **kwargs): + def stop(self): for nic in self.nics.values(): nic.stop() @@ -927,10 +927,10 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): "Client.UserInitiatedShutdown", ) - def delete(self, region): + def delete(self, region): # pylint: disable=unused-argument self.terminate() - def terminate(self, *args, **kwargs): + def terminate(self): for nic in self.nics.values(): nic.stop() @@ -969,7 +969,7 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): ].id ) - def reboot(self, *args, **kwargs): + def reboot(self): self._state.name = "running" self._state.code = 16 @@ -1072,8 +1072,8 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): eni.device_index = None @classmethod - def has_cfn_attr(cls, attribute): - return attribute in [ + def has_cfn_attr(cls, attr): + return attr in [ "AvailabilityZone", "PrivateDnsName", "PublicDnsName", @@ -1734,7 +1734,6 @@ class AmiBackend(object): instance_id, name=None, description=None, - context=None, tag_specifications=None, ): # TODO: check that instance exists and pull info from it. @@ -1781,9 +1780,7 @@ class AmiBackend(object): self.amis[ami_id] = ami return ami - def describe_images( - self, ami_ids=(), filters=None, exec_users=None, owners=None, context=None - ): + def describe_images(self, ami_ids=(), filters=None, exec_users=None, owners=None): images = self.amis.copy().values() if len(ami_ids): @@ -2427,7 +2424,7 @@ class SecurityGroup(TaggedEC2Resource, CloudFormationModel): if security_group: security_group.delete(region_name) - def delete(self, region_name): + def delete(self, region_name): # pylint: disable=unused-argument """Not exposed as part of the ELB API - used for CloudFormation.""" self.ec2_backend.delete_security_group(group_id=self.id) @@ -2599,8 +2596,8 @@ class SecurityGroup(TaggedEC2Resource, CloudFormationModel): return True @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["GroupId"] + def has_cfn_attr(cls, attr): + return attr in ["GroupId"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -3606,8 +3603,7 @@ class EBSBackend(object): if snapshot_ids: matches = [snap for snap in matches if snap.id in snapshot_ids] if len(snapshot_ids) > len(matches): - unknown_ids = set(snapshot_ids) - set(matches) - raise InvalidSnapshotIdError(unknown_ids) + raise InvalidSnapshotIdError() if filters: matches = generic_filter(filters, matches) return matches @@ -3630,7 +3626,7 @@ class EBSBackend(object): def get_snapshot(self, snapshot_id): snapshot = self.snapshots.get(snapshot_id, None) if not snapshot: - raise InvalidSnapshotIdError(snapshot_id) + raise InvalidSnapshotIdError() return snapshot def delete_snapshot(self, snapshot_id): @@ -3639,7 +3635,7 @@ class EBSBackend(object): if snapshot.from_ami and snapshot.from_ami in self.amis: raise InvalidSnapshotInUse(snapshot_id, snapshot.from_ami) return self.snapshots.pop(snapshot_id) - raise InvalidSnapshotIdError(snapshot_id) + raise InvalidSnapshotIdError() def get_create_volume_permission_groups(self, snapshot_id): snapshot = self.get_snapshot(snapshot_id) @@ -4625,8 +4621,8 @@ class Subnet(TaggedEC2Resource, CloudFormationModel): return super().get_filter_value(filter_name, "DescribeSubnets") @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["AvailabilityZone"] + def has_cfn_attr(cls, attr): + return attr in ["AvailabilityZone"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -4713,7 +4709,6 @@ class SubnetBackend(object): ipv6_cidr_block=None, availability_zone=None, availability_zone_id=None, - context=None, tags=None, ): subnet_id = random_subnet_id() @@ -6032,7 +6027,7 @@ class EgressOnlyInternetGatewayBackend(object): self.egress_only_internet_gateway_backend[egress_only_igw.id] = egress_only_igw return egress_only_igw - def describe_egress_only_internet_gateways(self, ids=None, filters=None): + def describe_egress_only_internet_gateways(self, ids=None): """ The Filters-argument is not yet supported """ @@ -6659,8 +6654,8 @@ class ElasticAddress(TaggedEC2Resource, CloudFormationModel): return self.public_ip @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["AllocationId"] + def has_cfn_attr(cls, attr): + return attr in ["AllocationId"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -7997,7 +7992,7 @@ class TransitGatewayAttachmentBackend(object): return transit_gateway_vpc_attachment def describe_transit_gateway_attachments( - self, transit_gateways_attachment_ids=None, filters=None, max_results=0 + self, transit_gateways_attachment_ids=None, filters=None ): transit_gateway_attachments = list(self.transit_gateway_attachments.values()) @@ -8023,7 +8018,7 @@ class TransitGatewayAttachmentBackend(object): return result def describe_transit_gateway_vpc_attachments( - self, transit_gateways_attachment_ids=None, filters=None, max_results=0 + self, transit_gateways_attachment_ids=None, filters=None ): transit_gateway_attachments = list(self.transit_gateway_attachments.values()) @@ -8131,7 +8126,7 @@ class TransitGatewayAttachmentBackend(object): return transit_gateway_peering_attachment def describe_transit_gateway_peering_attachments( - self, transit_gateways_attachment_ids=None, filters=None, max_results=0 + self, transit_gateways_attachment_ids=None, filters=None ): transit_gateway_attachments = list(self.transit_gateway_attachments.values()) diff --git a/moto/ec2/responses/amis.py b/moto/ec2/responses/amis.py index 28c02ec8c..731d19b67 100644 --- a/moto/ec2/responses/amis.py +++ b/moto/ec2/responses/amis.py @@ -13,7 +13,6 @@ class AmisResponse(BaseResponse): instance_id, name, description, - context=self, tag_specifications=tag_specifications, ) template = self.response_template(CREATE_IMAGE_RESPONSE) @@ -45,11 +44,7 @@ class AmisResponse(BaseResponse): owners = self._get_multi_param("Owner") exec_users = self._get_multi_param("ExecutableBy") images = self.ec2_backend.describe_images( - ami_ids=ami_ids, - filters=filters, - exec_users=exec_users, - owners=owners, - context=self, + ami_ids=ami_ids, filters=filters, exec_users=exec_users, owners=owners ) template = self.response_template(DESCRIBE_IMAGES_RESPONSE) return template.render(images=images) diff --git a/moto/ec2/responses/egress_only_internet_gateways.py b/moto/ec2/responses/egress_only_internet_gateways.py index 44db5fc31..aec0dc1fe 100644 --- a/moto/ec2/responses/egress_only_internet_gateways.py +++ b/moto/ec2/responses/egress_only_internet_gateways.py @@ -1,5 +1,5 @@ from moto.core.responses import BaseResponse -from moto.ec2.utils import filters_from_querystring, add_tag_specification +from moto.ec2.utils import add_tag_specification class EgressOnlyInternetGateway(BaseResponse): @@ -16,9 +16,8 @@ class EgressOnlyInternetGateway(BaseResponse): def describe_egress_only_internet_gateways(self): egress_only_igw_ids = self._get_multi_param("EgressOnlyInternetGatewayId") - filters = filters_from_querystring(self.querystring) egress_only_igws = self.ec2_backend.describe_egress_only_internet_gateways( - egress_only_igw_ids, filters + egress_only_igw_ids ) template = self.response_template(DESCRIBE_EGRESS_ONLY_IGW_RESPONSE) return template.render(egress_only_igws=egress_only_igws) diff --git a/moto/ec2/responses/subnets.py b/moto/ec2/responses/subnets.py index e711014f5..168cad3ed 100644 --- a/moto/ec2/responses/subnets.py +++ b/moto/ec2/responses/subnets.py @@ -25,7 +25,6 @@ class Subnets(BaseResponse): ipv6_cidr_block, availability_zone, availability_zone_id, - context=self, tags=tags, ) template = self.response_template(CREATE_SUBNET_RESPONSE) diff --git a/moto/ec2/responses/transit_gateway_attachments.py b/moto/ec2/responses/transit_gateway_attachments.py index a176bf87e..b5bb1b4c7 100644 --- a/moto/ec2/responses/transit_gateway_attachments.py +++ b/moto/ec2/responses/transit_gateway_attachments.py @@ -31,12 +31,10 @@ class TransitGatewayAttachment(BaseResponse): "TransitGatewayAttachmentIds" ) filters = filters_from_querystring(self.querystring) - max_results = self._get_param("MaxResults") transit_gateway_vpc_attachments = ( self.ec2_backend.describe_transit_gateway_vpc_attachments( transit_gateways_attachment_ids=transit_gateways_attachment_ids, filters=filters, - max_results=max_results, ) ) template = self.response_template(DESCRIBE_TRANSIT_GATEWAY_VPC_ATTACHMENTS) @@ -66,12 +64,10 @@ class TransitGatewayAttachment(BaseResponse): "TransitGatewayAttachmentIds" ) filters = filters_from_querystring(self.querystring) - max_results = self._get_param("MaxResults") transit_gateway_attachments = ( self.ec2_backend.describe_transit_gateway_attachments( transit_gateways_attachment_ids=transit_gateways_attachment_ids, filters=filters, - max_results=max_results, ) ) template = self.response_template(DESCRIBE_TRANSIT_GATEWAY_ATTACHMENTS) @@ -159,12 +155,10 @@ class TransitGatewayAttachment(BaseResponse): "TransitGatewayAttachmentIds" ) filters = filters_from_querystring(self.querystring) - max_results = self._get_param("MaxResults") transit_gateway_peering_attachments = ( self.ec2_backend.describe_transit_gateway_peering_attachments( transit_gateways_attachment_ids=transit_gateways_attachment_ids, filters=filters, - max_results=max_results, ) ) template = self.response_template(DESCRIBE_TRANSIT_GATEWAY_PEERING_ATTACHMENTS) diff --git a/moto/ecr/models.py b/moto/ecr/models.py index 9af44f2fe..a303f1c19 100644 --- a/moto/ecr/models.py +++ b/moto/ecr/models.py @@ -153,8 +153,8 @@ class Repository(BaseObject, CloudFormationModel): ecr_backend.delete_repository(self.name) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn", "RepositoryUri"] + def has_cfn_attr(cls, attr): + return attr in ["Arn", "RepositoryUri"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -505,13 +505,10 @@ class ECRBackend(BaseBackend): existing_images[0].update_tag(image_tag) return existing_images[0] - def batch_get_image( - self, - repository_name, - registry_id=None, - image_ids=None, - accepted_media_types=None, - ): + def batch_get_image(self, repository_name, registry_id=None, image_ids=None): + """ + The parameter AcceptedMediaTypes has not yet been implemented + """ if repository_name in self.repositories: repository = self.repositories[repository_name] else: diff --git a/moto/ecr/responses.py b/moto/ecr/responses.py index 023416a68..8cfec7424 100644 --- a/moto/ecr/responses.py +++ b/moto/ecr/responses.py @@ -19,8 +19,8 @@ class ECRResponse(BaseResponse): except ValueError: return {} - def _get_param(self, param, if_none=None): - return self.request_params.get(param, if_none) + def _get_param(self, param_name, if_none=None): + return self.request_params.get(param_name, if_none) def create_repository(self): repository_name = self._get_param("repositoryName") @@ -106,10 +106,9 @@ class ECRResponse(BaseResponse): repository_str = self._get_param("repositoryName") registry_id = self._get_param("registryId") image_ids = self._get_param("imageIds") - accepted_media_types = self._get_param("acceptedMediaTypes") response = self.ecr_backend.batch_get_image( - repository_str, registry_id, image_ids, accepted_media_types + repository_str, registry_id, image_ids ) return json.dumps(response) diff --git a/moto/ecs/models.py b/moto/ecs/models.py index 2634ad07e..1b0cef6a7 100644 --- a/moto/ecs/models.py +++ b/moto/ecs/models.py @@ -122,8 +122,8 @@ class Cluster(BaseObject, CloudFormationModel): return original_resource @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -484,8 +484,8 @@ class Service(BaseObject, CloudFormationModel): ) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Name"] + def has_cfn_attr(cls, attr): + return attr in ["Name"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -1469,9 +1469,10 @@ class EC2ContainerServiceBackend(BaseBackend): cluster_name=None, attr_name=None, attr_value=None, - max_results=None, - next_token=None, ): + """ + Pagination is not yet implemented + """ if target_type != "container-instance": raise JsonRESTError( "InvalidParameterException", "targetType must be container-instance" @@ -1554,9 +1555,10 @@ class EC2ContainerServiceBackend(BaseBackend): "TargetNotFoundException", "Could not find {0}".format(target_id) ) - def list_task_definition_families( - self, family_prefix=None, status=None, max_results=None, next_token=None - ): + def list_task_definition_families(self, family_prefix=None): + """ + The Status and pagination parameters are not yet implemented + """ for task_fam in self.task_definitions: if family_prefix is not None and not task_fam.startswith(family_prefix): continue @@ -1720,7 +1722,10 @@ class EC2ContainerServiceBackend(BaseBackend): return task_set_results - def delete_task_set(self, cluster, service, task_set, force=False): + def delete_task_set(self, cluster, service, task_set): + """ + The Force-parameter is not yet implemented + """ cluster_name = cluster.split("/")[-1] service_name = service.split("/")[-1] diff --git a/moto/ecs/responses.py b/moto/ecs/responses.py index b279ee793..b95168488 100644 --- a/moto/ecs/responses.py +++ b/moto/ecs/responses.py @@ -22,8 +22,8 @@ class EC2ContainerServiceResponse(BaseResponse): except ValueError: return {} - def _get_param(self, param, if_none=None): - return self.request_params.get(param, if_none) + def _get_param(self, param_name, if_none=None): + return self.request_params.get(param_name, if_none) def create_cluster(self): cluster_name = self._get_param("clusterName") @@ -319,11 +319,9 @@ class EC2ContainerServiceResponse(BaseResponse): attr_name = self._get_param("attributeName") attr_value = self._get_param("attributeValue") target_type = self._get_param("targetType") - max_results = self._get_param("maxResults") - next_token = self._get_param("nextToken") results = self.ecs_backend.list_attributes( - target_type, cluster_name, attr_name, attr_value, max_results, next_token + target_type, cluster_name, attr_name, attr_value ) # Result will be [item will be {0 cluster_name, 1 arn, 2 name, 3 value}] @@ -355,13 +353,7 @@ class EC2ContainerServiceResponse(BaseResponse): def list_task_definition_families(self): family_prefix = self._get_param("familyPrefix") - status = self._get_param("status") - max_results = self._get_param("maxResults") - next_token = self._get_param("nextToken") - - results = self.ecs_backend.list_task_definition_families( - family_prefix, status, max_results, next_token - ) + results = self.ecs_backend.list_task_definition_families(family_prefix) return json.dumps({"families": list(results)}) @@ -432,10 +424,7 @@ class EC2ContainerServiceResponse(BaseResponse): cluster_str = self._get_param("cluster") service_str = self._get_param("service") task_set = self._get_param("taskSet") - force = self._get_param("force") - task_set = self.ecs_backend.delete_task_set( - cluster_str, service_str, task_set, force - ) + task_set = self.ecs_backend.delete_task_set(cluster_str, service_str, task_set) return json.dumps({"taskSet": task_set.response_object}) def update_task_set(self): diff --git a/moto/eks/exceptions.py b/moto/eks/exceptions.py index 49a7a52e1..41f874b0f 100644 --- a/moto/eks/exceptions.py +++ b/moto/eks/exceptions.py @@ -4,7 +4,7 @@ from moto.core.exceptions import AWSError class EKSError(AWSError): - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): super(AWSError, self).__init__() self.description = json.dumps(kwargs) self.headers = {"status": self.STATUS, "x-amzn-ErrorType": self.TYPE} diff --git a/moto/elastictranscoder/models.py b/moto/elastictranscoder/models.py index a217f8ef5..3629e7c96 100644 --- a/moto/elastictranscoder/models.py +++ b/moto/elastictranscoder/models.py @@ -78,11 +78,13 @@ class ElasticTranscoderBackend(BaseBackend): input_bucket, output_bucket, role, - aws_kms_key_arn, - notifications, content_config, thumbnail_config, ): + """ + The following parameters are not yet implemented: + AWSKMSKeyArn, Notifications + """ pipeline = Pipeline( self.region_name, name, @@ -102,17 +104,11 @@ class ElasticTranscoderBackend(BaseBackend): def read_pipeline(self, pipeline_id): return self.pipelines[pipeline_id] - def update_pipeline( - self, - pipeline_id, - name, - input_bucket, - role, - aws_kms_key_arn, - notifications, - content_config, - thumbnail_config, - ): + def update_pipeline(self, pipeline_id, name, input_bucket, role): + """ + The following parameters are not yet implemented: + AWSKMSKeyArn, Notifications, ContentConfig, ThumbnailConfig + """ pipeline = self.read_pipeline(pipeline_id) pipeline.update(name, input_bucket, role) warnings = [] diff --git a/moto/elastictranscoder/responses.py b/moto/elastictranscoder/responses.py index 5ac8d0059..cb4b12538 100644 --- a/moto/elastictranscoder/responses.py +++ b/moto/elastictranscoder/responses.py @@ -35,8 +35,6 @@ class ElasticTranscoderResponse(BaseResponse): input_bucket = self._get_param("InputBucket") output_bucket = self._get_param("OutputBucket") role = self._get_param("Role") - aws_kms_key_arn = self._get_param("AwsKmsKeyArn") - notifications = self._get_param("Notifications") content_config = self._get_param("ContentConfig") thumbnail_config = self._get_param("ThumbnailConfig") if not role: @@ -58,8 +56,6 @@ class ElasticTranscoderResponse(BaseResponse): input_bucket=input_bucket, output_bucket=output_bucket, role=role, - aws_kms_key_arn=aws_kms_key_arn, - notifications=notifications, content_config=content_config, thumbnail_config=thumbnail_config, ) @@ -109,22 +105,11 @@ class ElasticTranscoderResponse(BaseResponse): name = self._get_param("Name") input_bucket = self._get_param("InputBucket") role = self._get_param("Role") - aws_kms_key_arn = self._get_param("AwsKmsKeyArn") - notifications = self._get_param("Notifications") - content_config = self._get_param("ContentConfig") - thumbnail_config = self._get_param("ThumbnailConfig") err = self.validate_pipeline_id(_id) if err: return err pipeline, warnings = self.elastictranscoder_backend.update_pipeline( - pipeline_id=_id, - name=name, - input_bucket=input_bucket, - role=role, - aws_kms_key_arn=aws_kms_key_arn, - notifications=notifications, - content_config=content_config, - thumbnail_config=thumbnail_config, + pipeline_id=_id, name=name, input_bucket=input_bucket, role=role ) return ( diff --git a/moto/elb/models.py b/moto/elb/models.py index 99fbd11e0..859031ed4 100644 --- a/moto/elb/models.py +++ b/moto/elb/models.py @@ -207,8 +207,8 @@ class FakeLoadBalancer(CloudFormationModel): return self.name @classmethod - def has_cfn_attr(cls, attribute): - return attribute in [ + def has_cfn_attr(cls, attr): + return attr in [ "CanonicalHostedZoneName", "CanonicalHostedZoneNameID", "DNSName", diff --git a/moto/elbv2/exceptions.py b/moto/elbv2/exceptions.py index 1e02c046d..0d1d83250 100644 --- a/moto/elbv2/exceptions.py +++ b/moto/elbv2/exceptions.py @@ -131,7 +131,7 @@ class ActionTargetGroupNotFoundError(ELBClientError): class ListenerOrBalancerMissingError(ELBClientError): - def __init__(self, arn): + def __init__(self): super().__init__( "ValidationError", "You must specify either listener ARNs or a load balancer ARN", diff --git a/moto/elbv2/models.py b/moto/elbv2/models.py index 3c64c211c..eea4cd049 100644 --- a/moto/elbv2/models.py +++ b/moto/elbv2/models.py @@ -515,8 +515,8 @@ class FakeLoadBalancer(CloudFormationModel): return load_balancer @classmethod - def has_cfn_attr(cls, attribute): - return attribute in [ + def has_cfn_attr(cls, attr): + return attr in [ "DNSName", "LoadBalancerName", "CanonicalHostedZoneID", diff --git a/moto/emr/models.py b/moto/emr/models.py index f34fa5da5..85640e1b1 100644 --- a/moto/emr/models.py +++ b/moto/emr/models.py @@ -670,14 +670,8 @@ class ElasticMapReduceBackend(BaseBackend): instance_group.auto_scaling_policy = auto_scaling_policy return instance_group - def remove_auto_scaling_policy(self, cluster_id, instance_group_id): - instance_groups = self.get_instance_groups( - instance_group_ids=[instance_group_id] - ) - if len(instance_groups) == 0: - return None - instance_group = instance_groups[0] - instance_group.auto_scaling_policy = None + def remove_auto_scaling_policy(self, instance_group_id): + self.put_auto_scaling_policy(instance_group_id, auto_scaling_policy=None) def create_security_configuration(self, name, security_configuration): if name in self.security_configurations: diff --git a/moto/emr/responses.py b/moto/emr/responses.py index 8a6266ac0..c98e96750 100644 --- a/moto/emr/responses.py +++ b/moto/emr/responses.py @@ -532,7 +532,7 @@ class ElasticMapReduceResponse(BaseResponse): def remove_auto_scaling_policy(self): cluster_id = self._get_param("ClusterId") instance_group_id = self._get_param("InstanceGroupId") - instance_group = self.backend.put_auto_scaling_policy(instance_group_id, None) + instance_group = self.backend.remove_auto_scaling_policy(instance_group_id) template = self.response_template(REMOVE_AUTO_SCALING_POLICY) return template.render(cluster_id=cluster_id, instance_group=instance_group) diff --git a/moto/emr/utils.py b/moto/emr/utils.py index 46c78b787..b0746ece5 100644 --- a/moto/emr/utils.py +++ b/moto/emr/utils.py @@ -14,15 +14,15 @@ def random_id(size=13): return "".join(str(random.choice(chars)) for x in range(size)) -def random_cluster_id(size=13): +def random_cluster_id(): return "j-{0}".format(random_id()) -def random_step_id(size=13): +def random_step_id(): return "s-{0}".format(random_id()) -def random_instance_group_id(size=13): +def random_instance_group_id(): return "i-{0}".format(random_id()) diff --git a/moto/es/models.py b/moto/es/models.py index def2c3536..511f6beba 100644 --- a/moto/es/models.py +++ b/moto/es/models.py @@ -22,7 +22,6 @@ class Domain(BaseModel): domain_endpoint_options, advanced_security_options, auto_tune_options, - tag_list, ): self.domain_id = get_random_hex(8) self.region_name = region_name @@ -104,7 +103,6 @@ class ElasticsearchServiceBackend(BaseBackend): domain_endpoint_options, advanced_security_options, auto_tune_options, - tag_list, ): # TODO: Persist/Return other attributes new_domain = Domain( @@ -124,7 +122,6 @@ class ElasticsearchServiceBackend(BaseBackend): domain_endpoint_options=domain_endpoint_options, advanced_security_options=advanced_security_options, auto_tune_options=auto_tune_options, - tag_list=tag_list, ) self.domains[domain_name] = new_domain return new_domain.to_json() @@ -139,7 +136,7 @@ class ElasticsearchServiceBackend(BaseBackend): raise DomainNotFound(domain_name) return self.domains[domain_name].to_json() - def list_domain_names(self, engine_type): + def list_domain_names(self): """ The engine-type parameter is not yet supported. Pagination is not yet implemented. diff --git a/moto/es/responses.py b/moto/es/responses.py index ac4dfc2e2..c07b7ae83 100644 --- a/moto/es/responses.py +++ b/moto/es/responses.py @@ -71,7 +71,6 @@ class ElasticsearchServiceResponse(BaseResponse): domain_endpoint_options = params.get("DomainEndpointOptions") advanced_security_options = params.get("AdvancedSecurityOptions") auto_tune_options = params.get("AutoTuneOptions") - tag_list = params.get("TagList") domain_status = self.es_backend.create_elasticsearch_domain( domain_name=domain_name, elasticsearch_version=elasticsearch_version, @@ -88,7 +87,6 @@ class ElasticsearchServiceResponse(BaseResponse): domain_endpoint_options=domain_endpoint_options, advanced_security_options=advanced_security_options, auto_tune_options=auto_tune_options, - tag_list=tag_list, ) return 200, {}, json.dumps({"DomainStatus": domain_status}) @@ -107,7 +105,5 @@ class ElasticsearchServiceResponse(BaseResponse): return 200, {}, json.dumps({"DomainStatus": domain_status}) def list_domain_names(self): - params = self._get_params() - engine_type = params.get("EngineType") - domain_names = self.es_backend.list_domain_names(engine_type=engine_type) + domain_names = self.es_backend.list_domain_names() return 200, {}, json.dumps({"DomainNames": domain_names}) diff --git a/moto/events/models.py b/moto/events/models.py index c2d6fa021..3ecfdee3f 100644 --- a/moto/events/models.py +++ b/moto/events/models.py @@ -188,7 +188,7 @@ class Rule(CloudFormationModel): logs_backends[self.region_name].create_log_stream(name, log_stream_name) logs_backends[self.region_name].put_log_events( - name, log_stream_name, log_events, None + name, log_stream_name, log_events ) def _send_to_events_archive(self, resource_id, event): @@ -223,8 +223,8 @@ class Rule(CloudFormationModel): ) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -342,8 +342,8 @@ class EventBus(CloudFormationModel): event_backend.delete_event_bus(name=self.name) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn", "Name", "Policy"] + def has_cfn_attr(cls, attr): + return attr in ["Arn", "Name", "Policy"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -544,8 +544,8 @@ class Archive(CloudFormationModel): event_backend.archives.pop(self.name) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn", "ArchiveName"] + def has_cfn_attr(cls, attr): + return attr in ["Arn", "ArchiveName"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException diff --git a/moto/events/responses.py b/moto/events/responses.py index b112d0f6b..f79fbe8da 100644 --- a/moto/events/responses.py +++ b/moto/events/responses.py @@ -24,8 +24,8 @@ class EventsHandler(BaseResponse): self._json_body = {} return self._json_body - def _get_param(self, param, if_none=None): - return self.request_params.get(param, if_none) + def _get_param(self, param_name, if_none=None): + return self.request_params.get(param_name, if_none) def _create_response(self, result): """ diff --git a/moto/glacier/responses.py b/moto/glacier/responses.py index 6937d1645..334e737bd 100644 --- a/moto/glacier/responses.py +++ b/moto/glacier/responses.py @@ -1,5 +1,4 @@ import json -from urllib.parse import urlparse, parse_qs from moto.core.responses import BaseResponse from .models import glacier_backends @@ -13,9 +12,9 @@ class GlacierResponse(BaseResponse): def all_vault_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) - return self._all_vault_response(request, full_url, headers) + return self._all_vault_response(headers) - def _all_vault_response(self, request, full_url, headers): + def _all_vault_response(self, headers): vaults = self.glacier_backend.list_vaults() response = json.dumps( {"Marker": None, "VaultList": [vault.to_dict() for vault in vaults]} @@ -30,27 +29,25 @@ class GlacierResponse(BaseResponse): def _vault_response(self, request, full_url, headers): method = request.method - parsed_url = urlparse(full_url) - querystring = parse_qs(parsed_url.query, keep_blank_values=True) vault_name = vault_from_glacier_url(full_url) if method == "GET": - return self._vault_response_get(vault_name, querystring, headers) + return self._vault_response_get(vault_name, headers) elif method == "PUT": - return self._vault_response_put(vault_name, querystring, headers) + return self._vault_response_put(vault_name, headers) elif method == "DELETE": - return self._vault_response_delete(vault_name, querystring, headers) + return self._vault_response_delete(vault_name, headers) - def _vault_response_get(self, vault_name, querystring, headers): + def _vault_response_get(self, vault_name, headers): vault = self.glacier_backend.get_vault(vault_name) headers["content-type"] = "application/json" return 200, headers, json.dumps(vault.to_dict()) - def _vault_response_put(self, vault_name, querystring, headers): + def _vault_response_put(self, vault_name, headers): self.glacier_backend.create_vault(vault_name) return 201, headers, "" - def _vault_response_delete(self, vault_name, querystring, headers): + def _vault_response_delete(self, vault_name, headers): self.glacier_backend.delete_vault(vault_name) return 204, headers, "" @@ -66,20 +63,16 @@ class GlacierResponse(BaseResponse): description = "" if "x-amz-archive-description" in request.headers: description = request.headers["x-amz-archive-description"] - parsed_url = urlparse(full_url) - querystring = parse_qs(parsed_url.query, keep_blank_values=True) vault_name = full_url.split("/")[-2] if method == "POST": return self._vault_archive_response_post( - vault_name, body, description, querystring, headers + vault_name, body, description, headers ) else: return 400, headers, "400 Bad Request" - def _vault_archive_response_post( - self, vault_name, body, description, querystring, headers - ): + def _vault_archive_response_post(self, vault_name, body, description, headers): vault = self.glacier_backend.upload_archive(vault_name, body, description) headers["x-amz-archive-id"] = vault["archive_id"] headers["x-amz-sha256-tree-hash"] = vault["sha256"] @@ -143,9 +136,9 @@ class GlacierResponse(BaseResponse): def vault_jobs_individual_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) - return self._vault_jobs_individual_response(request, full_url, headers) + return self._vault_jobs_individual_response(full_url, headers) - def _vault_jobs_individual_response(self, request, full_url, headers): + def _vault_jobs_individual_response(self, full_url, headers): vault_name = full_url.split("/")[-3] archive_id = full_url.split("/")[-1] @@ -154,9 +147,9 @@ class GlacierResponse(BaseResponse): def vault_jobs_output_response(self, request, full_url, headers): self.setup_class(request, full_url, headers) - return self._vault_jobs_output_response(request, full_url, headers) + return self._vault_jobs_output_response(full_url, headers) - def _vault_jobs_output_response(self, request, full_url, headers): + def _vault_jobs_output_response(self, full_url, headers): vault_name = full_url.split("/")[-4] job_id = full_url.split("/")[-2] output = self.glacier_backend.get_job_output(vault_name, job_id) diff --git a/moto/guardduty/models.py b/moto/guardduty/models.py index aee27a772..31495ee49 100644 --- a/moto/guardduty/models.py +++ b/moto/guardduty/models.py @@ -16,9 +16,7 @@ class GuardDutyBackend(BaseBackend): self.__dict__ = {} self.__init__(region_name) - def create_detector( - self, enable, client_token, finding_publishing_frequency, data_sources, tags - ): + def create_detector(self, enable, finding_publishing_frequency, data_sources, tags): if finding_publishing_frequency not in [ "FIFTEEN_MINUTES", "ONE_HOUR", diff --git a/moto/guardduty/responses.py b/moto/guardduty/responses.py index 77d55c384..8b4554665 100644 --- a/moto/guardduty/responses.py +++ b/moto/guardduty/responses.py @@ -22,13 +22,12 @@ class GuardDutyResponse(BaseResponse): def create_detector(self): enable = self._get_param("enable") - client_token = self._get_param("clientToken") finding_publishing_frequency = self._get_param("findingPublishingFrequency") data_sources = self._get_param("dataSources") tags = self._get_param("tags") detector_id = self.guardduty_backend.create_detector( - enable, client_token, finding_publishing_frequency, data_sources, tags + enable, finding_publishing_frequency, data_sources, tags ) return 200, {}, json.dumps(dict(detectorId=detector_id)) diff --git a/moto/iam/models.py b/moto/iam/models.py index d79f60106..a2e9ae740 100644 --- a/moto/iam/models.py +++ b/moto/iam/models.py @@ -335,11 +335,11 @@ class ManagedPolicy(Policy, CloudFormationModel): @classmethod def create_from_cloudformation_json( - cls, resource_physical_name, cloudformation_json, region_name, **kwargs + cls, resource_name, cloudformation_json, region_name, **kwargs ): properties = cloudformation_json.get("Properties", {}) policy_document = json.dumps(properties.get("PolicyDocument")) - name = properties.get("ManagedPolicyName", resource_physical_name) + name = properties.get("ManagedPolicyName", resource_name) description = properties.get("Description") path = properties.get("Path") group_names = properties.get("Groups", []) @@ -442,7 +442,7 @@ class InlinePolicy(CloudFormationModel): @classmethod def create_from_cloudformation_json( - cls, resource_physical_name, cloudformation_json, region_name, **kwargs + cls, resource_name, cloudformation_json, region_name, **kwargs ): properties = cloudformation_json.get("Properties", {}) policy_document = properties.get("PolicyDocument") @@ -452,7 +452,7 @@ class InlinePolicy(CloudFormationModel): group_names = properties.get("Groups") return iam_backend.create_inline_policy( - resource_physical_name, + resource_name, policy_name, policy_document, group_names, @@ -584,14 +584,10 @@ class Role(CloudFormationModel): @classmethod def create_from_cloudformation_json( - cls, resource_physical_name, cloudformation_json, region_name, **kwargs + cls, resource_name, cloudformation_json, region_name, **kwargs ): properties = cloudformation_json["Properties"] - role_name = ( - properties["RoleName"] - if "RoleName" in properties - else resource_physical_name - ) + role_name = properties.get("RoleName", resource_name) role = iam_backend.create_role( role_name=role_name, @@ -707,8 +703,8 @@ class Role(CloudFormationModel): return self.name @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -751,13 +747,13 @@ class InstanceProfile(CloudFormationModel): @classmethod def create_from_cloudformation_json( - cls, resource_physical_name, cloudformation_json, region_name, **kwargs + cls, resource_name, cloudformation_json, region_name, **kwargs ): properties = cloudformation_json["Properties"] role_names = properties["Roles"] return iam_backend.create_instance_profile( - name=resource_physical_name, + name=resource_name, path=properties.get("Path", "/"), role_names=role_names, ) @@ -782,8 +778,8 @@ class InstanceProfile(CloudFormationModel): return self.name @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -880,8 +876,8 @@ class AccessKey(CloudFormationModel): return iso_8601_datetime_without_milliseconds(self.last_used) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["SecretAccessKey"] + def has_cfn_attr(cls, attr): + return attr in ["SecretAccessKey"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -900,7 +896,7 @@ class AccessKey(CloudFormationModel): @classmethod def create_from_cloudformation_json( - cls, resource_physical_name, cloudformation_json, region_name, **kwargs + cls, resource_name, cloudformation_json, region_name, **kwargs ): properties = cloudformation_json.get("Properties", {}) user_name = properties.get("UserName") @@ -981,8 +977,8 @@ class Group(BaseModel): return iso_8601_datetime_with_milliseconds(self.create_date) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -1145,8 +1141,8 @@ class User(CloudFormationModel): self.ssh_public_keys.remove(key) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -1237,11 +1233,11 @@ class User(CloudFormationModel): @classmethod def create_from_cloudformation_json( - cls, resource_physical_name, cloudformation_json, region_name, **kwargs + cls, resource_name, cloudformation_json, region_name, **kwargs ): properties = cloudformation_json.get("Properties", {}) path = properties.get("Path") - user, _ = iam_backend.create_user(resource_physical_name, path) + user, _ = iam_backend.create_user(resource_name, path) return user @classmethod @@ -2032,7 +2028,10 @@ class IAMBackend(BaseBackend): role = self.get_role(role_name) profile.roles.remove(role) - def get_all_server_certs(self, marker=None): + def list_server_certificates(self): + """ + Pagination is not yet implemented + """ return self.certificates.values() def upload_server_certificate( @@ -2080,7 +2079,10 @@ class IAMBackend(BaseBackend): self.groups[group_name] = group return group - def get_group(self, group_name, marker=None, max_items=None): + def get_group(self, group_name): + """ + Pagination is not yet implemented + """ try: return self.groups[group_name] except KeyError: @@ -2105,7 +2107,10 @@ class IAMBackend(BaseBackend): iam_policy_document_validator.validate() group.put_policy(policy_name, policy_json) - def list_group_policies(self, group_name, marker=None, max_items=None): + def list_group_policies(self, group_name): + """ + Pagination is not yet implemented + """ group = self.get_group(group_name) return group.list_policies() @@ -2363,10 +2368,13 @@ class IAMBackend(BaseBackend): def get_all_access_keys_for_all_users(self): access_keys_list = [] for user_name in self.users: - access_keys_list += self.get_all_access_keys(user_name) + access_keys_list += self.list_access_keys(user_name) return access_keys_list - def get_all_access_keys(self, user_name, marker=None, max_items=None): + def list_access_keys(self, user_name): + """ + Pagination is not yet implemented + """ user = self.get_user(user_name) keys = user.get_all_access_keys() return keys @@ -2556,7 +2564,7 @@ class IAMBackend(BaseBackend): # alias is force updated self.account_aliases = [alias] - def delete_account_alias(self, alias): + def delete_account_alias(self): self.account_aliases = [] def get_account_authorization_details(self, policy_filter): @@ -2619,7 +2627,7 @@ class IAMBackend(BaseBackend): def get_user_from_access_key_id(self, access_key_id): for user_name, user in self.users.items(): - access_keys = self.get_all_access_keys(user_name) + access_keys = self.list_access_keys(user_name) for access_key in access_keys: if access_key.access_key_id == access_key_id: return user diff --git a/moto/iam/responses.py b/moto/iam/responses.py index 85de40370..c28e3707e 100644 --- a/moto/iam/responses.py +++ b/moto/iam/responses.py @@ -420,8 +420,8 @@ class IamResponse(BaseResponse): template = self.response_template(UPLOAD_CERT_TEMPLATE) return template.render(certificate=cert) - def list_server_certificates(self, marker=None): - certs = iam_backend.get_all_server_certs(marker=marker) + def list_server_certificates(self): + certs = iam_backend.list_server_certificates() template = self.response_template(LIST_SERVER_CERTIFICATES_TEMPLATE) return template.render(server_certificates=certs) @@ -475,10 +475,7 @@ class IamResponse(BaseResponse): def list_group_policies(self): group_name = self._get_param("GroupName") marker = self._get_param("Marker") - max_items = self._get_param("MaxItems") - policies = iam_backend.list_group_policies( - group_name, marker=marker, max_items=max_items - ) + policies = iam_backend.list_group_policies(group_name) template = self.response_template(LIST_GROUP_POLICIES_TEMPLATE) return template.render( name="ListGroupPoliciesResponse", policies=policies, marker=marker @@ -675,7 +672,7 @@ class IamResponse(BaseResponse): access_key = iam_backend.get_access_key_last_used(access_key_id) user_name = access_key["user_name"] - keys = iam_backend.get_all_access_keys(user_name) + keys = iam_backend.list_access_keys(user_name) template = self.response_template(LIST_ACCESS_KEYS_TEMPLATE) return template.render(user_name=user_name, keys=keys) @@ -830,8 +827,7 @@ class IamResponse(BaseResponse): return template.render() def delete_account_alias(self): - alias = self._get_param("AccountAlias") - iam_backend.delete_account_alias(alias) + iam_backend.delete_account_alias() template = self.response_template(DELETE_ACCOUNT_ALIAS_TEMPLATE) return template.render() diff --git a/moto/instance_metadata/responses.py b/moto/instance_metadata/responses.py index 13b2a0c63..f96675581 100644 --- a/moto/instance_metadata/responses.py +++ b/moto/instance_metadata/responses.py @@ -6,7 +6,9 @@ from moto.core.responses import BaseResponse class InstanceMetadataResponse(BaseResponse): - def metadata_response(self, request, full_url, headers): + def metadata_response( + self, request, full_url, headers + ): # pylint: disable=unused-argument """ Mock response for localhost metadata diff --git a/moto/iot/models.py b/moto/iot/models.py index 954ed3be6..16792f5d4 100644 --- a/moto/iot/models.py +++ b/moto/iot/models.py @@ -750,8 +750,10 @@ class IoTBackend(BaseBackend): self.endpoint = FakeEndpoint(endpoint_type, self.region_name) return self.endpoint - def delete_thing(self, thing_name, expected_version): - # TODO: handle expected_version + def delete_thing(self, thing_name): + """ + The ExpectedVersion-parameter is not yet implemented + """ # can raise ResourceNotFoundError thing = self.describe_thing(thing_name) @@ -781,9 +783,11 @@ class IoTBackend(BaseBackend): thing_name, thing_type_name, attribute_payload, - expected_version, remove_thing_type, ): + """ + The ExpectedVersion-parameter is not yet implemented + """ # if attributes payload = {}, nothing thing = self.describe_thing(thing_name) thing_type = None @@ -921,10 +925,12 @@ class IoTBackend(BaseBackend): def register_ca_certificate( self, ca_certificate, - verification_certificate, set_as_active, registration_config, ): + """ + The VerificationCertificate-parameter is not yet implemented + """ certificate = FakeCaCertificate( ca_certificate=ca_certificate, status="ACTIVE" if set_as_active else "INACTIVE", @@ -1204,7 +1210,10 @@ class IoTBackend(BaseBackend): self.thing_groups[thing_group.arn] = thing_group return thing_group.thing_group_name, thing_group.arn, thing_group.thing_group_id - def delete_thing_group(self, thing_group_name, expected_version): + def delete_thing_group(self, thing_group_name): + """ + The ExpectedVersion-parameter is not yet implemented + """ child_groups = [ thing_group for _, thing_group in self.thing_groups.items() @@ -1328,9 +1337,9 @@ class IoTBackend(BaseBackend): return del thing_group.things[thing.arn] - def list_things_in_thing_group(self, thing_group_name, recursive): + def list_things_in_thing_group(self, thing_group_name): """ - The recursive-parameter is not yet implemented + Pagination and the recursive-parameter is not yet implemented """ thing_group = self.describe_thing_group(thing_group_name) return thing_group.things.values() @@ -1435,16 +1444,10 @@ class IoTBackend(BaseBackend): def get_job_document(self, job_id): return self.jobs[job_id] - def list_jobs( - self, - status, - target_selection, - max_results, - token, - thing_group_name, - thing_group_id, - ): - # TODO: implement filters + def list_jobs(self, max_results, token): + """ + The following parameter are not yet implemented: Status, TargetSelection, ThingGroupName, ThingGroupId + """ all_jobs = [_.to_dict() for _ in self.jobs.values()] filtered_jobs = all_jobs @@ -1476,9 +1479,10 @@ class IoTBackend(BaseBackend): return job_execution - def cancel_job_execution( - self, job_id, thing_name, force, expected_version, status_details - ): + def cancel_job_execution(self, job_id, thing_name, force): + """ + The parameters ExpectedVersion and StatusDetails are not yet implemented + """ job_execution = self.job_executions[(job_id, thing_name)] if job_execution is None: @@ -1607,10 +1611,12 @@ class IoTBackend(BaseBackend): domain_configuration_name, domain_name, server_certificate_arns, - validation_certificate_arn, authorizer_config, service_type, ): + """ + The ValidationCertificateArn-parameter is not yet implemented + """ if domain_configuration_name in self.domain_configurations: raise ResourceAlreadyExistsException( "Domain configuration with given name already exists.", diff --git a/moto/iot/responses.py b/moto/iot/responses.py index 525b6a246..544e8e944 100644 --- a/moto/iot/responses.py +++ b/moto/iot/responses.py @@ -107,10 +107,7 @@ class IoTResponse(BaseResponse): def delete_thing(self): thing_name = self._get_param("thingName") - expected_version = self._get_param("expectedVersion") - self.iot_backend.delete_thing( - thing_name=thing_name, expected_version=expected_version - ) + self.iot_backend.delete_thing(thing_name=thing_name) return json.dumps(dict()) def delete_thing_type(self): @@ -130,13 +127,11 @@ class IoTResponse(BaseResponse): thing_name = self._get_param("thingName") thing_type_name = self._get_param("thingTypeName") attribute_payload = self._get_param("attributePayload") - expected_version = self._get_param("expectedVersion") remove_thing_type = self._get_param("removeThingType") self.iot_backend.update_thing( thing_name=thing_name, thing_type_name=thing_type_name, attribute_payload=attribute_payload, - expected_version=expected_version, remove_thing_type=remove_thing_type, ) return json.dumps(dict()) @@ -213,21 +208,11 @@ class IoTResponse(BaseResponse): return json.dumps({"document": ""}) def list_jobs(self): - status = (self._get_param("status"),) - target_selection = (self._get_param("targetSelection"),) - max_results = self._get_int_param( - "maxResults", 50 - ) # not the default, but makes testing easier + # not the default, but makes testing easier + max_results = self._get_int_param("maxResults", 50) previous_next_token = self._get_param("nextToken") - thing_group_name = (self._get_param("thingGroupName"),) - thing_group_id = self._get_param("thingGroupId") jobs, next_token = self.iot_backend.list_jobs( - status=status, - target_selection=target_selection, - max_results=max_results, - token=previous_next_token, - thing_group_name=thing_group_name, - thing_group_id=thing_group_id, + max_results=max_results, token=previous_next_token ) return json.dumps(dict(jobs=jobs, nextToken=next_token)) @@ -246,15 +231,9 @@ class IoTResponse(BaseResponse): job_id = self._get_param("jobId") thing_name = self._get_param("thingName") force = self._get_bool_param("force") - expected_version = self._get_int_param("expectedVersion") - status_details = self._get_param("statusDetails") self.iot_backend.cancel_job_execution( - job_id=job_id, - thing_name=thing_name, - force=force, - expected_version=expected_version, - status_details=status_details, + job_id=job_id, thing_name=thing_name, force=force ) return json.dumps(dict()) @@ -366,13 +345,11 @@ class IoTResponse(BaseResponse): def register_ca_certificate(self): ca_certificate = self._get_param("caCertificate") - verification_certificate = self._get_param("verificationCertificate") set_as_active = self._get_bool_param("setAsActive") registration_config = self._get_param("registrationConfig") cert = self.iot_backend.register_ca_certificate( ca_certificate=ca_certificate, - verification_certificate=verification_certificate, set_as_active=set_as_active, registration_config=registration_config, ) @@ -621,10 +598,7 @@ class IoTResponse(BaseResponse): def delete_thing_group(self): thing_group_name = self._get_param("thingGroupName") - expected_version = self._get_param("expectedVersion") - self.iot_backend.delete_thing_group( - thing_group_name=thing_group_name, expected_version=expected_version - ) + self.iot_backend.delete_thing_group(thing_group_name=thing_group_name) return json.dumps(dict()) def list_thing_groups(self): @@ -684,15 +658,11 @@ class IoTResponse(BaseResponse): def list_things_in_thing_group(self): thing_group_name = self._get_param("thingGroupName") - recursive = self._get_param("recursive") - # next_token = self._get_param("nextToken") - # max_results = self._get_int_param("maxResults") things = self.iot_backend.list_things_in_thing_group( - thing_group_name=thing_group_name, recursive=recursive + thing_group_name=thing_group_name ) next_token = None thing_names = [_.thing_name for _ in things] - # TODO: implement pagination in the future return json.dumps(dict(things=thing_names, nextToken=next_token)) def list_thing_groups_for_thing(self): @@ -765,7 +735,6 @@ class IoTResponse(BaseResponse): domain_configuration_name=self._get_param("domainConfigurationName"), domain_name=self._get_param("domainName"), server_certificate_arns=self._get_param("serverCertificateArns"), - validation_certificate_arn=self._get_param("validationCertificateArn"), authorizer_config=self._get_param("authorizerConfig"), service_type=self._get_param("serviceType"), ) diff --git a/moto/iotdata/models.py b/moto/iotdata/models.py index 071a03a2b..52ab966a1 100644 --- a/moto/iotdata/models.py +++ b/moto/iotdata/models.py @@ -199,7 +199,7 @@ class IoTDataPlaneBackend(BaseBackend): thing.thing_shadow = new_shadow return thing.thing_shadow - def publish(self, topic, qos, payload): + def publish(self, topic, payload): self.published_payloads.append((topic, payload)) diff --git a/moto/iotdata/responses.py b/moto/iotdata/responses.py index 801d20c78..02b8d6ea8 100644 --- a/moto/iotdata/responses.py +++ b/moto/iotdata/responses.py @@ -42,6 +42,5 @@ class IoTDataPlaneResponse(BaseResponse): def publish(self): topic = self._get_param("target") - qos = self._get_int_param("qos") - self.iotdata_backend.publish(topic=topic, qos=qos, payload=self.body) + self.iotdata_backend.publish(topic=topic, payload=self.body) return json.dumps(dict()) diff --git a/moto/kinesis/models.py b/moto/kinesis/models.py index 0a73c90e0..4ba54e3f6 100644 --- a/moto/kinesis/models.py +++ b/moto/kinesis/models.py @@ -245,9 +245,7 @@ class Stream(CloudFormationModel): for index in records: record = records[index] - self.put_record( - record.partition_key, record.explicit_hash_key, None, record.data - ) + self.put_record(record.partition_key, record.explicit_hash_key, record.data) def merge_shards(self, shard_to_merge, adjacent_shard_to_merge): shard1 = self.shards[shard_to_merge] @@ -371,9 +369,7 @@ class Stream(CloudFormationModel): if shard.starting_hash <= key < shard.ending_hash: return shard - def put_record( - self, partition_key, explicit_hash_key, sequence_number_for_ordering, data - ): + def put_record(self, partition_key, explicit_hash_key, data): shard = self.get_shard_for_key(partition_key, explicit_hash_key) sequence_number = shard.put_record(partition_key, data, explicit_hash_key) @@ -488,8 +484,8 @@ class Stream(CloudFormationModel): ) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -594,13 +590,12 @@ class KinesisBackend(BaseBackend): stream_name, partition_key, explicit_hash_key, - sequence_number_for_ordering, data, ): stream = self.describe_stream(stream_name) sequence_number, shard_id = stream.put_record( - partition_key, explicit_hash_key, sequence_number_for_ordering, data + partition_key, explicit_hash_key, data ) return sequence_number, shard_id @@ -616,7 +611,7 @@ class KinesisBackend(BaseBackend): data = record.get("Data") sequence_number, shard_id = stream.put_record( - partition_key, explicit_hash_key, None, data + partition_key, explicit_hash_key, data ) response["Records"].append( {"SequenceNumber": sequence_number, "ShardId": shard_id} diff --git a/moto/kinesis/responses.py b/moto/kinesis/responses.py index 54d2c7b08..f8e321409 100644 --- a/moto/kinesis/responses.py +++ b/moto/kinesis/responses.py @@ -98,14 +98,12 @@ class KinesisResponse(BaseResponse): stream_name = self.parameters.get("StreamName") partition_key = self.parameters.get("PartitionKey") explicit_hash_key = self.parameters.get("ExplicitHashKey") - sequence_number_for_ordering = self.parameters.get("SequenceNumberForOrdering") data = self.parameters.get("Data") sequence_number, shard_id = self.kinesis_backend.put_record( stream_name, partition_key, explicit_hash_key, - sequence_number_for_ordering, data, ) diff --git a/moto/kinesisvideo/models.py b/moto/kinesisvideo/models.py index 56d285ac6..ed96ff2b1 100644 --- a/moto/kinesisvideo/models.py +++ b/moto/kinesisvideo/models.py @@ -113,12 +113,18 @@ class KinesisVideoBackend(BaseBackend): stream_info = stream.to_dict() return stream_info - def list_streams(self, max_results, next_token, stream_name_condition): + def list_streams(self): + """ + Pagination and the StreamNameCondition-parameter are not yet implemented + """ stream_info_list = [_.to_dict() for _ in self.streams.values()] next_token = None return stream_info_list, next_token - def delete_stream(self, stream_arn, current_version): + def delete_stream(self, stream_arn): + """ + The CurrentVersion-parameter is not yet implemented + """ stream = self.streams.get(stream_arn) if stream is None: raise ResourceNotFoundException() diff --git a/moto/kinesisvideo/responses.py b/moto/kinesisvideo/responses.py index 8dd48fb08..41d954627 100644 --- a/moto/kinesisvideo/responses.py +++ b/moto/kinesisvideo/responses.py @@ -36,22 +36,12 @@ class KinesisVideoResponse(BaseResponse): return json.dumps(dict(StreamInfo=stream_info)) def list_streams(self): - max_results = self._get_int_param("MaxResults") - next_token = self._get_param("NextToken") - stream_name_condition = self._get_param("StreamNameCondition") - stream_info_list, next_token = self.kinesisvideo_backend.list_streams( - max_results=max_results, - next_token=next_token, - stream_name_condition=stream_name_condition, - ) + stream_info_list, next_token = self.kinesisvideo_backend.list_streams() return json.dumps(dict(StreamInfoList=stream_info_list, NextToken=next_token)) def delete_stream(self): stream_arn = self._get_param("StreamARN") - current_version = self._get_param("CurrentVersion") - self.kinesisvideo_backend.delete_stream( - stream_arn=stream_arn, current_version=current_version - ) + self.kinesisvideo_backend.delete_stream(stream_arn=stream_arn) return json.dumps(dict()) def get_data_endpoint(self): diff --git a/moto/kinesisvideoarchivedmedia/models.py b/moto/kinesisvideoarchivedmedia/models.py index 0b662b110..c50cae930 100644 --- a/moto/kinesisvideoarchivedmedia/models.py +++ b/moto/kinesisvideoarchivedmedia/models.py @@ -28,40 +28,19 @@ class KinesisVideoArchivedMediaBackend(BaseBackend): url = "{}{}?SessionToken={}".format(data_endpoint, relative_path, session_token) return url - def get_hls_streaming_session_url( - self, - stream_name, - stream_arn, - playback_mode, - hls_fragment_selector, - container_format, - discontinuity_mode, - display_fragment_timestamp, - expires, - max_media_playlist_fragment_results, - ): + def get_hls_streaming_session_url(self, stream_name, stream_arn): # Ignore option paramters as the format of hls_url does't depends on them api_name = "GET_HLS_STREAMING_SESSION_URL" url = self._get_streaming_url(stream_name, stream_arn, api_name) return url - def get_dash_streaming_session_url( - self, - stream_name, - stream_arn, - playback_mode, - display_fragment_timestamp, - display_fragment_number, - dash_fragment_selector, - expires, - max_manifest_fragment_results, - ): + def get_dash_streaming_session_url(self, stream_name, stream_arn): # Ignore option paramters as the format of hls_url does't depends on them api_name = "GET_DASH_STREAMING_SESSION_URL" url = self._get_streaming_url(stream_name, stream_arn, api_name) return url - def get_clip(self, stream_name, stream_arn, clip_fragment_selector): + def get_clip(self, stream_name, stream_arn): kinesisvideo_backends[self.region_name]._get_stream(stream_name, stream_arn) content_type = "video/mp4" # Fixed content_type as it depends on input stream payload = b"sample-mp4-video" diff --git a/moto/kinesisvideoarchivedmedia/responses.py b/moto/kinesisvideoarchivedmedia/responses.py index dbfa6fee7..caa10ca54 100644 --- a/moto/kinesisvideoarchivedmedia/responses.py +++ b/moto/kinesisvideoarchivedmedia/responses.py @@ -13,26 +13,9 @@ class KinesisVideoArchivedMediaResponse(BaseResponse): def get_hls_streaming_session_url(self): stream_name = self._get_param("StreamName") stream_arn = self._get_param("StreamARN") - playback_mode = self._get_param("PlaybackMode") - hls_fragment_selector = self._get_param("HLSFragmentSelector") - container_format = self._get_param("ContainerFormat") - discontinuity_mode = self._get_param("DiscontinuityMode") - display_fragment_timestamp = self._get_param("DisplayFragmentTimestamp") - expires = self._get_int_param("Expires") - max_media_playlist_fragment_results = self._get_param( - "MaxMediaPlaylistFragmentResults" - ) hls_streaming_session_url = ( self.kinesisvideoarchivedmedia_backend.get_hls_streaming_session_url( - stream_name=stream_name, - stream_arn=stream_arn, - playback_mode=playback_mode, - hls_fragment_selector=hls_fragment_selector, - container_format=container_format, - discontinuity_mode=discontinuity_mode, - display_fragment_timestamp=display_fragment_timestamp, - expires=expires, - max_media_playlist_fragment_results=max_media_playlist_fragment_results, + stream_name=stream_name, stream_arn=stream_arn ) ) return json.dumps(dict(HLSStreamingSessionURL=hls_streaming_session_url)) @@ -40,22 +23,9 @@ class KinesisVideoArchivedMediaResponse(BaseResponse): def get_dash_streaming_session_url(self): stream_name = self._get_param("StreamName") stream_arn = self._get_param("StreamARN") - playback_mode = self._get_param("PlaybackMode") - display_fragment_timestamp = self._get_param("DisplayFragmentTimestamp") - display_fragment_number = self._get_param("DisplayFragmentNumber") - dash_fragment_selector = self._get_param("DASHFragmentSelector") - expires = self._get_int_param("Expires") - max_manifest_fragment_results = self._get_param("MaxManifestFragmentResults") dash_streaming_session_url = ( self.kinesisvideoarchivedmedia_backend.get_dash_streaming_session_url( - stream_name=stream_name, - stream_arn=stream_arn, - playback_mode=playback_mode, - display_fragment_timestamp=display_fragment_timestamp, - display_fragment_number=display_fragment_number, - dash_fragment_selector=dash_fragment_selector, - expires=expires, - max_manifest_fragment_results=max_manifest_fragment_results, + stream_name=stream_name, stream_arn=stream_arn ) ) return json.dumps(dict(DASHStreamingSessionURL=dash_streaming_session_url)) @@ -63,11 +33,8 @@ class KinesisVideoArchivedMediaResponse(BaseResponse): def get_clip(self): stream_name = self._get_param("StreamName") stream_arn = self._get_param("StreamARN") - clip_fragment_selector = self._get_param("ClipFragmentSelector") content_type, payload = self.kinesisvideoarchivedmedia_backend.get_clip( - stream_name=stream_name, - stream_arn=stream_arn, - clip_fragment_selector=clip_fragment_selector, + stream_name=stream_name, stream_arn=stream_arn ) new_headers = {"Content-Type": content_type} return payload, new_headers diff --git a/moto/kms/models.py b/moto/kms/models.py index e66efa2c9..b7eefef65 100644 --- a/moto/kms/models.py +++ b/moto/kms/models.py @@ -148,8 +148,8 @@ class Key(CloudFormationModel): return key @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Arn"] + def has_cfn_attr(cls, attr): + return attr in ["Arn"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException @@ -361,9 +361,7 @@ class KmsBackend(BaseBackend): ) return new_ciphertext_blob, decrypting_arn, encrypting_arn - def generate_data_key( - self, key_id, encryption_context, number_of_bytes, key_spec, grant_tokens - ): + def generate_data_key(self, key_id, encryption_context, number_of_bytes, key_spec): key_id = self.any_id_to_key_id(key_id) if key_spec: diff --git a/moto/kms/responses.py b/moto/kms/responses.py index 82ebd9f14..327bba902 100644 --- a/moto/kms/responses.py +++ b/moto/kms/responses.py @@ -462,7 +462,6 @@ class KmsResponse(BaseResponse): encryption_context = self.parameters.get("EncryptionContext", {}) number_of_bytes = self.parameters.get("NumberOfBytes") key_spec = self.parameters.get("KeySpec") - grant_tokens = self.parameters.get("GrantTokens") # Param validation self._validate_key_id(key_id) @@ -499,7 +498,6 @@ class KmsResponse(BaseResponse): encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, - grant_tokens=grant_tokens, ) plaintext_response = base64.b64encode(plaintext).decode("utf-8") diff --git a/moto/logs/models.py b/moto/logs/models.py index d17cee960..578dd456d 100644 --- a/moto/logs/models.py +++ b/moto/logs/models.py @@ -105,9 +105,7 @@ class LogStream(BaseModel): res.update(rest) return res - def put_log_events( - self, log_group_name, log_stream_name, log_events, sequence_token - ): + def put_log_events(self, log_group_name, log_stream_name, log_events): # TODO: ensure sequence_token # TODO: to be thread safe this would need a lock self.last_ingestion_time = int(unix_time_millis()) @@ -160,8 +158,6 @@ class LogStream(BaseModel): def get_log_events( self, - log_group_name, - log_stream_name, start_time, end_time, limit, @@ -238,17 +234,7 @@ class LogStream(BaseModel): "f/{:056d}".format(end_index), ) - def filter_log_events( - self, - log_group_name, - log_stream_names, - start_time, - end_time, - limit, - next_token, - filter_pattern, - interleaved, - ): + def filter_log_events(self, start_time, end_time, filter_pattern): if filter_pattern: raise NotImplementedError("filter_pattern is not yet implemented") @@ -375,19 +361,14 @@ class LogGroup(CloudFormationModel): return log_streams_page, new_token - def put_log_events( - self, log_group_name, log_stream_name, log_events, sequence_token - ): + def put_log_events(self, log_group_name, log_stream_name, log_events): if log_stream_name not in self.streams: raise ResourceNotFoundException("The specified log stream does not exist.") stream = self.streams[log_stream_name] - return stream.put_log_events( - log_group_name, log_stream_name, log_events, sequence_token - ) + return stream.put_log_events(log_group_name, log_stream_name, log_events) def get_log_events( self, - log_group_name, log_stream_name, start_time, end_time, @@ -399,8 +380,6 @@ class LogGroup(CloudFormationModel): raise ResourceNotFoundException() stream = self.streams[log_stream_name] return stream.get_log_events( - log_group_name, - log_stream_name, start_time, end_time, limit, @@ -429,16 +408,7 @@ class LogGroup(CloudFormationModel): events = [] for stream in streams: - events += stream.filter_log_events( - log_group_name, - log_stream_names, - start_time, - end_time, - limit, - next_token, - filter_pattern, - interleaved, - ) + events += stream.filter_log_events(start_time, end_time, filter_pattern) if interleaved: events = sorted(events, key=lambda event: event["timestamp"]) @@ -728,10 +698,10 @@ class LogsBackend(BaseBackend): order_by=order_by, ) - def put_log_events( - self, log_group_name, log_stream_name, log_events, sequence_token - ): - # TODO: add support for sequence_tokens + def put_log_events(self, log_group_name, log_stream_name, log_events): + """ + The SequenceToken-parameter is not yet implemented + """ if log_group_name not in self.groups: raise ResourceNotFoundException() log_group = self.groups[log_group_name] @@ -756,7 +726,7 @@ class LogsBackend(BaseBackend): last_timestamp = event["timestamp"] token = log_group.put_log_events( - log_group_name, log_stream_name, allowed_events, sequence_token + log_group_name, log_stream_name, allowed_events ) return token, rejected_info @@ -780,13 +750,7 @@ class LogsBackend(BaseBackend): ) log_group = self.groups[log_group_name] return log_group.get_log_events( - log_group_name, - log_stream_name, - start_time, - end_time, - limit, - next_token, - start_from_head, + log_stream_name, start_time, end_time, limit, next_token, start_from_head ) def filter_log_events( @@ -977,17 +941,7 @@ class LogsBackend(BaseBackend): self.queries[query_id] = LogQuery(query_id, start_time, end_time, query_string) return query_id - def create_export_task( - self, - *, - task_name, - log_group_name, - log_stream_name_prefix, - fromTime, - to, - destination, - destination_prefix, - ): + def create_export_task(self, log_group_name, destination): s3_backend.get_bucket(destination) if log_group_name not in self.groups: raise ResourceNotFoundException() diff --git a/moto/logs/responses.py b/moto/logs/responses.py index edf30c677..39f1930ba 100644 --- a/moto/logs/responses.py +++ b/moto/logs/responses.py @@ -41,8 +41,8 @@ class LogsResponse(BaseResponse): except ValueError: return {} - def _get_param(self, param, if_none=None): - return self.request_params.get(param, if_none) + def _get_param(self, param_name, if_none=None): + return self.request_params.get(param_name, if_none) def _get_validated_param( self, param, constraint, constraint_expression, pattern=None @@ -212,10 +212,9 @@ class LogsResponse(BaseResponse): log_group_name = self._get_param("logGroupName") log_stream_name = self._get_param("logStreamName") log_events = self._get_param("logEvents") - sequence_token = self._get_param("sequenceToken") next_sequence_token, rejected_info = self.logs_backend.put_log_events( - log_group_name, log_stream_name, log_events, sequence_token + log_group_name, log_stream_name, log_events ) if rejected_info: return json.dumps( @@ -381,21 +380,9 @@ class LogsResponse(BaseResponse): return json.dumps({"queryId": "{0}".format(query_id)}) def create_export_task(self): - task_name = self._get_param("taskName") log_group_name = self._get_param("logGroupName") - log_group_name = self._get_param("logGroupName") - log_stream_name_prefix = self._get_param("logStreamNamePrefix") - fromTime = self._get_param("from") - to = self._get_param("to") destination = self._get_param("destination") - destination_prefix = self._get_param("destinationPrefix") task_id = self.logs_backend.create_export_task( - task_name=task_name, - log_group_name=log_group_name, - log_stream_name_prefix=log_stream_name_prefix, - fromTime=fromTime, - to=to, - destination=destination, - destination_prefix=destination_prefix, + log_group_name=log_group_name, destination=destination ) return json.dumps(dict(taskId=str(task_id))) diff --git a/moto/managedblockchain/exceptions.py b/moto/managedblockchain/exceptions.py index fbcab1481..71cf4ff4c 100644 --- a/moto/managedblockchain/exceptions.py +++ b/moto/managedblockchain/exceptions.py @@ -17,12 +17,12 @@ def exception_handler(f): class ManagedBlockchainClientError(HTTPException): code = 400 - def __init__(self, error_type, message, **kwargs): + def __init__(self, error_type, message): self.error_type = error_type self.message = message self.description = json.dumps({"message": self.message}) - def get_headers(self, *args, **kwargs): + def get_headers(self, *args, **kwargs): # pylint: disable=unused-argument return [ ("Content-Type", "application/json"), ("x-amzn-ErrorType", self.error_type), @@ -32,7 +32,7 @@ class ManagedBlockchainClientError(HTTPException): def response(self): return self.get_body() - def get_body(self, *args, **kwargs): + def get_body(self, *args, **kwargs): # pylint: disable=unused-argument return self.description diff --git a/moto/managedblockchain/responses.py b/moto/managedblockchain/responses.py index 8433a02a9..f23112bf2 100644 --- a/moto/managedblockchain/responses.py +++ b/moto/managedblockchain/responses.py @@ -26,23 +26,21 @@ class ManagedBlockchainResponse(BaseResponse): response_instance = ManagedBlockchainResponse( managedblockchain_backends[region_name] ) - return response_instance._network_response(request, full_url, headers) + return response_instance._network_response(request, headers) - def _network_response(self, request, full_url, headers): + def _network_response(self, request, headers): method = request.method if hasattr(request, "body"): body = request.body else: body = request.data - parsed_url = urlparse(full_url) - querystring = parse_qs(parsed_url.query, keep_blank_values=True) if method == "GET": - return self._all_networks_response(request, full_url, headers) + return self._all_networks_response(headers) elif method == "POST": json_body = json.loads(body.decode("utf-8")) - return self._network_response_post(json_body, querystring, headers) + return self._network_response_post(json_body, headers) - def _all_networks_response(self, request, full_url, headers): + def _all_networks_response(self, headers): mbcnetworks = self.backend.list_networks() response = json.dumps( {"Networks": [mbcnetwork.to_dict() for mbcnetwork in mbcnetworks]} @@ -50,7 +48,7 @@ class ManagedBlockchainResponse(BaseResponse): headers["content-type"] = "application/json" return 200, headers, response - def _network_response_post(self, json_body, querystring, headers): + def _network_response_post(self, json_body, headers): name = json_body["Name"] framework = json_body["Framework"] frameworkversion = json_body["FrameworkVersion"] @@ -109,16 +107,12 @@ class ManagedBlockchainResponse(BaseResponse): body = request.body else: body = request.data - parsed_url = urlparse(full_url) - querystring = parse_qs(parsed_url.query, keep_blank_values=True) network_id = networkid_from_managedblockchain_url(full_url) if method == "GET": return self._all_proposals_response(network_id, headers) elif method == "POST": json_body = json.loads(body.decode("utf-8")) - return self._proposal_response_post( - network_id, json_body, querystring, headers - ) + return self._proposal_response_post(network_id, json_body, headers) def _all_proposals_response(self, network_id, headers): proposals = self.backend.list_proposals(network_id) @@ -128,7 +122,7 @@ class ManagedBlockchainResponse(BaseResponse): headers["content-type"] = "application/json" return 200, headers, response - def _proposal_response_post(self, network_id, json_body, querystring, headers): + def _proposal_response_post(self, network_id, json_body, headers): memberid = json_body["MemberId"] actions = json_body["Actions"] @@ -177,8 +171,6 @@ class ManagedBlockchainResponse(BaseResponse): body = request.body else: body = request.data - parsed_url = urlparse(full_url) - querystring = parse_qs(parsed_url.query, keep_blank_values=True) network_id = networkid_from_managedblockchain_url(full_url) proposal_id = proposalid_from_managedblockchain_url(full_url) if method == "GET": @@ -186,7 +178,7 @@ class ManagedBlockchainResponse(BaseResponse): elif method == "POST": json_body = json.loads(body.decode("utf-8")) return self._proposal_votes_response_post( - network_id, proposal_id, json_body, querystring, headers + network_id, proposal_id, json_body, headers ) def _all_proposal_votes_response(self, network_id, proposal_id, headers): @@ -196,7 +188,7 @@ class ManagedBlockchainResponse(BaseResponse): return 200, headers, response def _proposal_votes_response_post( - self, network_id, proposal_id, json_body, querystring, headers + self, network_id, proposal_id, json_body, headers ): votermemberid = json_body["VoterMemberId"] vote = json_body["Vote"] @@ -211,14 +203,14 @@ class ManagedBlockchainResponse(BaseResponse): response_instance = ManagedBlockchainResponse( managedblockchain_backends[region_name] ) - return response_instance._invitation_response(request, full_url, headers) + return response_instance._invitation_response(request, headers) - def _invitation_response(self, request, full_url, headers): + def _invitation_response(self, request, headers): method = request.method if method == "GET": - return self._all_invitation_response(request, full_url, headers) + return self._all_invitation_response(headers) - def _all_invitation_response(self, request, full_url, headers): + def _all_invitation_response(self, headers): invitations = self.backend.list_invitations() response = json.dumps( {"Invitations": [invitation.to_dict() for invitation in invitations]} @@ -261,16 +253,12 @@ class ManagedBlockchainResponse(BaseResponse): body = request.body else: body = request.data - parsed_url = urlparse(full_url) - querystring = parse_qs(parsed_url.query, keep_blank_values=True) network_id = networkid_from_managedblockchain_url(full_url) if method == "GET": return self._all_members_response(network_id, headers) elif method == "POST": json_body = json.loads(body.decode("utf-8")) - return self._member_response_post( - network_id, json_body, querystring, headers - ) + return self._member_response_post(network_id, json_body, headers) def _all_members_response(self, network_id, headers): members = self.backend.list_members(network_id) @@ -278,7 +266,7 @@ class ManagedBlockchainResponse(BaseResponse): headers["content-type"] = "application/json" return 200, headers, response - def _member_response_post(self, network_id, json_body, querystring, headers): + def _member_response_post(self, network_id, json_body, headers): invitationid = json_body["InvitationId"] member_configuration = json_body["MemberConfiguration"] @@ -356,9 +344,7 @@ class ManagedBlockchainResponse(BaseResponse): return self._all_nodes_response(network_id, member_id, status, headers) elif method == "POST": json_body = json.loads(body.decode("utf-8")) - return self._node_response_post( - network_id, member_id, json_body, querystring, headers - ) + return self._node_response_post(network_id, member_id, json_body, headers) def _all_nodes_response(self, network_id, member_id, status, headers): nodes = self.backend.list_nodes(network_id, member_id, status) @@ -366,9 +352,7 @@ class ManagedBlockchainResponse(BaseResponse): headers["content-type"] = "application/json" return 200, headers, response - def _node_response_post( - self, network_id, member_id, json_body, querystring, headers - ): + def _node_response_post(self, network_id, member_id, json_body, headers): instancetype = json_body["NodeConfiguration"]["InstanceType"] availabilityzone = json_body["NodeConfiguration"]["AvailabilityZone"] logpublishingconfiguration = json_body["NodeConfiguration"][ diff --git a/moto/mediaconnect/models.py b/moto/mediaconnect/models.py index b63260071..0bd6ff3e1 100644 --- a/moto/mediaconnect/models.py +++ b/moto/mediaconnect/models.py @@ -7,7 +7,7 @@ from moto.mediaconnect.exceptions import NotFoundException class Flow(BaseModel): - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): self.availability_zone = kwargs.get("availability_zone") self.entitlements = kwargs.get("entitlements", []) self.name = kwargs.get("name") @@ -59,7 +59,7 @@ class Flow(BaseModel): class Resource(BaseModel): - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): self.resource_arn = kwargs.get("resource_arn") self.tags = OrderedDict() diff --git a/moto/medialive/models.py b/moto/medialive/models.py index 21ea0dd83..38a4ae0ac 100644 --- a/moto/medialive/models.py +++ b/moto/medialive/models.py @@ -6,7 +6,7 @@ from moto.core.utils import BackendDict class Input(BaseModel): - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): self.arn = kwargs.get("arn") self.attached_channels = kwargs.get("attached_channels", []) self.destinations = kwargs.get("destinations", []) @@ -54,7 +54,7 @@ class Input(BaseModel): class Channel(BaseModel): - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): self.arn = kwargs.get("arn") self.cdi_input_specification = kwargs.get("cdi_input_specification") self.channel_class = kwargs.get("channel_class", "STANDARD") @@ -134,11 +134,12 @@ class MediaLiveBackend(BaseBackend): input_specification, log_level, name, - request_id, - reserved, role_arn, tags, ): + """ + The RequestID and Reserved parameters are not yet implemented + """ channel_id = uuid4().hex arn = "arn:aws:medialive:channel:{}".format(channel_id) channel = Channel( @@ -225,13 +226,14 @@ class MediaLiveBackend(BaseBackend): input_security_groups, media_connect_flows, name, - request_id, role_arn, sources, tags, input_type, - vpc, ): + """ + The VPC and RequestId parameters are not yet implemented + """ input_id = uuid4().hex arn = "arn:aws:medialive:input:{}".format(input_id) a_input = Input( diff --git a/moto/medialive/responses.py b/moto/medialive/responses.py index f22e83e30..9d75eb4b8 100644 --- a/moto/medialive/responses.py +++ b/moto/medialive/responses.py @@ -19,8 +19,6 @@ class MediaLiveResponse(BaseResponse): input_specification = self._get_param("inputSpecification") log_level = self._get_param("logLevel") name = self._get_param("name") - request_id = self._get_param("requestId") - reserved = self._get_param("reserved") role_arn = self._get_param("roleArn") tags = self._get_param("tags") channel = self.medialive_backend.create_channel( @@ -32,8 +30,6 @@ class MediaLiveResponse(BaseResponse): input_specification=input_specification, log_level=log_level, name=name, - request_id=request_id, - reserved=reserved, role_arn=role_arn, tags=tags, ) @@ -98,24 +94,20 @@ class MediaLiveResponse(BaseResponse): input_security_groups = self._get_param("inputSecurityGroups") media_connect_flows = self._get_param("mediaConnectFlows") name = self._get_param("name") - request_id = self._get_param("requestId") role_arn = self._get_param("roleArn") sources = self._get_param("sources") tags = self._get_param("tags") input_type = self._get_param("type") - vpc = self._get_param("vpc") a_input = self.medialive_backend.create_input( destinations=destinations, input_devices=input_devices, input_security_groups=input_security_groups, media_connect_flows=media_connect_flows, name=name, - request_id=request_id, role_arn=role_arn, sources=sources, tags=tags, input_type=input_type, - vpc=vpc, ) return json.dumps({"input": a_input.to_dict()}) diff --git a/moto/mediapackage/models.py b/moto/mediapackage/models.py index 82b49521b..fd2ffd3b0 100644 --- a/moto/mediapackage/models.py +++ b/moto/mediapackage/models.py @@ -7,7 +7,7 @@ from .exceptions import ClientError class Channel(BaseModel): - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): self.arn = kwargs.get("arn") self.channel_id = kwargs.get("channel_id") self.description = kwargs.get("description") @@ -27,7 +27,7 @@ class Channel(BaseModel): class OriginEndpoint(BaseModel): - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): self.arn = kwargs.get("arn") self.authorization = kwargs.get("authorization") self.channel_id = kwargs.get("channel_id") diff --git a/moto/mediastore/models.py b/moto/mediastore/models.py index 9b8091553..5e256cc80 100644 --- a/moto/mediastore/models.py +++ b/moto/mediastore/models.py @@ -11,7 +11,7 @@ from .exceptions import ( class Container(BaseModel): - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): self.arn = kwargs.get("arn") self.name = kwargs.get("name") self.endpoint = kwargs.get("endpoint") @@ -74,7 +74,10 @@ class MediaStoreBackend(BaseBackend): container.status = "ACTIVE" return container - def list_containers(self, next_token, max_results): + def list_containers(self): + """ + Pagination is not yet implemented + """ containers = list(self._containers.values()) response_containers = [c.to_dict() for c in containers] return response_containers, None diff --git a/moto/mediastore/responses.py b/moto/mediastore/responses.py index 3dd3d1771..5d55c179f 100644 --- a/moto/mediastore/responses.py +++ b/moto/mediastore/responses.py @@ -28,11 +28,7 @@ class MediaStoreResponse(BaseResponse): return json.dumps(dict(Container=container.to_dict())) def list_containers(self): - next_token = self._get_param("NextToken") - max_results = self._get_int_param("MaxResults") - containers, next_token = self.mediastore_backend.list_containers( - next_token=next_token, max_results=max_results - ) + containers, next_token = self.mediastore_backend.list_containers() return json.dumps(dict(dict(Containers=containers), NextToken=next_token)) def list_tags_for_resource(self): diff --git a/moto/mediastoredata/models.py b/moto/mediastoredata/models.py index 33cb03e83..04953d455 100644 --- a/moto/mediastoredata/models.py +++ b/moto/mediastoredata/models.py @@ -39,15 +39,10 @@ class MediaStoreDataBackend(BaseBackend): self.__dict__ = {} self.__init__(region_name) - def put_object( - self, - body, - path, - content_type=None, - cache_control=None, - storage_class="TEMPORAL", - upload_availability="STANDARD", - ): + def put_object(self, body, path, storage_class="TEMPORAL"): + """ + The following parameters are not yet implemented: ContentType, CacheControl, UploadAvailability + """ new_object = Object( path=path, body=body, etag="etag", storage_class=storage_class ) @@ -61,7 +56,7 @@ class MediaStoreDataBackend(BaseBackend): del self._objects[path] return {} - def get_object(self, path, object_range=None): + def get_object(self, path): """ The Range-parameter is not yet supported. """ @@ -71,7 +66,7 @@ class MediaStoreDataBackend(BaseBackend): raise ClientError(error, "Object with id={} not found".format(path)) return objects_found[0] - def list_items(self, path, max_results=1000, next_token=None): + def list_items(self): """ The Path- and MaxResults-parameters are not yet supported. """ diff --git a/moto/mediastoredata/responses.py b/moto/mediastoredata/responses.py index 9354fb80b..2803e0913 100644 --- a/moto/mediastoredata/responses.py +++ b/moto/mediastoredata/responses.py @@ -13,10 +13,7 @@ class MediaStoreDataResponse(BaseResponse): def get_object(self): path = self._get_param("Path") - object_range = self._get_param("Range") - result = self.mediastoredata_backend.get_object( - path=path, object_range=object_range - ) + result = self.mediastoredata_backend.get_object(path=path) headers = {"Path": result.path} return result.body, headers @@ -33,11 +30,5 @@ class MediaStoreDataResponse(BaseResponse): return json.dumps(result) def list_items(self): - path = self._get_param("Path") - max_results = self._get_param("MaxResults") - next_token = self._get_param("NextToken") - items = self.mediastoredata_backend.list_items( - path=path, max_results=max_results, next_token=next_token - ) - response_items = json.dumps(dict(Items=items)) - return response_items + items = self.mediastoredata_backend.list_items() + return json.dumps(dict(Items=items)) diff --git a/moto/mq/models.py b/moto/mq/models.py index 530b90bfc..48f9ac386 100644 --- a/moto/mq/models.py +++ b/moto/mq/models.py @@ -368,7 +368,6 @@ class MQBackend(BaseBackend): auto_minor_version_upgrade, broker_name, configuration, - creator_request_id, deployment_mode, encryption_options, engine_type, diff --git a/moto/mq/responses.py b/moto/mq/responses.py index 06276f55f..69331ecec 100644 --- a/moto/mq/responses.py +++ b/moto/mq/responses.py @@ -95,7 +95,6 @@ class MQResponse(BaseResponse): auto_minor_version_upgrade = params.get("autoMinorVersionUpgrade") broker_name = params.get("brokerName") configuration = params.get("configuration") - creator_request_id = params.get("creatorRequestId") deployment_mode = params.get("deploymentMode") encryption_options = params.get("encryptionOptions") engine_type = params.get("engineType") @@ -115,7 +114,6 @@ class MQResponse(BaseResponse): auto_minor_version_upgrade=auto_minor_version_upgrade, broker_name=broker_name, configuration=configuration, - creator_request_id=creator_request_id, deployment_mode=deployment_mode, encryption_options=encryption_options, engine_type=engine_type, diff --git a/moto/organizations/models.py b/moto/organizations/models.py index 02bedd196..11aabae16 100644 --- a/moto/organizations/models.py +++ b/moto/organizations/models.py @@ -379,7 +379,7 @@ class OrganizationsBackend(BaseBackend): raise AWSOrganizationsNotInUseException return self.org.describe() - def delete_organization(self, **kwargs): + def delete_organization(self): if [account for account in self.accounts if account.name != "master"]: raise RESTError( "OrganizationNotEmptyException", @@ -612,7 +612,7 @@ class OrganizationsBackend(BaseBackend): else: raise InvalidInputException("You specified an invalid value.") - def list_policies(self, **kwargs): + def list_policies(self): return dict( Policies=[p.describe()["Policy"]["PolicySummary"] for p in self.policies] ) diff --git a/moto/organizations/responses.py b/moto/organizations/responses.py index 049878db3..8734ab10f 100644 --- a/moto/organizations/responses.py +++ b/moto/organizations/responses.py @@ -16,8 +16,8 @@ class OrganizationsResponse(BaseResponse): except ValueError: return {} - def _get_param(self, param, default=None): - return self.request_params.get(param, default) + def _get_param(self, param_name, if_none=None): + return self.request_params.get(param_name, if_none) def create_organization(self): return json.dumps( @@ -28,9 +28,7 @@ class OrganizationsResponse(BaseResponse): return json.dumps(self.organizations_backend.describe_organization()) def delete_organization(self): - return json.dumps( - self.organizations_backend.delete_organization(**self.request_params) - ) + return json.dumps(self.organizations_backend.delete_organization()) def list_roots(self): return json.dumps(self.organizations_backend.list_roots()) @@ -125,9 +123,7 @@ class OrganizationsResponse(BaseResponse): ) def list_policies(self): - return json.dumps( - self.organizations_backend.list_policies(**self.request_params) - ) + return json.dumps(self.organizations_backend.list_policies()) def delete_policy(self): self.organizations_backend.delete_policy(**self.request_params) diff --git a/moto/polly/models.py b/moto/polly/models.py index 3a9c3823a..7238968e7 100644 --- a/moto/polly/models.py +++ b/moto/polly/models.py @@ -75,7 +75,10 @@ class PollyBackend(BaseBackend): self.__dict__ = {} self.__init__(region_name) - def describe_voices(self, language_code, next_token): + def describe_voices(self, language_code): + """ + Pagination is not yet implemented + """ if language_code is None: return VOICE_DATA @@ -89,7 +92,10 @@ class PollyBackend(BaseBackend): # Raises KeyError return self._lexicons[name] - def list_lexicons(self, next_token): + def list_lexicons(self): + """ + Pagination is not yet implemented + """ result = [] diff --git a/moto/polly/responses.py b/moto/polly/responses.py index 16e897ce5..39ecc7385 100644 --- a/moto/polly/responses.py +++ b/moto/polly/responses.py @@ -34,7 +34,6 @@ class PollyResponse(BaseResponse): # DescribeVoices def voices(self): language_code = self._get_param("LanguageCode") - next_token = self._get_param("NextToken") if language_code is not None and language_code not in LANGUAGE_CODES: msg = ( @@ -45,7 +44,7 @@ class PollyResponse(BaseResponse): ) return msg, dict(status=400) - voices = self.polly_backend.describe_voices(language_code, next_token) + voices = self.polly_backend.describe_voices(language_code) return json.dumps({"Voices": voices}) @@ -83,9 +82,7 @@ class PollyResponse(BaseResponse): # ListLexicons def _get_lexicons_list(self): - next_token = self._get_param("NextToken") - - result = {"Lexicons": self.polly_backend.list_lexicons(next_token)} + result = {"Lexicons": self.polly_backend.list_lexicons()} return json.dumps(result) diff --git a/moto/rds/models.py b/moto/rds/models.py index 852746d82..2a45751ec 100644 --- a/moto/rds/models.py +++ b/moto/rds/models.py @@ -619,8 +619,8 @@ class Database(CloudFormationModel): setattr(self, key, value) @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Endpoint.Address", "Endpoint.Port"] + def has_cfn_attr(cls, attr): + return attr in ["Endpoint.Address", "Endpoint.Port"] def get_cfn_attribute(self, attribute_name): # Local import to avoid circular dependency with cloudformation.parsing @@ -1646,11 +1646,7 @@ class RDSBackend(BaseBackend): return default_option_group_options[engine_name]["all"] def modify_option_group( - self, - option_group_name, - options_to_include=None, - options_to_remove=None, - apply_immediately=None, + self, option_group_name, options_to_include=None, options_to_remove=None ): if option_group_name not in self.option_groups: raise OptionGroupNotFoundFaultError(option_group_name) @@ -2094,12 +2090,12 @@ class OptionGroup(object): ) return template.render(option_group=self) - def remove_options(self, options_to_remove): + def remove_options(self, options_to_remove): # pylint: disable=unused-argument # TODO: Check for option in self.options and remove if exists. Raise # error otherwise return - def add_options(self, options_to_add): + def add_options(self, options_to_add): # pylint: disable=unused-argument # TODO: Validate option and add it to self.options. If invalid raise # error return diff --git a/moto/rds/responses.py b/moto/rds/responses.py index da5585fa2..03fa1cf36 100644 --- a/moto/rds/responses.py +++ b/moto/rds/responses.py @@ -432,9 +432,8 @@ class RDSResponse(BaseResponse): self._get_param("OptionsToRemove.member.{0}".format(count)) ) count += 1 - apply_immediately = self._get_param("ApplyImmediately") option_group = self.backend.modify_option_group( - option_group_name, options_to_include, options_to_remove, apply_immediately + option_group_name, options_to_include, options_to_remove ) template = self.response_template(MODIFY_OPTION_GROUP_TEMPLATE) return template.render(option_group=option_group) diff --git a/moto/redshift/models.py b/moto/redshift/models.py index 04316ae2a..3b75a1cd9 100644 --- a/moto/redshift/models.py +++ b/moto/redshift/models.py @@ -212,8 +212,8 @@ class Cluster(TaggableResourceMixin, CloudFormationModel): return cluster @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["Endpoint.Address", "Endpoint.Port"] + def has_cfn_attr(cls, attr): + return attr in ["Endpoint.Address", "Endpoint.Port"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException diff --git a/moto/resourcegroups/models.py b/moto/resourcegroups/models.py index b2711a441..e498875b6 100644 --- a/moto/resourcegroups/models.py +++ b/moto/resourcegroups/models.py @@ -330,15 +330,12 @@ class ResourceGroupsBackend(BaseBackend): def get_tags(self, arn): return self.groups.by_arn[arn].tags - # def list_group_resources(self): - # ... - - def list_groups(self, filters=None, max_results=None, next_token=None): + def list_groups(self): + """ + Pagination or the Filters-parameter is not yet implemented + """ return self.groups.by_name - # def search_resources(self): - # ... - def tag(self, arn, tags): all_tags = self.groups.by_arn[arn].tags all_tags.update(tags) diff --git a/moto/resourcegroups/responses.py b/moto/resourcegroups/responses.py index 0073e0fbd..19042e2fd 100644 --- a/moto/resourcegroups/responses.py +++ b/moto/resourcegroups/responses.py @@ -1,9 +1,6 @@ import json -try: - from urllib import unquote -except ImportError: - from urllib.parse import unquote +from urllib.parse import unquote from moto.core.responses import BaseResponse from .models import resourcegroups_backends @@ -95,16 +92,7 @@ class ResourceGroupsResponse(BaseResponse): ) def list_groups(self): - filters = self._get_param("Filters") - if filters: - raise NotImplementedError( - "ResourceGroups.list_groups with filter parameter is not yet implemented" - ) - max_results = self._get_int_param("MaxResults", 50) - next_token = self._get_param("NextToken") - groups = self.resourcegroups_backend.list_groups( - filters=filters, max_results=max_results, next_token=next_token - ) + groups = self.resourcegroups_backend.list_groups() return json.dumps( { "GroupIdentifiers": [ @@ -119,7 +107,7 @@ class ResourceGroupsResponse(BaseResponse): } for group in groups.values() ], - "NextToken": next_token, + "NextToken": None, } ) diff --git a/moto/resourcegroupstaggingapi/models.py b/moto/resourcegroupstaggingapi/models.py index 2d2ed8deb..bf214741a 100644 --- a/moto/resourcegroupstaggingapi/models.py +++ b/moto/resourcegroupstaggingapi/models.py @@ -299,7 +299,7 @@ class ResourceGroupsTaggingAPIBackend(BaseBackend): # ELB, resource type elasticloadbalancing:loadbalancer def get_elbv2_tags(arn): result = [] - for key, value in self.elbv2_backend.load_balancers[elb.arn].tags.items(): + for key, value in self.elbv2_backend.load_balancers[arn].tags.items(): result.append({"Key": key, "Value": value}) return result @@ -318,9 +318,7 @@ class ResourceGroupsTaggingAPIBackend(BaseBackend): # ELB Target Group, resource type elasticloadbalancing:targetgroup def get_target_group_tags(arn): result = [] - for key, value in self.elbv2_backend.target_groups[ - target_group.arn - ].tags.items(): + for key, value in self.elbv2_backend.target_groups[arn].tags.items(): result.append({"Key": key, "Value": value}) return result diff --git a/moto/route53/models.py b/moto/route53/models.py index 9fad2fd21..812fd0b93 100644 --- a/moto/route53/models.py +++ b/moto/route53/models.py @@ -213,7 +213,7 @@ class RecordSet(CloudFormationModel): def physical_resource_id(self): return self.name - def delete(self, *args, **kwargs): + def delete(self, *args, **kwargs): # pylint: disable=unused-argument """Not exposed as part of the Route 53 API - used for CloudFormation. args are ignored""" hosted_zone = route53_backend.get_hosted_zone_by_name(self.hosted_zone_name) if not hosted_zone: @@ -518,13 +518,15 @@ class Route53Backend(BaseBackend): zones = sorted(zones, key=sort_key) return dnsname, zones - def list_hosted_zones_by_vpc(self, VPCId, VPCRegion, MaxItems=None, NextToken=None): - + def list_hosted_zones_by_vpc(self, vpc_id): + """ + Pagination is not yet implemented + """ zone_list = [] for zone in self.list_hosted_zones(): if zone.private_zone == "true": this_zone = self.get_hosted_zone(zone.id) - if this_zone.vpcid == VPCId: + if this_zone.vpcid == vpc_id: this_id = f"/hostedzone/{zone.id}" zone_list.append( { diff --git a/moto/route53/responses.py b/moto/route53/responses.py index 2c5c6665b..cd3dc8f4e 100644 --- a/moto/route53/responses.py +++ b/moto/route53/responses.py @@ -90,8 +90,7 @@ class Route53(BaseResponse): parsed_url = urlparse(full_url) query_params = parse_qs(parsed_url.query) vpc_id = query_params.get("vpcid")[0] - vpc_region = query_params.get("vpcregion")[0] - zones = route53_backend.list_hosted_zones_by_vpc(vpc_id, vpc_region) + zones = route53_backend.list_hosted_zones_by_vpc(vpc_id) template = Template(LIST_HOSTED_ZONES_BY_VPC_RESPONSE) return 200, headers, template.render(zones=zones, xmlns=XMLNS) diff --git a/moto/s3/models.py b/moto/s3/models.py index 00fc9b641..c95d133fc 100644 --- a/moto/s3/models.py +++ b/moto/s3/models.py @@ -1109,8 +1109,8 @@ class FakeBucket(CloudFormationModel): self.accelerate_configuration = accelerate_config @classmethod - def has_cfn_attr(cls, attribute): - return attribute in [ + def has_cfn_attr(cls, attr): + return attr in [ "Arn", "DomainName", "DualStackDomainName", @@ -1464,14 +1464,7 @@ class S3Backend(BaseBackend, CloudWatchMetricProvider): return self.get_bucket(bucket_name).encryption def list_object_versions( - self, - bucket_name, - delimiter=None, - encoding_type=None, - key_marker=None, - max_keys=None, - version_id_marker=None, - prefix="", + self, bucket_name, delimiter=None, key_marker=None, prefix="" ): bucket = self.get_bucket(bucket_name) @@ -1521,7 +1514,7 @@ class S3Backend(BaseBackend, CloudWatchMetricProvider): def put_bucket_policy(self, bucket_name, policy): self.get_bucket(bucket_name).policy = policy - def delete_bucket_policy(self, bucket_name, body): + def delete_bucket_policy(self, bucket_name): bucket = self.get_bucket(bucket_name) bucket.policy = None diff --git a/moto/s3/responses.py b/moto/s3/responses.py index 3c53d4ea8..cfb561040 100644 --- a/moto/s3/responses.py +++ b/moto/s3/responses.py @@ -135,7 +135,7 @@ def parse_key_name(pth): return pth[1:] if pth.startswith("/") else pth -def is_delete_keys(request, path, bucket_name): +def is_delete_keys(request, path): # GOlang sends a request as url/?delete= (treating it as a normal key=value, even if the value is empty) # Python sends a request as url/?delete (treating it as a flag) # https://github.com/spulec/moto/issues/2937 @@ -222,7 +222,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): def is_delete_keys(self, request, path, bucket_name): if self.subdomain_based_buckets(request): - return is_delete_keys(request, path, bucket_name) + return is_delete_keys(request, path) else: return bucketpath_is_delete_keys(request, path, bucket_name) @@ -248,7 +248,9 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): return self.bucket_response(request, full_url, headers) @amzn_request_id - def bucket_response(self, request, full_url, headers): + def bucket_response( + self, request, full_url, headers + ): # pylint: disable=unused-argument self.method = request.method self.path = self._get_path(request) # Make a copy of request.headers because it's immutable @@ -256,7 +258,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): if "Host" not in self.headers: self.headers["Host"] = urlparse(full_url).netloc try: - response = self._bucket_response(request, full_url, headers) + response = self._bucket_response(request, full_url) except S3ClientError as s3error: response = s3error.code, {}, s3error.description @@ -273,7 +275,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): return status_code, headers, response_content - def _bucket_response(self, request, full_url, headers): + def _bucket_response(self, request, full_url): querystring = self._get_querystring(full_url) method = request.method region_name = parse_region_from_url(full_url) @@ -306,7 +308,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): request, body, region_name, bucket_name, querystring ) elif method == "DELETE": - return self._bucket_response_delete(body, bucket_name, querystring) + return self._bucket_response_delete(bucket_name, querystring) elif method == "POST": return self._bucket_response_post(request, body, bucket_name) elif method == "OPTIONS": @@ -513,11 +515,8 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): elif "versions" in querystring: delimiter = querystring.get("delimiter", [None])[0] - encoding_type = querystring.get("encoding-type", [None])[0] key_marker = querystring.get("key-marker", [None])[0] - max_keys = querystring.get("max-keys", [None])[0] prefix = querystring.get("prefix", [""])[0] - version_id_marker = querystring.get("version-id-marker", [None])[0] bucket = self.backend.get_bucket(bucket_name) ( @@ -525,13 +524,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): common_prefixes, delete_markers, ) = self.backend.list_object_versions( - bucket_name, - delimiter=delimiter, - encoding_type=encoding_type, - key_marker=key_marker, - max_keys=max_keys, - version_id_marker=version_id_marker, - prefix=prefix, + bucket_name, delimiter=delimiter, key_marker=key_marker, prefix=prefix ) key_list = versions template = self.response_template(S3_BUCKET_GET_VERSIONS) @@ -894,12 +887,12 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): template = self.response_template(S3_BUCKET_CREATE_RESPONSE) return 200, {}, template.render(bucket=new_bucket) - def _bucket_response_delete(self, body, bucket_name, querystring): + def _bucket_response_delete(self, bucket_name, querystring): self._set_action("BUCKET", "DELETE", querystring) self._authenticate_and_authorize_s3_action() if "policy" in querystring: - self.backend.delete_bucket_policy(bucket_name, body) + self.backend.delete_bucket_policy(bucket_name) return 204, {}, "" elif "tagging" in querystring: self.backend.delete_bucket_tagging(bucket_name) @@ -945,7 +938,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): self.data["Action"] = "DeleteObject" self._authenticate_and_authorize_s3_action() - return self._bucket_response_delete_keys(request, body, bucket_name) + return self._bucket_response_delete_keys(body, bucket_name) self.data["Action"] = "PutObject" self._authenticate_and_authorize_s3_action() @@ -1007,7 +1000,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): else path_url(request.url) ) - def _bucket_response_delete_keys(self, request, body, bucket_name): + def _bucket_response_delete_keys(self, body, bucket_name): template = self.response_template(S3_DELETE_KEYS_RESPONSE) body_dict = xmltodict.parse(body, strip_whitespace=False) @@ -1073,7 +1066,9 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): return bytes(new_body) @amzn_request_id - def key_response(self, request, full_url, headers): + def key_response( + self, request, full_url, headers + ): # pylint: disable=unused-argument # Key and Control are lumped in because splitting out the regex is too much of a pain :/ self.method = request.method self.path = self._get_path(request) @@ -1172,9 +1167,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): bucket_name, query, key_name, headers=request.headers ) elif method == "PUT": - return self._key_response_put( - request, body, bucket_name, query, key_name, headers - ) + return self._key_response_put(request, body, bucket_name, query, key_name) elif method == "HEAD": return self._key_response_head( bucket_name, query, key_name, headers=request.headers @@ -1291,7 +1284,7 @@ class ResponseObject(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): response_headers.update(key.response_dict) return 200, response_headers, key.value - def _key_response_put(self, request, body, bucket_name, query, key_name, headers): + def _key_response_put(self, request, body, bucket_name, query, key_name): self._set_action("KEY", "PUT", query) self._authenticate_and_authorize_s3_action() diff --git a/moto/s3control/responses.py b/moto/s3control/responses.py index 78e90c1fd..9b040947a 100644 --- a/moto/s3control/responses.py +++ b/moto/s3control/responses.py @@ -23,7 +23,9 @@ def error_handler(f): class S3ControlResponse(BaseResponse): @amzn_request_id - def public_access_block(self, request, full_url, headers): + def public_access_block( + self, request, full_url, headers + ): # pylint: disable=unused-argument try: if request.method == "GET": return self.get_public_access_block(request) diff --git a/moto/sagemaker/models.py b/moto/sagemaker/models.py index db50e8140..fb2307615 100644 --- a/moto/sagemaker/models.py +++ b/moto/sagemaker/models.py @@ -74,7 +74,6 @@ class FakeProcessingJob(BaseObject): processing_inputs, processing_job_name, processing_output_config, - processing_resources, region_name, role_arn, stopping_condition, @@ -279,8 +278,8 @@ class FakeEndpoint(BaseObject, CloudFormationModel): return self.endpoint_arn @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["EndpointName"] + def has_cfn_attr(cls, attr): + return attr in ["EndpointName"] def get_cfn_attribute(self, attribute_name): # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-endpoint.html#aws-resource-sagemaker-endpoint-return-values @@ -469,8 +468,8 @@ class FakeEndpointConfig(BaseObject, CloudFormationModel): return self.endpoint_config_arn @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["EndpointConfigName"] + def has_cfn_attr(cls, attr): + return attr in ["EndpointConfigName"] def get_cfn_attribute(self, attribute_name): # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-endpointconfig.html#aws-resource-sagemaker-endpointconfig-return-values @@ -581,8 +580,8 @@ class Model(BaseObject, CloudFormationModel): return self.model_arn @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["ModelName"] + def has_cfn_attr(cls, attr): + return attr in ["ModelName"] def get_cfn_attribute(self, attribute_name): # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-model.html#aws-resource-sagemaker-model-return-values @@ -801,8 +800,8 @@ class FakeSagemakerNotebookInstance(CloudFormationModel): return self.arn @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["NotebookInstanceName"] + def has_cfn_attr(cls, attr): + return attr in ["NotebookInstanceName"] def get_cfn_attribute(self, attribute_name): # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-notebookinstance.html#aws-resource-sagemaker-notebookinstance-return-values @@ -910,8 +909,8 @@ class FakeSageMakerNotebookInstanceLifecycleConfig(BaseObject, CloudFormationMod return self.notebook_instance_lifecycle_config_arn @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["NotebookInstanceLifecycleConfigName"] + def has_cfn_attr(cls, attr): + return attr in ["NotebookInstanceLifecycleConfigName"] def get_cfn_attribute(self, attribute_name): # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-notebookinstancelifecycleconfig.html#aws-resource-sagemaker-notebookinstancelifecycleconfig-return-values @@ -1721,7 +1720,6 @@ class SageMakerModelBackend(BaseBackend): processing_inputs, processing_job_name, processing_output_config, - processing_resources, role_arn, stopping_condition, ): @@ -1732,7 +1730,6 @@ class SageMakerModelBackend(BaseBackend): processing_inputs=processing_inputs, processing_job_name=processing_job_name, processing_output_config=processing_output_config, - processing_resources=processing_resources, region_name=self.region_name, role_arn=role_arn, stopping_condition=stopping_condition, @@ -1759,8 +1756,6 @@ class SageMakerModelBackend(BaseBackend): last_modified_time_before, name_contains, status_equals, - sort_by, - sort_order, ): if next_token: try: @@ -1929,8 +1924,6 @@ class SageMakerModelBackend(BaseBackend): last_modified_time_before, name_contains, status_equals, - sort_by, - sort_order, ): if next_token: try: diff --git a/moto/sagemaker/responses.py b/moto/sagemaker/responses.py index 916ea47ea..7c40bc017 100644 --- a/moto/sagemaker/responses.py +++ b/moto/sagemaker/responses.py @@ -41,8 +41,8 @@ class SageMakerResponse(BaseResponse): models = self.sagemaker_backend.list_models(**self.request_params) return json.dumps({"Models": [model.response_object for model in models]}) - def _get_param(self, param, if_none=None): - return self.request_params.get(param, if_none) + def _get_param(self, param_name, if_none=None): + return self.request_params.get(param_name, if_none) @amzn_request_id def create_notebook_instance(self): @@ -235,7 +235,6 @@ class SageMakerResponse(BaseResponse): processing_inputs=self._get_param("ProcessingInputs"), processing_job_name=self._get_param("ProcessingJobName"), processing_output_config=self._get_param("ProcessingOutputConfig"), - processing_resources=self._get_param("ProcessingResources"), role_arn=self._get_param("RoleArn"), stopping_condition=self._get_param("StoppingCondition"), ) @@ -381,14 +380,14 @@ class SageMakerResponse(BaseResponse): return 200, {}, json.dumps({}) @amzn_request_id - def create_experiment(self, *args, **kwargs): + def create_experiment(self): response = self.sagemaker_backend.create_experiment( experiment_name=self._get_param("ExperimentName") ) return 200, {}, json.dumps(response) @amzn_request_id - def describe_experiment(self, *args, **kwargs): + def describe_experiment(self): response = self.sagemaker_backend.describe_experiment( experiment_name=self._get_param("ExperimentName") ) @@ -426,7 +425,7 @@ class SageMakerResponse(BaseResponse): return 200, {}, json.dumps(response) @amzn_request_id - def create_trial(self, *args, **kwargs): + def create_trial(self): try: response = self.sagemaker_backend.create_trial( trial_name=self._get_param("TrialName"), @@ -467,7 +466,7 @@ class SageMakerResponse(BaseResponse): return 200, {}, json.dumps(response) @amzn_request_id - def create_trial_component(self, *args, **kwargs): + def create_trial_component(self): try: response = self.sagemaker_backend.create_trial_component( trial_component_name=self._get_param("TrialComponentName"), @@ -478,7 +477,7 @@ class SageMakerResponse(BaseResponse): return err.response() @amzn_request_id - def describe_trial(self, *args, **kwargs): + def describe_trial(self): trial_name = self._get_param("TrialName") response = self.sagemaker_backend.describe_trial(trial_name) return json.dumps(response) @@ -496,25 +495,25 @@ class SageMakerResponse(BaseResponse): return 200, {}, json.dumps({}) @amzn_request_id - def describe_trial_component(self, *args, **kwargs): + def describe_trial_component(self): trial_component_name = self._get_param("TrialComponentName") response = self.sagemaker_backend.describe_trial_component(trial_component_name) return json.dumps(response) @amzn_request_id - def associate_trial_component(self, *args, **kwargs): + def associate_trial_component(self): response = self.sagemaker_backend.associate_trial_component(self.request_params) return 200, {}, json.dumps(response) @amzn_request_id - def disassociate_trial_component(self, *args, **kwargs): + def disassociate_trial_component(self): response = self.sagemaker_backend.disassociate_trial_component( self.request_params ) return 200, {}, json.dumps(response) @amzn_request_id - def list_associations(self, *args, **kwargs): + def list_associations(self, *args, **kwargs): # pylint: disable=unused-argument response = self.sagemaker_backend.list_associations(self.request_params) return 200, {}, json.dumps(response) @@ -573,8 +572,6 @@ class SageMakerResponse(BaseResponse): last_modified_time_before=self._get_param("LastModifiedTimeBefore"), name_contains=self._get_param("NameContains"), status_equals=status_equals, - sort_by=sort_by, - sort_order=sort_order, ) return 200, {}, json.dumps(response) except AWSError as err: @@ -635,8 +632,6 @@ class SageMakerResponse(BaseResponse): last_modified_time_before=self._get_param("LastModifiedTimeBefore"), name_contains=self._get_param("NameContains"), status_equals=status_equals, - sort_by=sort_by, - sort_order=sort_order, ) return 200, {}, json.dumps(response) except AWSError as err: diff --git a/moto/sdb/models.py b/moto/sdb/models.py index bc8566105..a90c78633 100644 --- a/moto/sdb/models.py +++ b/moto/sdb/models.py @@ -59,11 +59,11 @@ class SimpleDBBackend(BaseBackend): self._validate_domain_name(domain_name) self.domains[domain_name] = FakeDomain(name=domain_name) - def list_domains(self, max_number_of_domains, next_token): + def list_domains(self): """ The `max_number_of_domains` and `next_token` parameter have not been implemented yet - we simply return all domains. """ - return self.domains.keys(), None + return self.domains.keys() def delete_domain(self, domain_name): self._validate_domain_name(domain_name) @@ -81,7 +81,7 @@ class SimpleDBBackend(BaseBackend): raise UnknownDomainName() return self.domains[domain_name] - def get_attributes(self, domain_name, item_name, attribute_names, consistent_read): + def get_attributes(self, domain_name, item_name, attribute_names): """ Behaviour for the consistent_read-attribute is not yet implemented """ @@ -89,7 +89,7 @@ class SimpleDBBackend(BaseBackend): domain = self._get_domain(domain_name) return domain.get(item_name, attribute_names) - def put_attributes(self, domain_name, item_name, attributes, expected): + def put_attributes(self, domain_name, item_name, attributes): """ Behaviour for the expected-attribute is not yet implemented. """ diff --git a/moto/sdb/responses.py b/moto/sdb/responses.py index 206e180a2..9b8a5e044 100644 --- a/moto/sdb/responses.py +++ b/moto/sdb/responses.py @@ -20,24 +20,18 @@ class SimpleDBResponse(BaseResponse): return template.render() def list_domains(self): - max_number_of_domains = self._get_int_param("MaxNumberOfDomains") - next_token = self._get_param("NextToken") - domain_names, next_token = self.sdb_backend.list_domains( - max_number_of_domains=max_number_of_domains, next_token=next_token - ) + domain_names = self.sdb_backend.list_domains() template = self.response_template(LIST_DOMAINS_TEMPLATE) - return template.render(domain_names=domain_names, next_token=next_token) + return template.render(domain_names=domain_names, next_token=None) def get_attributes(self): domain_name = self._get_param("DomainName") item_name = self._get_param("ItemName") attribute_names = self._get_multi_param("AttributeName.") - consistent_read = self._get_param("ConsistentRead") attributes = self.sdb_backend.get_attributes( domain_name=domain_name, item_name=item_name, attribute_names=attribute_names, - consistent_read=consistent_read, ) template = self.response_template(GET_ATTRIBUTES_TEMPLATE) return template.render(attributes=attributes) @@ -46,12 +40,8 @@ class SimpleDBResponse(BaseResponse): domain_name = self._get_param("DomainName") item_name = self._get_param("ItemName") attributes = self._get_list_prefix("Attribute") - expected = self._get_param("Expected") self.sdb_backend.put_attributes( - domain_name=domain_name, - item_name=item_name, - attributes=attributes, - expected=expected, + domain_name=domain_name, item_name=item_name, attributes=attributes ) template = self.response_template(PUT_ATTRIBUTES_TEMPLATE) return template.render() diff --git a/moto/secretsmanager/models.py b/moto/secretsmanager/models.py index 81cdb4e6b..a1a754a78 100644 --- a/moto/secretsmanager/models.py +++ b/moto/secretsmanager/models.py @@ -45,7 +45,7 @@ def _matches(secret, filters): class SecretsManager(BaseModel): - def __init__(self, region_name, **kwargs): + def __init__(self, region_name): self.region = region_name @@ -190,7 +190,7 @@ class SecretsStore(dict): class SecretsManagerBackend(BaseBackend): - def __init__(self, region_name=None, **kwargs): + def __init__(self, region_name=None): super().__init__() self.region = region_name self.secrets = SecretsStore() @@ -292,7 +292,6 @@ class SecretsManagerBackend(BaseBackend): secret_binary=None, client_request_token=None, kms_key_id=None, - **kwargs ): # error if secret does not exist diff --git a/moto/server.py b/moto/server.py index f1227b1ec..8d1570505 100644 --- a/moto/server.py +++ b/moto/server.py @@ -13,7 +13,7 @@ from moto.moto_server.threaded_moto_server import ( # noqa # pylint: disable=un ) -def signal_handler(signum, frame): +def signal_handler(signum, frame): # pylint: disable=unused-argument sys.exit(0) diff --git a/moto/sns/models.py b/moto/sns/models.py index 5579f33d7..a0635b83e 100644 --- a/moto/sns/models.py +++ b/moto/sns/models.py @@ -77,8 +77,8 @@ class Topic(CloudFormationModel): return message_id @classmethod - def has_cfn_attr(cls, attribute): - return attribute in ["TopicName"] + def has_cfn_attr(cls, attr): + return attr in ["TopicName"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException diff --git a/moto/sqs/models.py b/moto/sqs/models.py index fe29c3987..6a8b10e3a 100644 --- a/moto/sqs/models.py +++ b/moto/sqs/models.py @@ -589,8 +589,8 @@ class Queue(CloudFormationModel): self._messages = new_messages @classmethod - def has_cfn_attr(cls, attribute_name): - return attribute_name in ["Arn", "QueueName"] + def has_cfn_attr(cls, attr): + return attr in ["Arn", "QueueName"] def get_cfn_attribute(self, attribute_name): from moto.cloudformation.exceptions import UnformattedGetAttTemplateException diff --git a/moto/ssm/models.py b/moto/ssm/models.py index 11f46c972..c853ce619 100644 --- a/moto/ssm/models.py +++ b/moto/ssm/models.py @@ -1081,11 +1081,10 @@ class SimpleSystemManagerBackend(BaseBackend): # If we've fallen out of the loop, theres no more documents. No next token. return results, "" - def describe_document_permission( - self, name, max_results=None, permission_type=None, next_token=None - ): - # Parameters max_results, permission_type, and next_token not used because - # this current implementation doesn't support pagination. + def describe_document_permission(self, name): + """ + Parameters max_results, permission_type, and next_token not yet implemented + """ document = self._get_documents(name) return document.describe_permissions() @@ -1170,7 +1169,7 @@ class SimpleSystemManagerBackend(BaseBackend): result = [] for param_name in self._parameters: - ssm_parameter = self.get_parameter(param_name, False) + ssm_parameter = self.get_parameter(param_name) if not self._match_filters(ssm_parameter, parameter_filters): continue @@ -1385,7 +1384,7 @@ class SimpleSystemManagerBackend(BaseBackend): result.append(self._parameters[k]) return result - def get_parameters(self, names, with_decryption): + def get_parameters(self, names): result = {} if len(names) > 10: @@ -1400,7 +1399,7 @@ class SimpleSystemManagerBackend(BaseBackend): for name in set(names): if name.split(":")[0] in self._parameters: try: - param = self.get_parameter(name, with_decryption) + param = self.get_parameter(name) if param is not None: result[name] = param @@ -1411,7 +1410,6 @@ class SimpleSystemManagerBackend(BaseBackend): def get_parameters_by_path( self, path, - with_decryption, recursive, filters=None, next_token=None, @@ -1426,7 +1424,7 @@ class SimpleSystemManagerBackend(BaseBackend): # difference here. path = path.rstrip("/") + "/" for param_name in self._parameters.get_keys_beginning_with(path, recursive): - parameter = self.get_parameter(param_name, with_decryption) + parameter = self.get_parameter(param_name) if not self._match_filters(parameter, filters): continue result.append(parameter) @@ -1445,7 +1443,7 @@ class SimpleSystemManagerBackend(BaseBackend): next_token = None return values, next_token - def get_parameter_history(self, name, with_decryption, next_token, max_results=50): + def get_parameter_history(self, name, next_token, max_results=50): if max_results > PARAMETER_HISTORY_MAX_RESULTS: raise ValidationException( @@ -1545,7 +1543,7 @@ class SimpleSystemManagerBackend(BaseBackend): # True if no false match (or no filters at all) return True - def get_parameter(self, name, with_decryption): + def get_parameter(self, name): name_parts = name.split(":") name_prefix = name_parts[0] diff --git a/moto/ssm/responses.py b/moto/ssm/responses.py index 96110a3ad..588a9d207 100644 --- a/moto/ssm/responses.py +++ b/moto/ssm/responses.py @@ -128,16 +128,8 @@ class SimpleSystemManagerResponse(BaseResponse): def describe_document_permission(self): name = self._get_param("Name") - max_results = self._get_param("MaxResults") - next_token = self._get_param("NextToken") - permission_type = self._get_param("PermissionType") - result = self.ssm_backend.describe_document_permission( - name=name, - max_results=max_results, - next_token=next_token, - permission_type=permission_type, - ) + result = self.ssm_backend.describe_document_permission(name=name) return json.dumps(result) def modify_document_permission(self): @@ -155,8 +147,8 @@ class SimpleSystemManagerResponse(BaseResponse): permission_type=permission_type, ) - def _get_param(self, param, default=None): - return self.request_params.get(param, default) + def _get_param(self, param_name, if_none=None): + return self.request_params.get(param_name, if_none) def delete_parameter(self): name = self._get_param("Name") @@ -186,7 +178,7 @@ class SimpleSystemManagerResponse(BaseResponse): name = self._get_param("Name") with_decryption = self._get_param("WithDecryption") - result = self.ssm_backend.get_parameter(name, with_decryption) + result = self.ssm_backend.get_parameter(name) if result is None: error = { @@ -202,7 +194,7 @@ class SimpleSystemManagerResponse(BaseResponse): names = self._get_param("Names") with_decryption = self._get_param("WithDecryption") - result = self.ssm_backend.get_parameters(names, with_decryption) + result = self.ssm_backend.get_parameters(names) response = {"Parameters": [], "InvalidParameters": []} @@ -226,7 +218,6 @@ class SimpleSystemManagerResponse(BaseResponse): result, next_token = self.ssm_backend.get_parameters_by_path( path, - with_decryption, recursive, filters, next_token=token, @@ -307,7 +298,7 @@ class SimpleSystemManagerResponse(BaseResponse): max_results = self._get_param("MaxResults", 50) result, new_next_token = self.ssm_backend.get_parameter_history( - name, with_decryption, next_token, max_results + name, next_token, max_results ) if result is None: diff --git a/moto/stepfunctions/models.py b/moto/stepfunctions/models.py index decebfe13..929459457 100644 --- a/moto/stepfunctions/models.py +++ b/moto/stepfunctions/models.py @@ -124,8 +124,8 @@ class StateMachine(CloudFormationModel): return properties @classmethod - def has_cfn_attr(cls, attribute): - return attribute in [ + def has_cfn_attr(cls, attr): + return attr in [ "Name", "DefinitionString", "RoleArn", diff --git a/moto/sts/models.py b/moto/sts/models.py index 1a12c0633..9415154e0 100644 --- a/moto/sts/models.py +++ b/moto/sts/models.py @@ -14,7 +14,7 @@ from moto.sts.utils import ( class Token(BaseModel): - def __init__(self, duration, name=None, policy=None): + def __init__(self, duration, name=None): now = datetime.datetime.utcnow() self.expiration = now + datetime.timedelta(seconds=duration) self.name = name @@ -72,8 +72,8 @@ class STSBackend(BaseBackend): token = Token(duration=duration) return token - def get_federation_token(self, name, duration, policy): - token = Token(duration=duration, name=name, policy=policy) + def get_federation_token(self, name, duration): + token = Token(duration=duration, name=name) return token def assume_role(self, **kwargs): diff --git a/moto/sts/responses.py b/moto/sts/responses.py index 4e6fcf352..4ce343f09 100644 --- a/moto/sts/responses.py +++ b/moto/sts/responses.py @@ -27,9 +27,7 @@ class TokenResponse(BaseResponse): ) name = self.querystring.get("Name")[0] - token = sts_backend.get_federation_token( - duration=duration, name=name, policy=policy - ) + token = sts_backend.get_federation_token(duration=duration, name=name) template = self.response_template(GET_FEDERATION_TOKEN_RESPONSE) return template.render(token=token, account_id=ACCOUNT_ID) diff --git a/moto/support/models.py b/moto/support/models.py index 924a17542..0407a5c4f 100644 --- a/moto/support/models.py +++ b/moto/support/models.py @@ -59,7 +59,10 @@ class SupportBackend(BaseBackend): self.__dict__ = {} self.__init__(region_name) - def describe_trusted_advisor_checks(self, language): + def describe_trusted_advisor_checks(self): + """ + The Language-parameter is not yet implemented + """ # The checks are a static response checks = ADVISOR_CHECKS["checks"] return checks @@ -159,9 +162,11 @@ class SupportBackend(BaseBackend): communication_body, cc_email_addresses, language, - issue_type, attachment_set_id, ): + """ + The IssueType-parameter is not yet implemented + """ # Random case ID random_case_id = "".join( random.choice("0123456789ABCDEFGHIJKLMabcdefghijklm") for i in range(16) @@ -185,15 +190,14 @@ class SupportBackend(BaseBackend): def describe_cases( self, case_id_list, - display_id, - after_time, - before_time, include_resolved_cases, next_token, - max_results, - language, include_communications, ): + """ + The following parameters have not yet been implemented: + DisplayID, AfterTime, BeforeTime, MaxResults, Language + """ cases = [] requested_case_ids = case_id_list or self.cases.keys() diff --git a/moto/support/responses.py b/moto/support/responses.py index eab3277e0..3246b9164 100644 --- a/moto/support/responses.py +++ b/moto/support/responses.py @@ -11,8 +11,7 @@ class SupportResponse(BaseResponse): return support_backends[self.region] def describe_trusted_advisor_checks(self): - language = self._get_param("language") - checks = self.support_backend.describe_trusted_advisor_checks(language=language) + checks = self.support_backend.describe_trusted_advisor_checks() return json.dumps({"checks": checks}) @@ -35,7 +34,6 @@ class SupportResponse(BaseResponse): communication_body = self._get_param("communicationBody") cc_email_addresses = self._get_param("ccEmailAddresses") language = self._get_param("language") - issue_type = self._get_param("issueType") attachment_set_id = self._get_param("attachmentSetId") create_case_response = self.support_backend.create_case( subject=subject, @@ -45,7 +43,6 @@ class SupportResponse(BaseResponse): communication_body=communication_body, cc_email_addresses=cc_email_addresses, language=language, - issue_type=issue_type, attachment_set_id=attachment_set_id, ) @@ -53,24 +50,14 @@ class SupportResponse(BaseResponse): def describe_cases(self): case_id_list = self._get_param("caseIdList") - display_id = self._get_param("displayId") - after_time = self._get_param("afterTime") - before_time = self._get_param("beforeTime") include_resolved_cases = self._get_param("includeResolvedCases", False) next_token = self._get_param("nextToken") - max_results = self._get_int_param("maxResults") - language = self._get_param("language") include_communications = self._get_param("includeCommunications", True) describe_cases_response = self.support_backend.describe_cases( case_id_list=case_id_list, - display_id=display_id, - after_time=after_time, - before_time=before_time, include_resolved_cases=include_resolved_cases, next_token=next_token, - max_results=max_results, - language=language, include_communications=include_communications, ) diff --git a/moto/swf/models/__init__.py b/moto/swf/models/__init__.py index 957089fd2..562ea1205 100644 --- a/moto/swf/models/__init__.py +++ b/moto/swf/models/__init__.py @@ -56,7 +56,7 @@ class SWFBackend(BaseBackend): return domains def list_open_workflow_executions( - self, domain_name, maximum_page_size, tag_filter, reverse_order, **kwargs + self, domain_name, maximum_page_size, tag_filter, reverse_order ): self._process_timeouts() domain = self._get_domain(domain_name) @@ -77,12 +77,10 @@ class SWFBackend(BaseBackend): def list_closed_workflow_executions( self, domain_name, - close_time_filter, tag_filter, close_status_filter, maximum_page_size, reverse_order, - **kwargs ): self._process_timeouts() domain = self._get_domain(domain_name) diff --git a/moto/swf/responses.py b/moto/swf/responses.py index 48ebfff91..9de26facd 100644 --- a/moto/swf/responses.py +++ b/moto/swf/responses.py @@ -156,15 +156,10 @@ class SWFResponse(BaseResponse): workflow_executions = self.swf_backend.list_closed_workflow_executions( domain_name=domain, - start_time_filter=start_time_filter, - close_time_filter=close_time_filter, - execution_filter=execution_filter, tag_filter=tag_filter, - type_filter=type_filter, + close_status_filter=close_status_filter, maximum_page_size=maximum_page_size, reverse_order=reverse_order, - workflow_id=workflow_id, - close_status_filter=close_status_filter, ) return json.dumps( @@ -200,13 +195,9 @@ class SWFResponse(BaseResponse): workflow_executions = self.swf_backend.list_open_workflow_executions( domain_name=domain, - start_time_filter=start_time_filter, - execution_filter=execution_filter, - tag_filter=tag_filter, - type_filter=type_filter, maximum_page_size=maximum_page_size, + tag_filter=tag_filter, reverse_order=reverse_order, - workflow_id=workflow_id, ) return json.dumps( diff --git a/moto/textract/models.py b/moto/textract/models.py index 64eebd324..a20b61ab8 100644 --- a/moto/textract/models.py +++ b/moto/textract/models.py @@ -43,21 +43,19 @@ class TextractBackend(BaseBackend): self.__dict__ = {} self.__init__(region_name) - def get_document_text_detection(self, job_id, max_results, next_token): + def get_document_text_detection(self, job_id): + """ + Pagination has not yet been implemented + """ job = self.async_text_detection_jobs.get(job_id) if not job: raise InvalidJobIdException() return job - def start_document_text_detection( - self, - document_location, - client_request_token, - job_tag, - notification_channel, - output_config, - kms_key_id, - ): + def start_document_text_detection(self, document_location): + """ + The following parameters have not yet been implemented: ClientRequestToken, JobTag, NotificationChannel, OutputConfig, KmsKeyID + """ if not document_location: raise InvalidParameterException() job_id = str(uuid.uuid4()) diff --git a/moto/textract/responses.py b/moto/textract/responses.py index bea2db636..332cb24c5 100644 --- a/moto/textract/responses.py +++ b/moto/textract/responses.py @@ -16,27 +16,13 @@ class TextractResponse(BaseResponse): def get_document_text_detection(self): params = json.loads(self.body) job_id = params.get("JobId") - max_results = params.get("MaxResults") - next_token = params.get("NextToken") - job = self.textract_backend.get_document_text_detection( - job_id=job_id, max_results=max_results, next_token=next_token - ).to_dict() + job = self.textract_backend.get_document_text_detection(job_id=job_id).to_dict() return json.dumps(job) def start_document_text_detection(self): params = json.loads(self.body) document_location = params.get("DocumentLocation") - client_request_token = params.get("ClientRequestToken") - job_tag = params.get("JobTag") - notification_channel = params.get("NotificationChannel") - output_config = params.get("OutputConfig") - kms_key_id = params.get("KMSKeyId") job_id = self.textract_backend.start_document_text_detection( - document_location=document_location, - client_request_token=client_request_token, - job_tag=job_tag, - notification_channel=notification_channel, - output_config=output_config, - kms_key_id=kms_key_id, + document_location=document_location ) return json.dumps(dict(JobId=job_id)) diff --git a/moto/timestreamwrite/models.py b/moto/timestreamwrite/models.py index a72378921..bb87c3cba 100644 --- a/moto/timestreamwrite/models.py +++ b/moto/timestreamwrite/models.py @@ -84,7 +84,7 @@ class TimestreamWriteBackend(BaseBackend): self.region_name = region_name self.databases = dict() - def create_database(self, database_name, kms_key_id, tags): + def create_database(self, database_name, kms_key_id): database = TimestreamDatabase(self.region_name, database_name, kms_key_id) self.databases[database_name] = database return database diff --git a/moto/timestreamwrite/responses.py b/moto/timestreamwrite/responses.py index 330aa284d..c63d9c6b4 100644 --- a/moto/timestreamwrite/responses.py +++ b/moto/timestreamwrite/responses.py @@ -16,9 +16,8 @@ class TimestreamWriteResponse(BaseResponse): def create_database(self): database_name = self._get_param("DatabaseName") kms_key_id = self._get_param("KmsKeyId") - tags = self._get_list_prefix("Tags.member") database = self.timestreamwrite_backend.create_database( - database_name=database_name, kms_key_id=kms_key_id, tags=tags + database_name=database_name, kms_key_id=kms_key_id ) return json.dumps(dict(Database=database.description())) diff --git a/moto/xray/models.py b/moto/xray/models.py index 37e3a78e1..b6535e0c7 100644 --- a/moto/xray/models.py +++ b/moto/xray/models.py @@ -161,7 +161,7 @@ class SegmentCollection(object): # Todo consolidate trace segments into a trace. # not enough working knowledge of xray to do this - def summary(self, start_time, end_time, filter_expression=None, sampling=False): + def summary(self, start_time, end_time, filter_expression=None): # This beast https://docs.aws.amazon.com/xray/latest/api/API_GetTraceSummaries.html#API_GetTraceSummaries_ResponseSyntax if filter_expression is not None: raise AWSError( @@ -231,6 +231,7 @@ class SegmentCollection(object): class XRayBackend(BaseBackend): def __init__(self, region=None): + self.region = region self._telemetry_records = [] self._segment_collection = SegmentCollection() @@ -264,12 +265,10 @@ class XRayBackend(BaseBackend): seg_id=segment.id, code="InternalFailure", message=str(err) ) - def get_trace_summary(self, start_time, end_time, filter_expression, summaries): - return self._segment_collection.summary( - start_time, end_time, filter_expression, summaries - ) + def get_trace_summary(self, start_time, end_time, filter_expression): + return self._segment_collection.summary(start_time, end_time, filter_expression) - def get_trace_ids(self, trace_ids, next_token): + def get_trace_ids(self, trace_ids): traces, unprocessed_ids = self._segment_collection.get_trace_ids(trace_ids) result = {"Traces": [], "UnprocessedTraceIds": unprocessed_ids} diff --git a/moto/xray/responses.py b/moto/xray/responses.py index d4611c0f2..94d6a452f 100644 --- a/moto/xray/responses.py +++ b/moto/xray/responses.py @@ -24,8 +24,8 @@ class XRayResponse(BaseResponse): except ValueError: return {} - def _get_param(self, param, default=None): - return self.request_params.get(param, default) + def _get_param(self, param_name, if_none=None): + return self.request_params.get(param_name, if_none) def _get_action(self): # Amazon is just calling urls like /TelemetryRecords etc... @@ -88,7 +88,6 @@ class XRayResponse(BaseResponse): ) filter_expression = self._get_param("FilterExpression") - sampling = self._get_param("Sampling", "false") == "true" try: start_time = datetime.datetime.fromtimestamp(int(start_time)) @@ -107,7 +106,7 @@ class XRayResponse(BaseResponse): try: result = self.xray_backend.get_trace_summary( - start_time, end_time, filter_expression, sampling + start_time, end_time, filter_expression ) except AWSError as err: return err.response() @@ -122,7 +121,6 @@ class XRayResponse(BaseResponse): # BatchGetTraces def traces(self): trace_ids = self._get_param("TraceIds") - next_token = self._get_param("NextToken") # not implemented yet if trace_ids is None: msg = "Parameter TraceIds is missing" @@ -132,7 +130,7 @@ class XRayResponse(BaseResponse): ) try: - result = self.xray_backend.get_trace_ids(trace_ids, next_token) + result = self.xray_backend.get_trace_ids(trace_ids) except AWSError as err: return err.response() except Exception as err: diff --git a/setup.cfg b/setup.cfg index 4c09f068f..8050ffa44 100644 --- a/setup.cfg +++ b/setup.cfg @@ -17,5 +17,5 @@ ignore-paths=moto/packages [pylint.'MESSAGES CONTROL'] disable = W,C,R,E -# Check we have any tests with duplicate names (causing them to be skipped) -enable = function-redefined, redefined-builtin, unused-variable, dangerous-default-value, super-with-arguments, W0401, W0402, W0403, W0404, W0406, W0611 +# future sensible checks = super-init-not-called, useless-else-on-loop, pointless-statement, redefined-outer-name, unspecified-encoding, undefined-loop-variable +enable = arguments-renamed, dangerous-default-value, deprecated-module, function-redefined, import-self, redefined-builtin, reimported, super-with-arguments, unused-argument, unused-import, unused-variable, wildcard-import diff --git a/tests/test_acm/test_acm.py b/tests/test_acm/test_acm.py index 33ecee990..b48897c1b 100644 --- a/tests/test_acm/test_acm.py +++ b/tests/test_acm/test_acm.py @@ -16,13 +16,18 @@ from unittest import SkipTest, mock RESOURCE_FOLDER = os.path.join(os.path.dirname(__file__), "resources") -_GET_RESOURCE = lambda x: open(os.path.join(RESOURCE_FOLDER, x), "rb").read() -CA_CRT = _GET_RESOURCE("ca.pem") -CA_KEY = _GET_RESOURCE("ca.key") -SERVER_CRT = _GET_RESOURCE("star_moto_com.pem") + + +def get_resource(filename): + return open(os.path.join(RESOURCE_FOLDER, filename), "rb").read() + + +CA_CRT = get_resource("ca.pem") +CA_KEY = get_resource("ca.key") +SERVER_CRT = get_resource("star_moto_com.pem") SERVER_COMMON_NAME = "*.moto.com" -SERVER_CRT_BAD = _GET_RESOURCE("star_moto_com-bad.pem") -SERVER_KEY = _GET_RESOURCE("star_moto_com.key") +SERVER_CRT_BAD = get_resource("star_moto_com-bad.pem") +SERVER_KEY = get_resource("star_moto_com.key") BAD_ARN = f"arn:aws:acm:us-east-2:{ACCOUNT_ID}:certificate/_0000000-0000-0000-0000-000000000000" diff --git a/tests/test_appsync/test_appsync_schema.py b/tests/test_appsync/test_appsync_schema.py index b1572d79e..0934687e8 100644 --- a/tests/test_appsync/test_appsync_schema.py +++ b/tests/test_appsync/test_appsync_schema.py @@ -4,22 +4,22 @@ import sure # noqa # pylint: disable=unused-import from moto import mock_appsync schema = """type Mutation { - putPost(id: ID!, title: String!): Post + putPost(id: ID!, title: String!): Post } "My custom post type" type Post { - id: ID! - title: String! + id: ID! + title: String! } type Query { - singlePost(id: ID!): Post + singlePost(id: ID!): Post } schema { - query: Query - mutation: Mutation + query: Query + mutation: Mutation }""" diff --git a/tests/test_core/test_decorator_calls.py b/tests/test_core/test_decorator_calls.py index 2f805dcc7..0190a44f1 100644 --- a/tests/test_core/test_decorator_calls.py +++ b/tests/test_core/test_decorator_calls.py @@ -29,7 +29,7 @@ def aws_credentials(): @pytest.mark.network -def test_context_manager(aws_credentials): +def test_context_manager(aws_credentials): # pylint: disable=unused-argument client = boto3.client("ec2", region_name="us-west-1") with pytest.raises(ClientError) as exc: client.describe_addresses() @@ -127,7 +127,7 @@ class TestWithSetup_UppercaseU(unittest.TestCase): @mock_s3 class TestWithSetup_LowercaseU: - def setup(self, *args): + def setup(self, *args): # pylint: disable=unused-argument # This method will be executed automatically using pytest s3 = boto3.client("s3", region_name="us-east-1") s3.create_bucket(Bucket="mybucket") @@ -144,7 +144,7 @@ class TestWithSetup_LowercaseU: @mock_s3 class TestWithSetupMethod: - def setup_method(self, *args): + def setup_method(self, *args): # pylint: disable=unused-argument # This method will be executed automatically using pytest s3 = boto3.client("s3", region_name="us-east-1") s3.create_bucket(Bucket="mybucket") diff --git a/tests/test_core/test_importorder.py b/tests/test_core/test_importorder.py index 6c0a8567b..9a00507d4 100644 --- a/tests/test_core/test_importorder.py +++ b/tests/test_core/test_importorder.py @@ -18,7 +18,9 @@ def aws_credentials(): environ["AWS_SESSION_TOKEN"] = "testing" -def test_mock_works_with_client_created_inside(aws_credentials): +def test_mock_works_with_client_created_inside( + aws_credentials, +): # pylint: disable=unused-argument m = mock_s3() m.start() client = boto3.client("s3", region_name="us-east-1") @@ -28,7 +30,9 @@ def test_mock_works_with_client_created_inside(aws_credentials): m.stop() -def test_mock_works_with_client_created_outside(aws_credentials): +def test_mock_works_with_client_created_outside( + aws_credentials, +): # pylint: disable=unused-argument # Create the boto3 client first outside_client = boto3.client("s3", region_name="us-east-1") @@ -46,7 +50,9 @@ def test_mock_works_with_client_created_outside(aws_credentials): m.stop() -def test_mock_works_with_resource_created_outside(aws_credentials): +def test_mock_works_with_resource_created_outside( + aws_credentials, +): # pylint: disable=unused-argument # Create the boto3 client first outside_resource = boto3.resource("s3", region_name="us-east-1") @@ -88,7 +94,9 @@ class ImportantBusinessLogic: return self._s3.list_buckets()["Buckets"] -def test_mock_works_when_replacing_client(aws_credentials): +def test_mock_works_when_replacing_client( + aws_credentials, +): # pylint: disable=unused-argument logic = ImportantBusinessLogic() diff --git a/tests/test_dynamodb_v20111205/test_server.py b/tests/test_dynamodb_v20111205/test_server.py index 7255598ca..0d88079f6 100644 --- a/tests/test_dynamodb_v20111205/test_server.py +++ b/tests/test_dynamodb_v20111205/test_server.py @@ -7,7 +7,7 @@ from moto.dynamodb_v20111205 import dynamodb_backends """ Test the different server responses -Docs: +Docs: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Appendix.APIv20111205.html """ diff --git a/tests/test_dynamodb_v20111205/test_servermode.py b/tests/test_dynamodb_v20111205/test_servermode.py index 2c2e3707a..cd5588bce 100644 --- a/tests/test_dynamodb_v20111205/test_servermode.py +++ b/tests/test_dynamodb_v20111205/test_servermode.py @@ -8,7 +8,7 @@ from uuid import uuid4 """ Test the different server responses -Docs: +Docs: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Appendix.APIv20111205.html """ diff --git a/tests/test_ec2/test_account_attributes.py b/tests/test_ec2/test_account_attributes.py index 83158c1a3..5ceb267bb 100644 --- a/tests/test_ec2/test_account_attributes.py +++ b/tests/test_ec2/test_account_attributes.py @@ -1,6 +1,6 @@ import boto3 from moto import mock_ec2 -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import @mock_ec2 diff --git a/tests/test_ec2/test_ec2_integration.py b/tests/test_ec2/test_ec2_integration.py index eb6958af5..8298eb522 100644 --- a/tests/test_ec2/test_ec2_integration.py +++ b/tests/test_ec2/test_ec2_integration.py @@ -1,5 +1,5 @@ import boto3 -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import from moto import mock_ec2, mock_kms from tests import EXAMPLE_AMI_ID diff --git a/tests/test_ec2/test_egress_only_igw.py b/tests/test_ec2/test_egress_only_igw.py index 62aa83cae..22a012d03 100644 --- a/tests/test_ec2/test_egress_only_igw.py +++ b/tests/test_ec2/test_egress_only_igw.py @@ -1,6 +1,6 @@ import boto3 import pytest -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import from botocore.exceptions import ClientError from moto import mock_ec2 diff --git a/tests/test_ec2/test_route_tables.py b/tests/test_ec2/test_route_tables.py index 7dd830f7a..ddcab39f5 100644 --- a/tests/test_ec2/test_route_tables.py +++ b/tests/test_ec2/test_route_tables.py @@ -661,7 +661,7 @@ def test_create_route_with_invalid_destination_cidr_block_parameter(): destination_cidr_block = "1000.1.0.0/20" with pytest.raises(ClientError) as ex: - route = route_table.create_route( + route_table.create_route( DestinationCidrBlock=destination_cidr_block, GatewayId=internet_gateway.id ) str(ex.value).should.equal( diff --git a/tests/test_ecr/test_ecr_policy_validation.py b/tests/test_ecr/test_ecr_policy_validation.py index ff39a75f7..71f2b3d85 100644 --- a/tests/test_ecr/test_ecr_policy_validation.py +++ b/tests/test_ecr/test_ecr_policy_validation.py @@ -117,10 +117,8 @@ def test_validate_error_extract_rules(policy): ) -@pytest.mark.parametrize( - ["rule", "rule_type"], [["not_dict", "string"]], ids=["not_dict"] -) -def test_validate_error_rule_type(rule, rule_type): +@pytest.mark.parametrize("rule", ["not_dict"], ids=["not_dict"]) +def test_validate_error_rule_type(rule): # given # when diff --git a/tests/test_efs/test_file_system.py b/tests/test_efs/test_file_system.py index 48f8199b5..9f78e6379 100644 --- a/tests/test_efs/test_file_system.py +++ b/tests/test_efs/test_file_system.py @@ -41,7 +41,7 @@ def aws_credentials(): @pytest.fixture(scope="function") -def efs(aws_credentials): +def efs(aws_credentials): # pylint: disable=unused-argument with mock_efs(): yield boto3.client("efs", region_name="us-east-1") @@ -68,7 +68,7 @@ def test_create_file_system_correct_use(efs): assert create_fs_resp["Tags"][0] == {"Key": "Name", "Value": "Test EFS Container"} assert create_fs_resp["ThroughputMode"] == "bursting" assert create_fs_resp["PerformanceMode"] == "generalPurpose" - assert create_fs_resp["Encrypted"] == False + assert create_fs_resp["Encrypted"] is False assert create_fs_resp["NumberOfMountTargets"] == 0 for key_name in ["Value", "ValueInIA", "ValueInStandard"]: assert key_name in create_fs_resp["SizeInBytes"] diff --git a/tests/test_efs/test_mount_target.py b/tests/test_efs/test_mount_target.py index 07140c790..7d07d86bb 100644 --- a/tests/test_efs/test_mount_target.py +++ b/tests/test_efs/test_mount_target.py @@ -47,13 +47,13 @@ def aws_credentials(): @pytest.fixture(scope="function") -def ec2(aws_credentials): +def ec2(aws_credentials): # pylint: disable=unused-argument with mock_ec2(): yield boto3.client("ec2", region_name="us-east-1") @pytest.fixture(scope="function") -def efs(aws_credentials): +def efs(aws_credentials): # pylint: disable=unused-argument with mock_efs(): yield boto3.client("efs", region_name="us-east-1") @@ -254,7 +254,9 @@ def test_create_mount_target_too_many_security_groups(efs, ec2, file_system, sub assert "SecurityGroupLimitExceeded" in resp["Error"]["Message"] -def test_delete_file_system_mount_targets_attached(efs, ec2, file_system, subnet): +def test_delete_file_system_mount_targets_attached( + efs, ec2, file_system, subnet +): # pylint: disable=unused-argument efs.create_mount_target( FileSystemId=file_system["FileSystemId"], SubnetId=subnet["SubnetId"] ) @@ -265,7 +267,9 @@ def test_delete_file_system_mount_targets_attached(efs, ec2, file_system, subnet assert "FileSystemInUse" in resp["Error"]["Message"] -def test_describe_mount_targets_minimal_case(efs, ec2, file_system, subnet): +def test_describe_mount_targets_minimal_case( + efs, ec2, file_system, subnet +): # pylint: disable=unused-argument create_resp = efs.create_mount_target( FileSystemId=file_system["FileSystemId"], SubnetId=subnet["SubnetId"] ) @@ -383,7 +387,7 @@ def test_delete_mount_target_minimal_case(efs, file_system, subnet): assert len(desc_resp["MountTargets"]) == 0 -def test_delete_mount_target_invalid_mount_target_id(efs, file_system, subnet): +def test_delete_mount_target_invalid_mount_target_id(efs): with pytest.raises(ClientError) as exc_info: efs.delete_mount_target(MountTargetId="fsmt-98487aef0a7") resp = exc_info.value.response diff --git a/tests/test_efs/test_server.py b/tests/test_efs/test_server.py index 867c83001..2670a3f5d 100644 --- a/tests/test_efs/test_server.py +++ b/tests/test_efs/test_server.py @@ -21,13 +21,13 @@ def aws_credentials(): @pytest.fixture(scope="function") -def efs_client(aws_credentials): +def efs_client(aws_credentials): # pylint: disable=unused-argument with mock_efs(): yield server.create_backend_app("efs").test_client() @pytest.fixture(scope="function") -def subnet_id(aws_credentials): +def subnet_id(aws_credentials): # pylint: disable=unused-argument with mock_ec2(): ec2_client = server.create_backend_app("ec2").test_client() resp = ec2_client.get("/?Action=DescribeSubnets") diff --git a/tests/test_eks/test_eks.py b/tests/test_eks/test_eks.py index cb697076f..2ec09d845 100644 --- a/tests/test_eks/test_eks.py +++ b/tests/test_eks/test_eks.py @@ -527,9 +527,7 @@ def test_create_nodegroup_throws_exception_when_nodegroup_already_exists( @mock_eks -def test_create_nodegroup_throws_exception_when_cluster_not_active( - NodegroupBuilder, monkeypatch -): +def test_create_nodegroup_throws_exception_when_cluster_not_active(NodegroupBuilder): if settings.TEST_SERVER_MODE: raise SkipTest("Cant patch Cluster attributes in server mode.") client, generated_test_data = NodegroupBuilder(BatchCountSize.SMALL) @@ -977,7 +975,7 @@ def test_create_fargate_profile_throws_exception_when_fargate_profile_already_ex @mock_eks def test_create_fargate_profile_throws_exception_when_cluster_not_active( - FargateProfileBuilder, monkeypatch + FargateProfileBuilder, ): if settings.TEST_SERVER_MODE: raise SkipTest("Cant patch Cluster attributes in server mode.") diff --git a/tests/test_elasticbeanstalk/test_eb.py b/tests/test_elasticbeanstalk/test_eb.py index 34418c4a5..ba844eccf 100644 --- a/tests/test_elasticbeanstalk/test_eb.py +++ b/tests/test_elasticbeanstalk/test_eb.py @@ -39,7 +39,7 @@ def test_describe_applications(): def test_create_environment(): # Create Elastic Beanstalk Environment conn = boto3.client("elasticbeanstalk", region_name="us-east-1") - app = conn.create_application(ApplicationName="myapp") + conn.create_application(ApplicationName="myapp") env = conn.create_environment(ApplicationName="myapp", EnvironmentName="myenv") env["EnvironmentName"].should.equal("myenv") env["EnvironmentArn"].should.contain("myapp/myenv") diff --git a/tests/test_emrcontainers/test_emrcontainers.py b/tests/test_emrcontainers/test_emrcontainers.py index e9f1e9d28..851792302 100644 --- a/tests/test_emrcontainers/test_emrcontainers.py +++ b/tests/test_emrcontainers/test_emrcontainers.py @@ -202,7 +202,9 @@ class TestListVirtualClusters: tomorrow = today + timedelta(days=1) @pytest.fixture(autouse=True) - def _setup_environment(self, client, virtual_cluster_factory): + def _setup_environment( + self, client, virtual_cluster_factory + ): # pylint: disable=unused-argument self.client = client @pytest.mark.parametrize( @@ -428,7 +430,9 @@ class TestListJobRuns: tomorrow = today + timedelta(days=1) @pytest.fixture(autouse=True) - def _setup_environment(self, client, virtual_cluster_factory, job_factory): + def _setup_environment( + self, client, virtual_cluster_factory, job_factory + ): # pylint: disable=unused-argument self.client = client self.virtual_cluster_id = virtual_cluster_factory[0] diff --git a/tests/test_iam/test_iam.py b/tests/test_iam/test_iam.py index e507ce1e4..ecbf8ce74 100644 --- a/tests/test_iam/test_iam.py +++ b/tests/test_iam/test_iam.py @@ -3979,7 +3979,7 @@ def test_policy_config_dict(): assert policy["configuration"]["defaultVersionId"] == "v2" assert policy["configuration"]["attachmentCount"] == 1 assert policy["configuration"]["permissionsBoundaryUsageCount"] == 0 - assert policy["configuration"]["isAttachable"] == True + assert policy["configuration"]["isAttachable"] is True assert policy["configuration"]["description"] == "basic_policy" assert policy["configuration"]["createDate"] is not None assert policy["configuration"]["updateDate"] is not None diff --git a/tests/test_iam/test_iam_account_aliases.py b/tests/test_iam/test_iam_account_aliases.py index 7ae0d94de..998db7f91 100644 --- a/tests/test_iam/test_iam_account_aliases.py +++ b/tests/test_iam/test_iam_account_aliases.py @@ -1,5 +1,5 @@ import boto3 -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import from moto import mock_iam diff --git a/tests/test_iam/test_iam_cloudformation.py b/tests/test_iam/test_iam_cloudformation.py index a646f832b..c80ed0e6b 100644 --- a/tests/test_iam/test_iam_cloudformation.py +++ b/tests/test_iam/test_iam_cloudformation.py @@ -1,7 +1,7 @@ import boto3 import json import yaml -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import import pytest from botocore.exceptions import ClientError diff --git a/tests/test_iam/test_iam_policies.py b/tests/test_iam/test_iam_policies.py index 305906aca..7aa035e10 100644 --- a/tests/test_iam/test_iam_policies.py +++ b/tests/test_iam/test_iam_policies.py @@ -3,7 +3,7 @@ import json import boto3 from botocore.exceptions import ClientError import pytest -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import from moto import mock_iam diff --git a/tests/test_iam/test_server.py b/tests/test_iam/test_server.py index f3906aded..83ee181f2 100644 --- a/tests/test_iam/test_server.py +++ b/tests/test_iam/test_server.py @@ -1,5 +1,5 @@ import re -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import import moto.server as server diff --git a/tests/test_kms/test_kms_boto3.py b/tests/test_kms/test_kms_boto3.py index 766f9b937..162377a4d 100644 --- a/tests/test_kms/test_kms_boto3.py +++ b/tests/test_kms/test_kms_boto3.py @@ -383,7 +383,7 @@ def test_disable_key(): client.disable_key(KeyId=key["KeyMetadata"]["KeyId"]) result = client.describe_key(KeyId=key["KeyMetadata"]["KeyId"]) - assert result["KeyMetadata"]["Enabled"] == False + assert result["KeyMetadata"]["Enabled"] is False assert result["KeyMetadata"]["KeyState"] == "Disabled" @@ -395,7 +395,7 @@ def test_enable_key(): client.enable_key(KeyId=key["KeyMetadata"]["KeyId"]) result = client.describe_key(KeyId=key["KeyMetadata"]["KeyId"]) - assert result["KeyMetadata"]["Enabled"] == True + assert result["KeyMetadata"]["Enabled"] is True assert result["KeyMetadata"]["KeyState"] == "Enabled" @@ -416,7 +416,7 @@ def test_schedule_key_deletion(): assert response["KeyId"] == key["KeyMetadata"]["KeyId"] result = client.describe_key(KeyId=key["KeyMetadata"]["KeyId"]) - assert result["KeyMetadata"]["Enabled"] == False + assert result["KeyMetadata"]["Enabled"] is False assert result["KeyMetadata"]["KeyState"] == "PendingDeletion" assert "DeletionDate" in result["KeyMetadata"] @@ -442,7 +442,7 @@ def test_schedule_key_deletion_custom(): assert response["KeyId"] == key["KeyMetadata"]["KeyId"] result = client.describe_key(KeyId=key["KeyMetadata"]["KeyId"]) - assert result["KeyMetadata"]["Enabled"] == False + assert result["KeyMetadata"]["Enabled"] is False assert result["KeyMetadata"]["KeyState"] == "PendingDeletion" assert "DeletionDate" in result["KeyMetadata"] @@ -456,7 +456,7 @@ def test_cancel_key_deletion(): assert response["KeyId"] == key["KeyMetadata"]["KeyId"] result = client.describe_key(KeyId=key["KeyMetadata"]["KeyId"]) - assert result["KeyMetadata"]["Enabled"] == False + assert result["KeyMetadata"]["Enabled"] is False assert result["KeyMetadata"]["KeyState"] == "Disabled" assert "DeletionDate" not in result["KeyMetadata"] @@ -1041,7 +1041,8 @@ def test__delete_alias__raises_if_alias_is_not_found(): ) -sort = lambda l: sorted(l, key=lambda d: d.keys()) +def sort(l): + return sorted(l, key=lambda d: d.keys()) def _check_tags(key_id, created_tags, client): diff --git a/tests/test_logs/test_logs.py b/tests/test_logs/test_logs.py index 05bf2d3b3..28d03741f 100644 --- a/tests/test_logs/test_logs.py +++ b/tests/test_logs/test_logs.py @@ -40,16 +40,6 @@ def json_policy_doc(): ) -@pytest.fixture(scope="function") -def aws_credentials(): - """Mocked AWS Credentials for moto.""" - os.environ["AWS_ACCESS_KEY_ID"] = "testing" - os.environ["AWS_SECRET_ACCESS_KEY"] = "testing" - os.environ["AWS_SECURITY_TOKEN"] = "testing" - os.environ["AWS_SESSION_TOKEN"] = "testing" - os.environ["AWS_DEFAULT_REGION"] = "us-east-1" - - @mock_logs def test_describe_metric_filters_happy_prefix(): conn = boto3.client("logs", "us-west-2") @@ -1446,7 +1436,7 @@ def test_describe_log_streams_no_prefix(): @mock_s3 @mock_logs -def test_create_export_task_happy_path(aws_credentials): +def test_create_export_task_happy_path(): log_group_name = "/aws/codebuild/blah1" destination = "mybucket" fromTime = 1611316574 @@ -1464,7 +1454,7 @@ def test_create_export_task_happy_path(aws_credentials): @mock_logs -def test_create_export_task_raises_ClientError_when_bucket_not_found(aws_credentials): +def test_create_export_task_raises_ClientError_when_bucket_not_found(): log_group_name = "/aws/codebuild/blah1" destination = "368a7022dea3dd621" fromTime = 1611316574 @@ -1482,9 +1472,7 @@ def test_create_export_task_raises_ClientError_when_bucket_not_found(aws_credent @mock_s3 @mock_logs -def test_create_export_raises_ResourceNotFoundException_log_group_not_found( - aws_credentials, -): +def test_create_export_raises_ResourceNotFoundException_log_group_not_found(): log_group_name = "/aws/codebuild/blah1" destination = "mybucket" fromTime = 1611316574 diff --git a/tests/test_s3/test_s3.py b/tests/test_s3/test_s3.py index 360e1dad9..7e128915e 100644 --- a/tests/test_s3/test_s3.py +++ b/tests/test_s3/test_s3.py @@ -1076,7 +1076,7 @@ def test_list_objects_truncated_response(): assert listed_object["Key"] == "one" assert resp["MaxKeys"] == 1 - assert resp["IsTruncated"] == True + assert resp["IsTruncated"] is True assert resp.get("Prefix") is None assert resp.get("Delimiter") is None assert "NextMarker" in resp @@ -1089,7 +1089,7 @@ def test_list_objects_truncated_response(): assert listed_object["Key"] == "three" assert resp["MaxKeys"] == 1 - assert resp["IsTruncated"] == True + assert resp["IsTruncated"] is True assert resp.get("Prefix") is None assert resp.get("Delimiter") is None assert "NextMarker" in resp @@ -1102,7 +1102,7 @@ def test_list_objects_truncated_response(): assert listed_object["Key"] == "two" assert resp["MaxKeys"] == 1 - assert resp["IsTruncated"] == False + assert resp["IsTruncated"] is False assert resp.get("Prefix") is None assert resp.get("Delimiter") is None assert "NextMarker" not in resp @@ -1121,7 +1121,7 @@ def test_list_keys_xml_escaped(): assert resp["KeyCount"] == 1 assert resp["MaxKeys"] == 1000 assert resp["Prefix"] == key_name - assert resp["IsTruncated"] == False + assert resp["IsTruncated"] is False assert "Delimiter" not in resp assert "StartAfter" not in resp assert "NextContinuationToken" not in resp @@ -1199,7 +1199,7 @@ def test_list_objects_v2_truncated_response(): assert resp["MaxKeys"] == 1 assert resp["Prefix"] == "" assert resp["KeyCount"] == 1 - assert resp["IsTruncated"] == True + assert resp["IsTruncated"] is True assert "Delimiter" not in resp assert "StartAfter" not in resp assert "Owner" not in listed_object # owner info was not requested @@ -1216,7 +1216,7 @@ def test_list_objects_v2_truncated_response(): assert resp["MaxKeys"] == 1 assert resp["Prefix"] == "" assert resp["KeyCount"] == 1 - assert resp["IsTruncated"] == True + assert resp["IsTruncated"] is True assert "Delimiter" not in resp assert "StartAfter" not in resp assert "Owner" not in listed_object @@ -1233,7 +1233,7 @@ def test_list_objects_v2_truncated_response(): assert resp["MaxKeys"] == 1 assert resp["Prefix"] == "" assert resp["KeyCount"] == 1 - assert resp["IsTruncated"] == False + assert resp["IsTruncated"] is False assert "Delimiter" not in resp assert "Owner" not in listed_object assert "StartAfter" not in resp @@ -1256,7 +1256,7 @@ def test_list_objects_v2_truncated_response_start_after(): assert resp["MaxKeys"] == 1 assert resp["Prefix"] == "" assert resp["KeyCount"] == 1 - assert resp["IsTruncated"] == True + assert resp["IsTruncated"] is True assert resp["StartAfter"] == "one" assert "Delimiter" not in resp assert "Owner" not in listed_object @@ -1274,7 +1274,7 @@ def test_list_objects_v2_truncated_response_start_after(): assert resp["MaxKeys"] == 1 assert resp["Prefix"] == "" assert resp["KeyCount"] == 1 - assert resp["IsTruncated"] == False + assert resp["IsTruncated"] is False # When ContinuationToken is given, StartAfter is ignored. This also means # AWS does not return it in the response. assert "StartAfter" not in resp @@ -1541,7 +1541,7 @@ def test_delete_versioned_bucket_returns_meta(): del_resp2 = client.delete_object( Bucket="blah", Key="test1", VersionId=del_resp["VersionId"] ) - assert del_resp2["DeleteMarker"] == True + assert del_resp2["DeleteMarker"] is True assert "VersionId" not in del_resp2 diff --git a/tests/test_s3/test_s3_cloudformation.py b/tests/test_s3/test_s3_cloudformation.py index 32da0d389..5496184a0 100644 --- a/tests/test_s3/test_s3_cloudformation.py +++ b/tests/test_s3/test_s3_cloudformation.py @@ -1,7 +1,7 @@ import json import boto3 -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import from moto import mock_s3, mock_cloudformation diff --git a/tests/test_s3/test_s3_config.py b/tests/test_s3/test_s3_config.py index 604ce6889..8927e7eaf 100644 --- a/tests/test_s3/test_s3_config.py +++ b/tests/test_s3/test_s3_config.py @@ -31,11 +31,9 @@ def test_s3_public_access_block_to_config_dict(): .public_access_block.to_config_dict() ) - convert_bool = lambda x: x == "True" for key, value in public_access_block.items(): - assert result[ - "{lowercase}{rest}".format(lowercase=key[0].lower(), rest=key[1:]) - ] == convert_bool(value) + k = "{lowercase}{rest}".format(lowercase=key[0].lower(), rest=key[1:]) + assert result[k] is (value == "True") # Verify that this resides in the full bucket's to_config_dict: full_result = s3_config_query.backends["global"].buckets["bucket1"].to_config_dict() diff --git a/tests/test_s3/test_s3_metadata.py b/tests/test_s3/test_s3_metadata.py index 7f5c73f5e..3f5c521b9 100644 --- a/tests/test_s3/test_s3_metadata.py +++ b/tests/test_s3/test_s3_metadata.py @@ -3,7 +3,7 @@ import boto3 from moto import mock_s3 from moto.s3.responses import DEFAULT_REGION_NAME -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import @mock_s3 diff --git a/tests/test_s3/test_s3_multipart.py b/tests/test_s3/test_s3_multipart.py index d54a790d5..092411768 100644 --- a/tests/test_s3/test_s3_multipart.py +++ b/tests/test_s3/test_s3_multipart.py @@ -49,12 +49,12 @@ def test_default_key_buffer_size(): os.environ["MOTO_S3_DEFAULT_KEY_BUFFER_SIZE"] = "2" # 2 bytes assert get_s3_default_key_buffer_size() == 2 fk = s3model.FakeKey("a", os.urandom(1)) # 1 byte string - assert fk._value_buffer._rolled == False + assert fk._value_buffer._rolled is False os.environ["MOTO_S3_DEFAULT_KEY_BUFFER_SIZE"] = "1" # 1 byte assert get_s3_default_key_buffer_size() == 1 fk = s3model.FakeKey("a", os.urandom(3)) # 3 byte string - assert fk._value_buffer._rolled == True + assert fk._value_buffer._rolled is True # if no MOTO_S3_DEFAULT_KEY_BUFFER_SIZE env variable is present the buffer size should be less than # S3_UPLOAD_PART_MIN_SIZE to prevent in memory caching of multi part uploads diff --git a/tests/test_s3/test_s3_storageclass.py b/tests/test_s3/test_s3_storageclass.py index 8eac2e0d2..4c71a6b33 100644 --- a/tests/test_s3/test_s3_storageclass.py +++ b/tests/test_s3/test_s3_storageclass.py @@ -1,6 +1,6 @@ import boto3 -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import from botocore.exceptions import ClientError import pytest diff --git a/tests/test_s3/test_s3_utils.py b/tests/test_s3/test_s3_utils.py index c01ba99ac..efc65bc02 100644 --- a/tests/test_s3/test_s3_utils.py +++ b/tests/test_s3/test_s3_utils.py @@ -24,7 +24,7 @@ def test_localhost_without_bucket(): expect(bucket_name_from_url("https://www.localhost:5000/def")).should.equal(None) -def test_force_ignore_subdomain_for_bucketnames(monkeypatch): +def test_force_ignore_subdomain_for_bucketnames(): with patch("moto.s3.utils.S3_IGNORE_SUBDOMAIN_BUCKETNAME", True): expect( bucket_name_from_url("https://subdomain.localhost:5000/abc/resource") diff --git a/tests/test_s3/test_server.py b/tests/test_s3/test_server.py index ac6f6dced..c572f0be4 100644 --- a/tests/test_s3/test_server.py +++ b/tests/test_s3/test_server.py @@ -1,6 +1,6 @@ import io from urllib.parse import urlparse, parse_qs -import sure # pylint: disable=unused-import +import sure # noqa # pylint: disable=unused-import from flask.testing import FlaskClient import moto.server as server diff --git a/tests/test_sns/test_subscriptions_boto3.py b/tests/test_sns/test_subscriptions_boto3.py index 1e1bf4f63..63b8c6282 100644 --- a/tests/test_sns/test_subscriptions_boto3.py +++ b/tests/test_sns/test_subscriptions_boto3.py @@ -35,11 +35,12 @@ def test_double_subscription(): resp = client.create_topic(Name="some-topic") arn = resp["TopicArn"] - do_subscribe_sqs = lambda sqs_arn: client.subscribe( - TopicArn=arn, Protocol="sqs", Endpoint=sqs_arn + resp1 = client.subscribe( + TopicArn=arn, Protocol="sqs", Endpoint="arn:aws:sqs:elasticmq:000000000000:foo" + ) + resp2 = client.subscribe( + TopicArn=arn, Protocol="sqs", Endpoint="arn:aws:sqs:elasticmq:000000000000:foo" ) - resp1 = do_subscribe_sqs("arn:aws:sqs:elasticmq:000000000000:foo") - resp2 = do_subscribe_sqs("arn:aws:sqs:elasticmq:000000000000:foo") resp1["SubscriptionArn"].should.equal(resp2["SubscriptionArn"]) diff --git a/tests/test_ssm/test_ssm_parameterstore.py b/tests/test_ssm/test_ssm_parameterstore.py index 7babff0a3..edac9f261 100644 --- a/tests/test_ssm/test_ssm_parameterstore.py +++ b/tests/test_ssm/test_ssm_parameterstore.py @@ -51,14 +51,14 @@ def test_get_key_beginning_with(): store["/b/c/d"] = "some other object" store["/a/c/d"] = "some third object" - l = list(store.get_keys_beginning_with("/a/b", recursive=False)) - l.should.equal(["/a/b/c"]) + begins_with_ab = list(store.get_keys_beginning_with("/a/b", recursive=False)) + begins_with_ab.should.equal(["/a/b/c"]) - l = list(store.get_keys_beginning_with("/a", recursive=False)) - l.should.equal([]) + begins_with_a = list(store.get_keys_beginning_with("/a", recursive=False)) + begins_with_a.should.equal([]) - l = list(store.get_keys_beginning_with("/a", recursive=True)) - set(l).should.equal({"/a/b/c", "/a/c/d"}) + begins_with_a_recursive = list(store.get_keys_beginning_with("/a", recursive=True)) + set(begins_with_a_recursive).should.equal({"/a/b/c", "/a/c/d"}) def test_get_key_beginning_with_aws(): diff --git a/tests/test_utilities/test_docker_utilities.py b/tests/test_utilities/test_docker_utilities.py index e5db048a4..a7687a4f4 100644 --- a/tests/test_utilities/test_docker_utilities.py +++ b/tests/test_utilities/test_docker_utilities.py @@ -1,4 +1,4 @@ -import sure +import sure # noqa # pylint: disable=unused-import import pytest from moto.utilities.docker_utilities import parse_image_ref diff --git a/tests/test_utilities/test_threaded_server.py b/tests/test_utilities/test_threaded_server.py index 310f128bd..8564512e8 100644 --- a/tests/test_utilities/test_threaded_server.py +++ b/tests/test_utilities/test_threaded_server.py @@ -27,7 +27,9 @@ class TestThreadedMotoServer(unittest.TestCase): def test_server_can_handle_multiple_services(self): s3_client = boto3.client("s3", endpoint_url="http://127.0.0.1:5000") - dynamodb_client = boto3.client("dynamodb", endpoint_url="http://127.0.0.1:5000") + dynamodb_client = boto3.client( + "dynamodb", endpoint_url="http://127.0.0.1:5000", region_name="us-east-1" + ) s3_client.create_bucket(Bucket="test") dynamodb_client.create_table( TableName="table1", diff --git a/tests/test_xray/test_xray_client.py b/tests/test_xray/test_xray_client.py index 81ab70f05..7307ca08b 100644 --- a/tests/test_xray/test_xray_client.py +++ b/tests/test_xray/test_xray_client.py @@ -12,7 +12,7 @@ import botocore.endpoint original_make_api_call = botocore.client.BaseClient._make_api_call original_encode_headers = botocore.endpoint.Endpoint._encode_headers -import requests +import requests # noqa # pylint: disable=all original_session_request = requests.Session.request original_session_prep_request = requests.Session.prepare_request