Admin: Using ruff format instead of black (#7502)

This commit is contained in:
Akira Noda 2024-03-22 05:17:29 +09:00 committed by GitHub
parent 8123e6d71f
commit 90bdd72555
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
386 changed files with 1555 additions and 1340 deletions

View File

@ -23,9 +23,9 @@ You should be able to run `make init` to install the dependencies and then `make
## Linting
Ensure that the correct version of black is installed (see `requirements-dev.txt`). Different versions of black will return different results.
Ensure that the correct version of ruff is installed (see `requirements-dev.txt`). Different versions of ruff will return different results.
Run `make lint` to verify whether your code confirms to the guidelines.
Use `make format` to automatically format your code, if it does not conform to `black`'s rules.
Use `make format` to automatically format your code, if it does not conform to `ruff`'s rules.
# Maintainers

View File

@ -20,17 +20,13 @@ init:
lint:
@echo "Running ruff..."
ruff check moto tests
@echo "Running black... "
$(eval black_version := $(shell grep "^black==" requirements-dev.txt | sed "s/black==//"))
@echo "(Make sure you have black-$(black_version) installed, as other versions will produce different results)"
black --check moto/ tests/
@echo "Running pylint..."
pylint -j 0 moto tests
@echo "Running MyPy..."
mypy --install-types --non-interactive
format:
black moto/ tests/
ruff format moto/ tests/
ruff check --fix moto/ tests/
test-only:

View File

@ -8,7 +8,7 @@
[![PyPI](https://img.shields.io/pypi/v/moto.svg)](https://pypi.org/project/moto/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/moto.svg)](#)
[![PyPI - Downloads](https://img.shields.io/pypi/dw/moto.svg)](https://pypistats.org/packages/moto)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Code style: Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![Financial Contributors](https://opencollective.com/moto/tiers/badge.svg)](https://opencollective.com/moto)

View File

@ -13,9 +13,9 @@ FAQ for Developers
When running the linter...
#############################
Why does black give different results?
Why does ruff give different results?
****************************************
Different versions of black produce different results.
Different versions of ruff produce different results.
The CI system uses the version set in `requirements-dev.txt`.
To ensure that our CI passes, please format the code using the same version.

View File

@ -46,13 +46,13 @@ To verify all tests pass for a specific service, for example for `s3`, run these
.. code-block:: bash
ruff moto/s3 tests/test_s3
black --check moto/s3 tests/test_s3
ruff check moto/s3 tests/test_s3
ruff format --check moto/s3 tests/test_s3
pylint moto/s3 tests/test_s3
mypy
pytest -sv tests/test_s3
If black fails, you can run the following command to automatically format the offending files:
If ruff fails, you can run the following command to automatically format the offending files:
.. code-block:: bash
@ -83,8 +83,8 @@ Then standard development on Moto can proceed, for example:
.. code-block:: bash
ruff moto/s3 tests/test_s3
black --check moto/s3 tests/test_s3
ruff check moto/s3 tests/test_s3
ruff format --check moto/s3 tests/test_s3
pylint moto/s3 tests/test_s3
mypy
pytest -sv tests/test_s3
pytest -sv tests/test_s3

View File

@ -1,4 +1,5 @@
"""Exceptions raised by the acmpca service."""
from moto.core.exceptions import JsonRESTError

View File

@ -1,4 +1,5 @@
"""ACMPCABackend class with methods for supported APIs."""
import base64
import datetime
from typing import Any, Dict, List, Optional, Tuple
@ -135,9 +136,9 @@ class CertificateAuthority(BaseModel):
"S3ObjectAcl"
not in self.revocation_configuration["CrlConfiguration"]
):
self.revocation_configuration["CrlConfiguration"][
"S3ObjectAcl"
] = "PUBLIC_READ"
self.revocation_configuration["CrlConfiguration"]["S3ObjectAcl"] = (
"PUBLIC_READ"
)
@property
def certificate_bytes(self) -> bytes:

View File

@ -1,4 +1,5 @@
"""Handles incoming acmpca requests, invokes methods, returns responses."""
import base64
import json

View File

@ -1,4 +1,5 @@
"""acmpca base URL and path."""
from .responses import ACMPCAResponse
url_bases = [

View File

@ -1,4 +1,5 @@
"""Handles incoming amp requests, invokes methods, returns responses."""
import json
from typing import Any
from urllib.parse import unquote

View File

@ -1,4 +1,5 @@
"""amp base URL and path."""
from .responses import PrometheusServiceResponse
url_bases = [

View File

@ -453,7 +453,8 @@ class Resource(CloudFormationModel):
integration_type = integration.integration_type # type: ignore[union-attr]
status, result = self.integration_parsers[integration_type].invoke(
request, integration # type: ignore[arg-type]
request,
integration, # type: ignore[arg-type]
)
return status, result
@ -704,12 +705,12 @@ class Stage(BaseModel):
updated_key = self._method_settings_translations(key)
if updated_key is not None:
if resource_path_and_method not in self.method_settings:
self.method_settings[
resource_path_and_method
] = self._get_default_method_settings()
self.method_settings[resource_path_and_method][
updated_key
] = self._convert_to_type(updated_key, value)
self.method_settings[resource_path_and_method] = (
self._get_default_method_settings()
)
self.method_settings[resource_path_and_method][updated_key] = (
self._convert_to_type(updated_key, value)
)
def _get_default_method_settings(self) -> Dict[str, Any]:
return {
@ -1004,7 +1005,6 @@ class VpcLink(BaseModel):
class RestAPI(CloudFormationModel):
PROP_ID = "id"
PROP_NAME = "name"
PROP_DESCRIPTION = "description"
@ -1462,7 +1462,6 @@ class Model(BaseModel):
class BasePathMapping(BaseModel):
# operations
OPERATION_REPLACE = "replace"
OPERATION_PATH = "path"
@ -1681,9 +1680,7 @@ class APIGatewayBackend(BaseBackend):
api.resources = {}
api.default = api.add_child("/") # Add default child
for (path, resource_doc) in sorted(
api_doc["paths"].items(), key=lambda x: x[0]
):
for path, resource_doc in sorted(api_doc["paths"].items(), key=lambda x: x[0]):
# We may want to create a path like /store/inventory
# Ensure that /store exists first, so we can use it as a parent
ancestors = path.split("/")[
@ -1715,12 +1712,12 @@ class APIGatewayBackend(BaseBackend):
path_part=path[path.rfind("/") + 1 :],
)
for (method_type, method_doc) in resource_doc.items():
for method_type, method_doc in resource_doc.items():
method_type = method_type.upper()
if method_doc.get("x-amazon-apigateway-integration") is None:
self.put_method(function_id, resource.id, method_type, None)
method_responses = method_doc.get("responses", {}).items()
for (response_code, _) in method_responses:
for response_code, _ in method_responses:
self.put_method_response(
function_id,
resource.id,
@ -2375,7 +2372,6 @@ class APIGatewayBackend(BaseBackend):
def update_base_path_mapping(
self, domain_name: str, base_path: str, patch_operations: Any
) -> BasePathMapping:
if domain_name not in self.domain_names:
raise DomainNameNotFound()

View File

@ -39,7 +39,9 @@ class APIGatewayResponse(BaseResponse):
).format(api_key_source=api_key_source),
)
def __validate_endpoint_configuration(self, endpoint_configuration: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def __validate_endpoint_configuration(
self, endpoint_configuration: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
if endpoint_configuration and "types" in endpoint_configuration:
invalid_types = list(
set(endpoint_configuration["types"]) - set(ENDPOINT_CONFIGURATION_TYPES)
@ -55,7 +57,9 @@ class APIGatewayResponse(BaseResponse):
).format(endpoint_type=invalid_types[0]),
)
def restapis(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def restapis(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "GET":
@ -101,7 +105,9 @@ class APIGatewayResponse(BaseResponse):
return 200, {}, json.dumps(rest_api.to_dict())
def __validte_rest_patch_operations(self, patch_operations: List[Dict[str, str]]) -> TYPE_RESPONSE: # type: ignore[return]
def __validte_rest_patch_operations(
self, patch_operations: List[Dict[str, str]]
) -> TYPE_RESPONSE: # type: ignore[return]
for op in patch_operations:
path = op["path"]
if "apiKeySource" in path:
@ -136,7 +142,9 @@ class APIGatewayResponse(BaseResponse):
return 200, {}, json.dumps(rest_api.to_dict())
def resources(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def resources(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
function_id = self.path.replace("/restapis/", "", 1).split("/")[0]
@ -148,7 +156,9 @@ class APIGatewayResponse(BaseResponse):
json.dumps({"item": [resource.to_dict() for resource in resources]}),
)
def gateway_response(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def gateway_response(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "PUT":
return self.put_gateway_response()
@ -157,12 +167,16 @@ class APIGatewayResponse(BaseResponse):
elif request.method == "DELETE":
return self.delete_gateway_response()
def gateway_responses(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def gateway_responses(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "GET":
return self.get_gateway_responses()
def resource_individual(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def resource_individual(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
function_id = self.path.replace("/restapis/", "", 1).split("/")[0]
resource_id = self.path.split("/")[-1]
@ -254,7 +268,9 @@ class APIGatewayResponse(BaseResponse):
return 204, {}, json.dumps(method_response.to_json()) # type: ignore[union-attr]
raise Exception(f'Unexpected HTTP method "{self.method}"')
def restapis_authorizers(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def restapis_authorizers(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
restapi_id = url_path_parts[2]
@ -304,7 +320,9 @@ class APIGatewayResponse(BaseResponse):
authorizers = self.backend.get_authorizers(restapi_id)
return 200, {}, json.dumps({"item": [a.to_json() for a in authorizers]})
def request_validators(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def request_validators(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
restapi_id = url_path_parts[2]
@ -324,7 +342,9 @@ class APIGatewayResponse(BaseResponse):
)
return 201, {}, json.dumps(validator.to_dict())
def request_validator_individual(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def request_validator_individual(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
restapi_id = url_path_parts[2]
@ -343,7 +363,9 @@ class APIGatewayResponse(BaseResponse):
)
return 200, {}, json.dumps(validator.to_dict())
def authorizers(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def authorizers(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
restapi_id = url_path_parts[2]
@ -362,7 +384,9 @@ class APIGatewayResponse(BaseResponse):
self.backend.delete_authorizer(restapi_id, authorizer_id)
return 202, {}, "{}"
def restapis_stages(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def restapis_stages(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
function_id = url_path_parts[2]
@ -393,7 +417,9 @@ class APIGatewayResponse(BaseResponse):
stages = self.backend.get_stages(function_id)
return 200, {}, json.dumps({"item": [s.to_json() for s in stages]})
def restapis_stages_tags(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def restapis_stages_tags(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
function_id = url_path_parts[4]
@ -411,7 +437,9 @@ class APIGatewayResponse(BaseResponse):
stage.tags.pop(tag, None) # type: ignore[union-attr]
return 200, {}, json.dumps({"item": ""})
def stages(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def stages(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
function_id = url_path_parts[2]
@ -448,7 +476,9 @@ class APIGatewayResponse(BaseResponse):
}
return 200, headers, json.dumps(body).encode("utf-8")
def integrations(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def integrations(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
function_id = url_path_parts[2]
@ -504,7 +534,9 @@ class APIGatewayResponse(BaseResponse):
)
return 204, {}, json.dumps(integration_response.to_json())
def integration_responses(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def integration_responses(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
function_id = url_path_parts[2]
@ -542,7 +574,9 @@ class APIGatewayResponse(BaseResponse):
)
return 204, {}, json.dumps(integration_response.to_json())
def deployments(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def deployments(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
function_id = self.path.replace("/restapis/", "", 1).split("/")[0]
@ -558,7 +592,9 @@ class APIGatewayResponse(BaseResponse):
)
return 201, {}, json.dumps(deployment.to_json())
def individual_deployment(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def individual_deployment(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
function_id = url_path_parts[2]
@ -571,7 +607,9 @@ class APIGatewayResponse(BaseResponse):
deployment = self.backend.delete_deployment(function_id, deployment_id)
return 202, {}, json.dumps(deployment.to_json())
def apikeys(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def apikeys(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "POST":
@ -611,7 +649,9 @@ class APIGatewayResponse(BaseResponse):
return 200, {}, json.dumps(apikey_resp)
def usage_plans(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def usage_plans(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "POST":
usage_plan_response = self.backend.create_usage_plan(json.loads(self.body))
@ -625,7 +665,9 @@ class APIGatewayResponse(BaseResponse):
json.dumps({"item": [u.to_json() for u in usage_plans_response]}),
)
def usage_plan_individual(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def usage_plan_individual(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
@ -644,7 +686,9 @@ class APIGatewayResponse(BaseResponse):
)
return 200, {}, json.dumps(usage_plan_response.to_json())
def usage_plan_keys(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def usage_plan_keys(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
@ -663,7 +707,9 @@ class APIGatewayResponse(BaseResponse):
json.dumps({"item": [u.to_json() for u in usage_plans_response]}),
)
def usage_plan_key_individual(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def usage_plan_key_individual(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
@ -677,7 +723,9 @@ class APIGatewayResponse(BaseResponse):
self.backend.delete_usage_plan_key(usage_plan_id, key_id)
return 202, {}, "{}"
def domain_names(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def domain_names(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "GET":
@ -732,7 +780,9 @@ class APIGatewayResponse(BaseResponse):
msg = f'Method "{self.method}" for API GW domain names not implemented'
return 404, {}, json.dumps({"error": msg})
def models(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def models(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
rest_api_id = self.path.replace("/restapis/", "", 1).split("/")[0]
@ -767,7 +817,9 @@ class APIGatewayResponse(BaseResponse):
return 200, {}, json.dumps(model_info.to_json())
return 200, {}, "{}"
def base_path_mappings(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def base_path_mappings(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
@ -790,8 +842,9 @@ class APIGatewayResponse(BaseResponse):
)
return 201, {}, json.dumps(base_path_mapping_resp.to_json())
def base_path_mapping_individual(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def base_path_mapping_individual(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
@ -813,7 +866,9 @@ class APIGatewayResponse(BaseResponse):
)
return 200, {}, json.dumps(base_path_mapping.to_json())
def vpc_link(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def vpc_link(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
url_path_parts = self.path.split("/")
vpc_link_id = url_path_parts[-1]
@ -825,7 +880,9 @@ class APIGatewayResponse(BaseResponse):
vpc_link = self.backend.get_vpc_link(vpc_link_id=vpc_link_id)
return 200, {}, json.dumps(vpc_link.to_json())
def vpc_links(self, request: Any, full_url: str, headers: Dict[str, str]) -> TYPE_RESPONSE: # type: ignore[return]
def vpc_links(
self, request: Any, full_url: str, headers: Dict[str, str]
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "GET":

View File

@ -1,4 +1,5 @@
"""ApiGatewayManagementApiBackend class with methods for supported APIs."""
from collections import defaultdict
from typing import Any, Dict

View File

@ -1,4 +1,5 @@
"""Handles incoming apigatewaymanagementapi requests, invokes methods, returns responses."""
import json
from typing import Any

View File

@ -1,4 +1,5 @@
"""apigatewaymanagementapi base URL and path."""
from .responses import ApiGatewayManagementApiResponse
url_bases = [r"https?://execute-api\.(.+)\.amazonaws\.com"]

View File

@ -1,4 +1,5 @@
"""ApiGatewayV2Backend class with methods for supported APIs."""
import hashlib
import string
from typing import Any, Dict, List, Optional, Union

View File

@ -1,4 +1,5 @@
"""Handles incoming apigatewayv2 requests, invokes methods, returns responses."""
import json
from typing import Any
from urllib.parse import unquote
@ -62,7 +63,9 @@ class ApiGatewayV2Response(BaseResponse):
if self.method == "DELETE":
return self.delete_cors_configuration()
def route_request_parameter(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def route_request_parameter(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "DELETE":
@ -102,7 +105,9 @@ class ApiGatewayV2Response(BaseResponse):
if self.method == "POST":
return self.create_integration()
def integration_response(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def integration_response(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "DELETE":
@ -112,7 +117,9 @@ class ApiGatewayV2Response(BaseResponse):
if self.method == "PATCH":
return self.update_integration_response()
def integration_responses(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def integration_responses(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "GET":
@ -138,7 +145,9 @@ class ApiGatewayV2Response(BaseResponse):
if self.method == "POST":
return self.create_route()
def route_response(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def route_response(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "DELETE":
@ -146,7 +155,9 @@ class ApiGatewayV2Response(BaseResponse):
if self.method == "GET":
return self.get_route_response()
def route_responses(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def route_responses(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if self.method == "POST":

View File

@ -1,4 +1,5 @@
"""apigatewayv2 base URL and path."""
from .responses import ApiGatewayV2Response
url_bases = [

View File

@ -1,4 +1,5 @@
"""Exceptions raised by the appconfig service."""
from moto.core.exceptions import JsonRESTError

View File

@ -189,9 +189,9 @@ class AppConfigBackend(BaseBackend):
_type=_type,
)
self.tag_resource(config_profile.arn, tags)
self.get_application(application_id).config_profiles[
config_profile.id
] = config_profile
self.get_application(application_id).config_profiles[config_profile.id] = (
config_profile
)
return config_profile
def delete_configuration_profile(self, app_id: str, config_profile_id: str) -> None:

View File

@ -1,4 +1,5 @@
"""appconfig base URL and path."""
from .responses import AppConfigResponse
url_bases = [

View File

@ -218,9 +218,9 @@ def _build_policy(p: FakeApplicationAutoscalingPolicy) -> Dict[str, Any]:
if p.policy_type == "StepScaling":
response["StepScalingPolicyConfiguration"] = p.step_scaling_policy_configuration
elif p.policy_type == "TargetTrackingScaling":
response[
"TargetTrackingScalingPolicyConfiguration"
] = p.target_tracking_scaling_policy_configuration
response["TargetTrackingScalingPolicyConfiguration"] = (
p.target_tracking_scaling_policy_configuration
)
return response

View File

@ -1,4 +1,5 @@
"""Handles incoming appsync requests, invokes methods, returns responses."""
import json
from typing import Any
from urllib.parse import unquote
@ -26,7 +27,9 @@ class AppSyncResponse(BaseResponse):
if request.method == "GET":
return self.list_graphql_apis()
def graph_ql_individual(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def graph_ql_individual(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "GET":
return self.get_graphql_api()
@ -42,14 +45,18 @@ class AppSyncResponse(BaseResponse):
if request.method == "GET":
return self.list_api_keys()
def schemacreation(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def schemacreation(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "POST":
return self.start_schema_creation()
if request.method == "GET":
return self.get_schema_creation_status()
def api_key_individual(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def api_key_individual(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "DELETE":
return self.delete_api_key()

View File

@ -1,4 +1,5 @@
"""appsync base URL and path."""
from .responses import AppSyncResponse
url_bases = [

View File

@ -36,7 +36,6 @@ class TaggableResourceMixin:
class WorkGroup(TaggableResourceMixin, BaseModel):
resource_type = "workgroup"
state = "ENABLED"

View File

@ -393,7 +393,7 @@ class FailedScheduledUpdateGroupActionRequest:
def set_string_propagate_at_launch_booleans_on_tags(
tags: List[Dict[str, Any]]
tags: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
bool_to_string = {True: "true", False: "false"}
for tag in tags:
@ -883,7 +883,9 @@ class AutoScalingBackend(BaseBackend):
self.elbv2_backend: ELBv2Backend = elbv2_backends[self.account_id][region_name]
@staticmethod
def default_vpc_endpoint_service(service_region: str, zones: List[str]) -> List[Dict[str, Any]]: # type: ignore[misc]
def default_vpc_endpoint_service(
service_region: str, zones: List[str]
) -> List[Dict[str, Any]]: # type: ignore[misc]
"""Default VPC endpoint service."""
return BaseBackend.default_vpc_endpoint_service_factory(
service_region, zones, "autoscaling"
@ -1195,7 +1197,6 @@ class AutoScalingBackend(BaseBackend):
def describe_auto_scaling_groups(
self, names: List[str], filters: Optional[List[Dict[str, str]]] = None
) -> List[FakeAutoScalingGroup]:
groups = list(self.autoscaling_groups.values())
if filters:

View File

@ -1271,7 +1271,6 @@ class EventSourceMapping(CloudFormationModel):
return event_source_arn.split(":")[2].lower()
def _validate_event_source(self, event_source_arn: str) -> bool:
valid_services = ("dynamodb", "kinesis", "sqs")
service = self._get_service_source_from_arn(event_source_arn)
return service in valid_services
@ -1418,9 +1417,9 @@ class LambdaStorage(object):
def __init__(self, region_name: str, account_id: str):
# Format 'func_name' {'versions': []}
self._functions: Dict[str, Any] = {}
self._arns: weakref.WeakValueDictionary[
str, LambdaFunction
] = weakref.WeakValueDictionary()
self._arns: weakref.WeakValueDictionary[str, LambdaFunction] = (
weakref.WeakValueDictionary()
)
self.region_name = region_name
self.account_id = account_id
@ -1758,9 +1757,9 @@ class LambdaStorage(object):
class LayerStorage(object):
def __init__(self) -> None:
self._layers: Dict[str, Layer] = {}
self._arns: weakref.WeakValueDictionary[
str, LambdaFunction
] = weakref.WeakValueDictionary()
self._arns: weakref.WeakValueDictionary[str, LambdaFunction] = (
weakref.WeakValueDictionary()
)
def _find_layer_by_name_or_arn(self, name_or_arn: str) -> Layer:
if name_or_arn in self._layers:

View File

@ -89,7 +89,9 @@ class LambdaResponse(BaseResponse):
if request.method == "GET":
return self._list_layers()
def layers_version(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def layers_version(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
layer_name = unquote(self.path.split("/")[-3])
layer_version = self.path.split("/")[-1]
@ -98,7 +100,9 @@ class LambdaResponse(BaseResponse):
elif request.method == "GET":
return self._get_layer_version(layer_name, layer_version)
def layers_versions(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def layers_versions(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "GET":
return self._get_layer_versions()
@ -186,7 +190,9 @@ class LambdaResponse(BaseResponse):
else:
raise ValueError("Cannot handle request")
def code_signing_config(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def code_signing_config(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "GET":
return self._get_code_signing_config()
@ -206,7 +212,9 @@ class LambdaResponse(BaseResponse):
else:
raise ValueError("Cannot handle request")
def function_url_config(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def function_url_config(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
http_method = request.method
self.setup_class(request, full_url, headers)
@ -409,7 +417,9 @@ class LambdaResponse(BaseResponse):
return 204, {}, ""
@staticmethod
def _set_configuration_qualifier(configuration: Dict[str, Any], function_name: str, qualifier: str) -> Dict[str, Any]: # type: ignore[misc]
def _set_configuration_qualifier(
configuration: Dict[str, Any], function_name: str, qualifier: str
) -> Dict[str, Any]: # type: ignore[misc]
# Qualifier may be explicitly passed or part of function name or ARN, extract it here
if function_name.startswith("arn:aws"):
# Extract from ARN

View File

@ -23,7 +23,6 @@ class LambdaSimpleBackend(LambdaBackend):
headers: Any,
response_headers: Any,
) -> Optional[Union[str, bytes]]:
default_result = "Simple Lambda happy path OK"
if self.lambda_simple_results_queue:
default_result = self.lambda_simple_results_queue.pop(0)

View File

@ -309,12 +309,10 @@ def _import_backend(
return getattr(module, backends_name)
# fmt: off
# This is more or less the dummy-implementation style that's currently in black's preview
# style. It should be live in black v24.0+, at which point we should remove the # fmt: off
# directive.
@overload
def get_backend(name: "Literal['acm']") -> "BackendDict[AWSCertificateManagerBackend]": ...
def get_backend(
name: "Literal['acm']",
) -> "BackendDict[AWSCertificateManagerBackend]": ...
@overload
def get_backend(name: "Literal['acm-pca']") -> "BackendDict[ACMPCABackend]": ...
@overload
@ -322,19 +320,27 @@ def get_backend(name: "Literal['amp']") -> "BackendDict[PrometheusServiceBackend
@overload
def get_backend(name: "Literal['apigateway']") -> "BackendDict[APIGatewayBackend]": ...
@overload
def get_backend(name: "Literal['apigatewaymanagementapi']") -> "BackendDict[ApiGatewayManagementApiBackend]": ...
def get_backend(
name: "Literal['apigatewaymanagementapi']",
) -> "BackendDict[ApiGatewayManagementApiBackend]": ...
@overload
def get_backend(name: "Literal['apigatewayv2']") -> "BackendDict[ApiGatewayV2Backend]": ...
def get_backend(
name: "Literal['apigatewayv2']",
) -> "BackendDict[ApiGatewayV2Backend]": ...
@overload
def get_backend(name: "Literal['appconfig']") -> "BackendDict[AppConfigBackend]": ...
@overload
def get_backend(name: "Literal['applicationautoscaling']") -> "BackendDict[ApplicationAutoscalingBackend]": ...
def get_backend(
name: "Literal['applicationautoscaling']",
) -> "BackendDict[ApplicationAutoscalingBackend]": ...
@overload
def get_backend(name: "Literal['appsync']") -> "BackendDict[AppSyncBackend]": ...
@overload
def get_backend(name: "Literal['athena']") -> "BackendDict[AthenaBackend]": ...
@overload
def get_backend(name: "Literal['autoscaling']") -> "BackendDict[AutoScalingBackend]": ...
def get_backend(
name: "Literal['autoscaling']",
) -> "BackendDict[AutoScalingBackend]": ...
@overload
def get_backend(name: "Literal['batch']") -> "BackendDict[BatchBackend]": ...
@overload
@ -342,7 +348,9 @@ def get_backend(name: "Literal['budgets']") -> "BackendDict[BudgetsBackend]": ..
@overload
def get_backend(name: "Literal['ce']") -> "BackendDict[CostExplorerBackend]": ...
@overload
def get_backend(name: "Literal['cloudformation']") -> "BackendDict[CloudFormationBackend]": ...
def get_backend(
name: "Literal['cloudformation']",
) -> "BackendDict[CloudFormationBackend]": ...
@overload
def get_backend(name: "Literal['cloudfront']") -> "BackendDict[CloudFrontBackend]": ...
@overload
@ -354,9 +362,13 @@ def get_backend(name: "Literal['codebuild']") -> "BackendDict[CodeBuildBackend]"
@overload
def get_backend(name: "Literal['codecommit']") -> "BackendDict[CodeCommitBackend]": ...
@overload
def get_backend(name: "Literal['codepipeline']") -> "BackendDict[CodePipelineBackend]": ...
def get_backend(
name: "Literal['codepipeline']",
) -> "BackendDict[CodePipelineBackend]": ...
@overload
def get_backend(name: "Literal['cognito-identity']") -> "BackendDict[CognitoIdentityBackend]": ...
def get_backend(
name: "Literal['cognito-identity']",
) -> "BackendDict[CognitoIdentityBackend]": ...
@overload
def get_backend(name: "Literal['cognito-idp']") -> "BackendDict[CognitoIdpBackend]": ...
@overload
@ -366,41 +378,57 @@ def get_backend(name: "Literal['config']") -> "BackendDict[ConfigBackend]": ...
@overload
def get_backend(name: "Literal['databrew']") -> "BackendDict[DataBrewBackend]": ...
@overload
def get_backend(name: "Literal['datapipeline']") -> "BackendDict[DataPipelineBackend]": ...
def get_backend(
name: "Literal['datapipeline']",
) -> "BackendDict[DataPipelineBackend]": ...
@overload
def get_backend(name: "Literal['datasync']") -> "BackendDict[DataSyncBackend]": ...
@overload
def get_backend(name: "Literal['dax']") -> "BackendDict[DAXBackend]": ...
@overload
def get_backend(name: "Literal['dms']") -> "BackendDict[DatabaseMigrationServiceBackend]": ...
def get_backend(
name: "Literal['dms']",
) -> "BackendDict[DatabaseMigrationServiceBackend]": ...
@overload
def get_backend(name: "Literal['ds']") -> "BackendDict[DirectoryServiceBackend]": ...
@overload
def get_backend(name: "Literal['dynamodb']") -> "BackendDict[DynamoDBBackend]": ...
@overload
def get_backend(name: "Literal['dynamodb_v20111205']") -> "BackendDict[DynamoDBBackend_v20111205]": ...
def get_backend(
name: "Literal['dynamodb_v20111205']",
) -> "BackendDict[DynamoDBBackend_v20111205]": ...
@overload
def get_backend(name: "Literal['dynamodbstreams']") -> "BackendDict[DynamoDBStreamsBackend]": ...
def get_backend(
name: "Literal['dynamodbstreams']",
) -> "BackendDict[DynamoDBStreamsBackend]": ...
@overload
def get_backend(name: "Literal['ebs']") -> "BackendDict[EBSBackend]": ...
@overload
def get_backend(name: "Literal['ec2']") -> "BackendDict[EC2Backend]": ...
@overload
def get_backend(name: "Literal['ec2instanceconnect']") -> "BackendDict[Ec2InstanceConnectBackend]": ...
def get_backend(
name: "Literal['ec2instanceconnect']",
) -> "BackendDict[Ec2InstanceConnectBackend]": ...
@overload
def get_backend(name: "Literal['ecr']") -> "BackendDict[ECRBackend]": ...
@overload
def get_backend(name: "Literal['ecs']") -> "BackendDict[EC2ContainerServiceBackend]": ...
def get_backend(
name: "Literal['ecs']",
) -> "BackendDict[EC2ContainerServiceBackend]": ...
@overload
def get_backend(name: "Literal['efs']") -> "BackendDict[EFSBackend]": ...
@overload
def get_backend(name: "Literal['eks']") -> "BackendDict[EKSBackend]": ...
@overload
def get_backend(name: "Literal['elasticache']") -> "BackendDict[ElastiCacheBackend]": ...
def get_backend(
name: "Literal['elasticache']",
) -> "BackendDict[ElastiCacheBackend]": ...
@overload
def get_backend(name: "Literal['elasticbeanstalk']") -> "BackendDict[EBBackend]": ...
@overload
def get_backend(name: "Literal['elastictranscoder']") -> "BackendDict[ElasticTranscoderBackend]": ...
def get_backend(
name: "Literal['elastictranscoder']",
) -> "BackendDict[ElasticTranscoderBackend]": ...
@overload
def get_backend(name: "Literal['elb']") -> "BackendDict[ELBBackend]": ...
@overload
@ -408,11 +436,17 @@ def get_backend(name: "Literal['elbv2']") -> "BackendDict[ELBv2Backend]": ...
@overload
def get_backend(name: "Literal['emr']") -> "BackendDict[ElasticMapReduceBackend]": ...
@overload
def get_backend(name: "Literal['emr-containers']") -> "BackendDict[EMRContainersBackend]": ...
def get_backend(
name: "Literal['emr-containers']",
) -> "BackendDict[EMRContainersBackend]": ...
@overload
def get_backend(name: "Literal['emr-serverless']") -> "BackendDict[EMRServerlessBackend]": ...
def get_backend(
name: "Literal['emr-serverless']",
) -> "BackendDict[EMRServerlessBackend]": ...
@overload
def get_backend(name: "Literal['es']") -> "BackendDict[ElasticsearchServiceBackend]": ...
def get_backend(
name: "Literal['es']",
) -> "BackendDict[ElasticsearchServiceBackend]": ...
@overload
def get_backend(name: "Literal['events']") -> "BackendDict[EventsBackend]": ...
@overload
@ -430,11 +464,15 @@ def get_backend(name: "Literal['guardduty']") -> "BackendDict[GuardDutyBackend]"
@overload
def get_backend(name: "Literal['iam']") -> "BackendDict[IAMBackend]": ...
@overload
def get_backend(name: "Literal['identitystore']") -> "BackendDict[IdentityStoreBackend]": ...
def get_backend(
name: "Literal['identitystore']",
) -> "BackendDict[IdentityStoreBackend]": ...
@overload
def get_backend(name: "Literal['inspector2']") -> "BackendDict[Inspector2Backend]": ...
@overload
def get_backend(name: "Literal['instance_metadata']") -> "BackendDict[InstanceMetadataBackend]": ...
def get_backend(
name: "Literal['instance_metadata']",
) -> "BackendDict[InstanceMetadataBackend]": ...
@overload
def get_backend(name: "Literal['iot']") -> "BackendDict[IoTBackend]": ...
@overload
@ -444,31 +482,47 @@ def get_backend(name: "Literal['ivs']") -> "BackendDict[IVSBackend]": ...
@overload
def get_backend(name: "Literal['kinesis']") -> "BackendDict[KinesisBackend]": ...
@overload
def get_backend(name: "Literal['kinesisvideo']") -> "BackendDict[KinesisVideoBackend]": ...
def get_backend(
name: "Literal['kinesisvideo']",
) -> "BackendDict[KinesisVideoBackend]": ...
@overload
def get_backend(name: "Literal['kinesis-video-archived-media']") -> "BackendDict[KinesisVideoArchivedMediaBackend]": ...
def get_backend(
name: "Literal['kinesis-video-archived-media']",
) -> "BackendDict[KinesisVideoArchivedMediaBackend]": ...
@overload
def get_backend(name: "Literal['kms']") -> "BackendDict[KmsBackend]": ...
@overload
def get_backend(name: "Literal['lakeformation']") -> "BackendDict[LakeFormationBackend]": ...
def get_backend(
name: "Literal['lakeformation']",
) -> "BackendDict[LakeFormationBackend]": ...
@overload
def get_backend(name: "Literal['lambda']") -> "BackendDict[LambdaBackend]": ...
@overload
def get_backend(name: "Literal['logs']") -> "BackendDict[LogsBackend]": ...
@overload
def get_backend(name: "Literal['managedblockchain']") -> "BackendDict[ManagedBlockchainBackend]": ...
def get_backend(
name: "Literal['managedblockchain']",
) -> "BackendDict[ManagedBlockchainBackend]": ...
@overload
def get_backend(name: "Literal['mediaconnect']") -> "BackendDict[MediaConnectBackend]": ...
def get_backend(
name: "Literal['mediaconnect']",
) -> "BackendDict[MediaConnectBackend]": ...
@overload
def get_backend(name: "Literal['medialive']") -> "BackendDict[MediaLiveBackend]": ...
@overload
def get_backend(name: "Literal['mediapackage']") -> "BackendDict[MediaPackageBackend]": ...
def get_backend(
name: "Literal['mediapackage']",
) -> "BackendDict[MediaPackageBackend]": ...
@overload
def get_backend(name: "Literal['mediastore']") -> "BackendDict[MediaStoreBackend]": ...
@overload
def get_backend(name: "Literal['mediastore-data']") -> "BackendDict[MediaStoreDataBackend]": ...
def get_backend(
name: "Literal['mediastore-data']",
) -> "BackendDict[MediaStoreDataBackend]": ...
@overload
def get_backend(name: "Literal['meteringmarketplace']") -> "BackendDict[MeteringMarketplaceBackend]": ...
def get_backend(
name: "Literal['meteringmarketplace']",
) -> "BackendDict[MeteringMarketplaceBackend]": ...
@overload
def get_backend(name: "Literal['moto_api']") -> "BackendDict[MotoAPIBackend]": ...
@overload
@ -476,13 +530,19 @@ def get_backend(name: "Literal['mq']") -> "BackendDict[MQBackend]": ...
@overload
def get_backend(name: "Literal['neptune']") -> "BackendDict[NeptuneBackend]": ...
@overload
def get_backend(name: "Literal['opensearch']") -> "BackendDict[OpenSearchServiceBackend]": ...
def get_backend(
name: "Literal['opensearch']",
) -> "BackendDict[OpenSearchServiceBackend]": ...
@overload
def get_backend(name: "Literal['opsworks']") -> "BackendDict[OpsWorksBackend]": ...
@overload
def get_backend(name: "Literal['organizations']") -> "BackendDict[OrganizationsBackend]": ...
def get_backend(
name: "Literal['organizations']",
) -> "BackendDict[OrganizationsBackend]": ...
@overload
def get_backend(name: "Literal['personalize']") -> "BackendDict[PersonalizeBackend]": ...
def get_backend(
name: "Literal['personalize']",
) -> "BackendDict[PersonalizeBackend]": ...
@overload
def get_backend(name: "Literal['pinpoint']") -> "BackendDict[PinpointBackend]": ...
@overload
@ -490,31 +550,49 @@ def get_backend(name: "Literal['polly']") -> "BackendDict[PollyBackend]": ...
@overload
def get_backend(name: "Literal['quicksight']") -> "BackendDict[QuickSightBackend]": ...
@overload
def get_backend(name: "Literal['ram']") -> "BackendDict[ResourceAccessManagerBackend]": ...
def get_backend(
name: "Literal['ram']",
) -> "BackendDict[ResourceAccessManagerBackend]": ...
@overload
def get_backend(name: "Literal['rds']") -> "BackendDict[RDSBackend]": ...
@overload
def get_backend(name: "Literal['rds-data']") -> "BackendDict[RDSDataServiceBackend]": ...
def get_backend(
name: "Literal['rds-data']",
) -> "BackendDict[RDSDataServiceBackend]": ...
@overload
def get_backend(name: "Literal['redshift']") -> "BackendDict[RedshiftBackend]": ...
@overload
def get_backend(name: "Literal['redshift-data']") -> "BackendDict[RedshiftDataAPIServiceBackend]": ...
def get_backend(
name: "Literal['redshift-data']",
) -> "BackendDict[RedshiftDataAPIServiceBackend]": ...
@overload
def get_backend(name: "Literal['rekognition']") -> "BackendDict[RekognitionBackend]": ...
def get_backend(
name: "Literal['rekognition']",
) -> "BackendDict[RekognitionBackend]": ...
@overload
def get_backend(name: "Literal['resiliencehub']") -> "BackendDict[ResilienceHubBackend]": ...
def get_backend(
name: "Literal['resiliencehub']",
) -> "BackendDict[ResilienceHubBackend]": ...
@overload
def get_backend(name: "Literal['resource-groups']") -> "BackendDict[ResourceGroupsBackend]": ...
def get_backend(
name: "Literal['resource-groups']",
) -> "BackendDict[ResourceGroupsBackend]": ...
@overload
def get_backend(name: "Literal['resourcegroupstaggingapi']") -> "BackendDict[ResourceGroupsTaggingAPIBackend]": ...
def get_backend(
name: "Literal['resourcegroupstaggingapi']",
) -> "BackendDict[ResourceGroupsTaggingAPIBackend]": ...
@overload
def get_backend(name: "Literal['robomaker']") -> "BackendDict[RoboMakerBackend]": ...
@overload
def get_backend(name: "Literal['route53']") -> "BackendDict[Route53Backend]": ...
@overload
def get_backend(name: "Literal['route53resolver']") -> "BackendDict[Route53ResolverBackend]": ...
def get_backend(
name: "Literal['route53resolver']",
) -> "BackendDict[Route53ResolverBackend]": ...
@overload
def get_backend(name: "Literal['route53domains']") -> "BackendDict[Route53DomainsBackend]": ...
def get_backend(
name: "Literal['route53domains']",
) -> "BackendDict[Route53DomainsBackend]": ...
@overload
def get_backend(name: "Literal['s3']") -> "BackendDict[S3Backend]": ...
@overload
@ -522,19 +600,31 @@ def get_backend(name: "Literal['s3bucket_path']") -> "BackendDict[S3Backend]": .
@overload
def get_backend(name: "Literal['s3control']") -> "BackendDict[S3ControlBackend]": ...
@overload
def get_backend(name: "Literal['sagemaker']") -> "BackendDict[SageMakerModelBackend]": ...
def get_backend(
name: "Literal['sagemaker']",
) -> "BackendDict[SageMakerModelBackend]": ...
@overload
def get_backend(name: "Literal['sagemaker-runtime']") -> "BackendDict[SageMakerRuntimeBackend]": ...
def get_backend(
name: "Literal['sagemaker-runtime']",
) -> "BackendDict[SageMakerRuntimeBackend]": ...
@overload
def get_backend(name: "Literal['scheduler']") -> "BackendDict[EventBridgeSchedulerBackend]": ...
def get_backend(
name: "Literal['scheduler']",
) -> "BackendDict[EventBridgeSchedulerBackend]": ...
@overload
def get_backend(name: "Literal['sdb']") -> "BackendDict[SimpleDBBackend]": ...
@overload
def get_backend(name: "Literal['secretsmanager']") -> "BackendDict[SecretsManagerBackend]": ...
def get_backend(
name: "Literal['secretsmanager']",
) -> "BackendDict[SecretsManagerBackend]": ...
@overload
def get_backend(name: "Literal['servicediscovery']") -> "BackendDict[ServiceDiscoveryBackend]": ...
def get_backend(
name: "Literal['servicediscovery']",
) -> "BackendDict[ServiceDiscoveryBackend]": ...
@overload
def get_backend(name: "Literal['service-quotas']") -> "BackendDict[ServiceQuotasBackend]": ...
def get_backend(
name: "Literal['service-quotas']",
) -> "BackendDict[ServiceQuotasBackend]": ...
@overload
def get_backend(name: "Literal['ses']") -> "BackendDict[SESBackend]": ...
@overload
@ -546,11 +636,15 @@ def get_backend(name: "Literal['sns']") -> "BackendDict[SNSBackend]": ...
@overload
def get_backend(name: "Literal['sqs']") -> "BackendDict[SQSBackend]": ...
@overload
def get_backend(name: "Literal['ssm']") -> "BackendDict[SimpleSystemManagerBackend]": ...
def get_backend(
name: "Literal['ssm']",
) -> "BackendDict[SimpleSystemManagerBackend]": ...
@overload
def get_backend(name: "Literal['sso-admin']") -> "BackendDict[SSOAdminBackend]": ...
@overload
def get_backend(name: "Literal['stepfunctions']") -> "BackendDict[StepFunctionBackend]": ...
def get_backend(
name: "Literal['stepfunctions']",
) -> "BackendDict[StepFunctionBackend]": ...
@overload
def get_backend(name: "Literal['sts']") -> "BackendDict[STSBackend]": ...
@overload
@ -560,7 +654,9 @@ def get_backend(name: "Literal['swf']") -> "BackendDict[SWFBackend]": ...
@overload
def get_backend(name: "Literal['textract']") -> "BackendDict[TextractBackend]": ...
@overload
def get_backend(name: "Literal['timestream-write']") -> "BackendDict[TimestreamWriteBackend]": ...
def get_backend(
name: "Literal['timestream-write']",
) -> "BackendDict[TimestreamWriteBackend]": ...
@overload
def get_backend(name: "Literal['transcribe']") -> "BackendDict[TranscribeBackend]": ...
@overload
@ -569,10 +665,10 @@ def get_backend(name: "Literal['wafv2']") -> "BackendDict[WAFV2Backend]": ...
def get_backend(name: "Literal['workspaces']") -> "BackendDict[WorkSpacesBackend]": ...
@overload
def get_backend(name: "Literal['xray']") -> "BackendDict[XRayBackend]": ...
# fmt: on
def get_backend(name: SERVICE_NAMES) -> "BackendDict[SERVICE_BACKEND]":
# fmt: on
safe_name = name.replace("-", "")
return _import_backend(
ALT_SERVICE_NAMES.get(safe_name, safe_name),

View File

@ -1,4 +1,5 @@
"""Exceptions raised by the backup service."""
from moto.core.exceptions import JsonRESTError

View File

@ -17,7 +17,6 @@ class Plan(BaseModel):
creator_request_id: str,
backend: "BackupBackend",
):
self.backup_plan_id = str(mock_random.uuid4())
self.backup_plan_arn = f"arn:aws:backup:{backend.region_name}:{backend.account_id}:backup-plan:{self.backup_plan_id}"
self.creation_date = unix_time()
@ -137,7 +136,6 @@ class BackupBackend(BaseBackend):
backup_plan_tags: Dict[str, str],
creator_request_id: str,
) -> Plan:
if backup_plan["BackupPlanName"] in list(
p.backup_plan["BackupPlanName"] for p in list(self.plans.values())
):
@ -197,7 +195,6 @@ class BackupBackend(BaseBackend):
encryption_key_arn: str,
creator_request_id: str,
) -> Vault:
if backup_vault_name in self.vaults:
raise AlreadyExistsException(
msg="Backup vault with the same name already exists"

View File

@ -1,4 +1,5 @@
"""Handles incoming backup requests, invokes methods, returns responses."""
import json
from urllib.parse import unquote

View File

@ -1,4 +1,5 @@
"""backup base URL and path."""
from .responses import BackupResponse
url_bases = [

View File

@ -768,9 +768,9 @@ class Job(threading.Thread, BaseModel, DockerModel, ManagedState):
environment = kwargs["environment"]
environment["MOTO_HOST"] = settings.moto_server_host()
environment["MOTO_PORT"] = settings.moto_server_port()
environment[
"MOTO_HTTP_ENDPOINT"
] = f'{environment["MOTO_HOST"]}:{environment["MOTO_PORT"]}'
environment["MOTO_HTTP_ENDPOINT"] = (
f'{environment["MOTO_HOST"]}:{environment["MOTO_PORT"]}'
)
if network_name:
kwargs["network"] = network_name

View File

@ -1,4 +1,5 @@
"""Exceptions raised by the budgets service."""
from moto.core.exceptions import JsonRESTError

View File

@ -1,4 +1,5 @@
"""Exceptions raised by the ce service."""
from moto.core.exceptions import JsonRESTError

View File

@ -1,4 +1,5 @@
"""Handles incoming ce requests, invokes methods, returns responses."""
import json
from moto.core.responses import BaseResponse

View File

@ -1,4 +1,5 @@
"""ce base URL and path."""
from .responses import CostExplorerResponse
url_bases = [

View File

@ -117,7 +117,6 @@ class FakeStackSet(BaseModel):
regions: List[str],
operation_id: str,
) -> Dict[str, Any]:
self.template = template or self.template
self.description = description if description is not None else self.description
self.parameters = parameters or self.parameters
@ -447,7 +446,6 @@ class FakeStack(CloudFormationModel):
resource_status_reason: Optional[str] = None,
resource_properties: Optional[str] = None,
) -> None:
event = FakeEvent(
stack_id=self.stack_id,
stack_name=self.name,

View File

@ -334,15 +334,17 @@ def parse_resource(
def parse_resource_and_generate_name(
logical_id: str, resource_json: Dict[str, Any], resources_map: "ResourceMap"
) -> Tuple[Type[CloudFormationModel], Dict[str, Any], str]:
resource_tuple: Tuple[
Type[CloudFormationModel], Dict[str, Any], str
] = parse_resource(resource_json, resources_map)
resource_tuple: Tuple[Type[CloudFormationModel], Dict[str, Any], str] = (
parse_resource(resource_json, resources_map)
)
if not resource_tuple:
return None
resource_class, resource_json, resource_type = resource_tuple
generated_resource_name = generate_resource_name(
resource_type, resources_map["AWS::StackName"], logical_id # type: ignore[arg-type]
resource_type,
resources_map["AWS::StackName"],
logical_id, # type: ignore[arg-type]
)
resource_name_property = resource_name_property_from_type(resource_type)
@ -373,9 +375,9 @@ def parse_and_create_resource(
return None
resource_type = resource_json["Type"]
resource_tuple: Tuple[
Type[CloudFormationModel], Dict[str, Any], str
] = parse_resource_and_generate_name(logical_id, resource_json, resources_map)
resource_tuple: Tuple[Type[CloudFormationModel], Dict[str, Any], str] = (
parse_resource_and_generate_name(logical_id, resource_json, resources_map)
)
if not resource_tuple:
return None
resource_class, resource_json, resource_physical_name = resource_tuple
@ -399,9 +401,9 @@ def parse_and_update_resource(
account_id: str,
region_name: str,
) -> Optional[CF_MODEL]:
resource_tuple: Optional[
Tuple[Type[CloudFormationModel], Dict[str, Any], str]
] = parse_resource_and_generate_name(logical_id, resource_json, resources_map)
resource_tuple: Optional[Tuple[Type[CloudFormationModel], Dict[str, Any], str]] = (
parse_resource_and_generate_name(logical_id, resource_json, resources_map)
)
if not resource_tuple:
return None
resource_class, resource_json, new_resource_name = resource_tuple
@ -436,7 +438,11 @@ def parse_and_delete_resource(
)
def parse_condition(condition: Union[Dict[str, Any], bool], resources_map: "ResourceMap", condition_map: Dict[str, Any]) -> bool: # type: ignore[return]
def parse_condition(
condition: Union[Dict[str, Any], bool],
resources_map: "ResourceMap",
condition_map: Dict[str, Any],
) -> bool: # type: ignore[return]
if isinstance(condition, bool):
return condition
@ -751,7 +757,6 @@ class ResourceMap(collections_abc.Mapping): # type: ignore[type-arg]
return all_resources_ready
def build_resource_diff(self, other_template: Dict[str, Any]) -> Dict[str, Any]:
old = self._resource_json_map
new = other_template["Resources"]
@ -766,7 +771,6 @@ class ResourceMap(collections_abc.Mapping): # type: ignore[type-arg]
def build_change_set_actions(
self, template: Dict[str, Any]
) -> Dict[str, Dict[str, Dict[str, str]]]:
resource_names_by_action = self.build_resource_diff(template)
resources_by_action: Dict[str, Dict[str, Dict[str, str]]] = {
@ -798,7 +802,6 @@ class ResourceMap(collections_abc.Mapping): # type: ignore[type-arg]
def update(
self, template: Dict[str, Any], parameters: Optional[Dict[str, Any]] = None
) -> None:
resource_names_by_action = self.build_resource_diff(template)
for logical_name in resource_names_by_action["Remove"]:
@ -816,7 +819,6 @@ class ResourceMap(collections_abc.Mapping): # type: ignore[type-arg]
self._resource_json_map = template["Resources"]
for logical_name in resource_names_by_action["Add"]:
# call __getitem__ to initialize the resource
# TODO: usage of indexer to initalize the resource is questionable
_ = self[logical_name]
@ -867,7 +869,6 @@ class ResourceMap(collections_abc.Mapping): # type: ignore[type-arg]
not isinstance(parsed_resource, str)
and parsed_resource is not None
):
resource_json = self._resource_json_map[
parsed_resource.logical_resource_id
]

View File

@ -40,14 +40,18 @@ class CloudFrontResponse(BaseResponse):
if request.method == "GET":
return self.list_tags_for_resource()
def origin_access_controls(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def origin_access_controls(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "POST":
return self.create_origin_access_control()
if request.method == "GET":
return self.list_origin_access_controls()
def origin_access_control(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def origin_access_control(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "GET":
return self.get_origin_access_control()
@ -82,7 +86,9 @@ class CloudFrontResponse(BaseResponse):
response = template.render(distributions=distributions)
return 200, {}, response
def individual_distribution(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def individual_distribution(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
distribution_id = full_url.split("/")[-1]
if request.method == "DELETE":

View File

@ -1,4 +1,5 @@
"""cloudfront base URL and path."""
from .responses import CloudFrontResponse
url_bases = [

View File

@ -1,4 +1,5 @@
"""Exceptions raised by the cloudtrail service."""
from moto.core.exceptions import JsonRESTError

View File

@ -1,4 +1,5 @@
"""Handles incoming cloudtrail requests, invokes methods, returns responses."""
import json
from typing import Any, Dict

View File

@ -1,4 +1,5 @@
"""cloudtrail base URL and path."""
from .responses import CloudTrailResponse
response = CloudTrailResponse()

View File

@ -25,9 +25,9 @@ class CodeBuildProjectMetadata(BaseModel):
self.build_metadata: Dict[str, Any] = dict()
self.build_metadata["id"] = build_id
self.build_metadata[
"arn"
] = f"arn:aws:codebuild:{region_name}:{account_id}:build/{build_id}"
self.build_metadata["arn"] = (
f"arn:aws:codebuild:{region_name}:{account_id}:build/{build_id}"
)
self.build_metadata["buildNumber"] = mock_random.randint(1, 100)
self.build_metadata["startTime"] = current_date
@ -86,9 +86,9 @@ class CodeBuildProjectMetadata(BaseModel):
self.build_metadata["queuedTimeoutInMinutes"] = 480
self.build_metadata["buildComplete"] = False
self.build_metadata["initiator"] = "rootme"
self.build_metadata[
"encryptionKey"
] = f"arn:aws:kms:{region_name}:{account_id}:alias/aws/s3"
self.build_metadata["encryptionKey"] = (
f"arn:aws:kms:{region_name}:{account_id}:alias/aws/s3"
)
class CodeBuild(BaseModel):
@ -106,21 +106,21 @@ class CodeBuild(BaseModel):
self.project_metadata: Dict[str, Any] = dict()
self.project_metadata["name"] = project_name
self.project_metadata[
"arn"
] = f"arn:aws:codebuild:{region}:{account_id}:project/{project_name}"
self.project_metadata[
"encryptionKey"
] = f"arn:aws:kms:{region}:{account_id}:alias/aws/s3"
self.project_metadata[
"serviceRole"
] = f"arn:aws:iam::{account_id}:role/service-role/{serviceRole}"
self.project_metadata["arn"] = (
f"arn:aws:codebuild:{region}:{account_id}:project/{project_name}"
)
self.project_metadata["encryptionKey"] = (
f"arn:aws:kms:{region}:{account_id}:alias/aws/s3"
)
self.project_metadata["serviceRole"] = (
f"arn:aws:iam::{account_id}:role/service-role/{serviceRole}"
)
self.project_metadata["lastModifiedDate"] = current_date
self.project_metadata["created"] = current_date
self.project_metadata["badge"] = dict()
self.project_metadata["badge"][
"badgeEnabled"
] = False # this false needs to be a json false not a python false
self.project_metadata["badge"]["badgeEnabled"] = (
False # this false needs to be a json false not a python false
)
self.project_metadata["environment"] = environment
self.project_metadata["artifacts"] = artifacts
self.project_metadata["source"] = project_source
@ -166,7 +166,6 @@ class CodeBuildBackend(BaseBackend):
return self.codebuild_projects[project_name].project_metadata
def list_projects(self) -> List[str]:
projects = []
for project in self.codebuild_projects.keys():
@ -180,7 +179,6 @@ class CodeBuildBackend(BaseBackend):
source_version: Optional[str] = None,
artifact_override: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
build_id = f"{project_name}:{mock_random.uuid4()}"
# construct a new build
@ -269,7 +267,6 @@ class CodeBuildBackend(BaseBackend):
self.codebuild_projects.pop(project_name, None)
def stop_build(self, build_id: str) -> Optional[Dict[str, Any]]: # type: ignore[return]
for metadata in self.build_metadata_history.values():
for build in metadata:
if build["id"] == build_id:

View File

@ -19,19 +19,19 @@ class CodeCommit(BaseModel):
current_date = iso_8601_datetime_with_milliseconds()
self.repository_metadata = dict()
self.repository_metadata["repositoryName"] = repository_name
self.repository_metadata[
"cloneUrlSsh"
] = f"ssh://git-codecommit.{region}.amazonaws.com/v1/repos/{repository_name}"
self.repository_metadata[
"cloneUrlHttp"
] = f"https://git-codecommit.{region}.amazonaws.com/v1/repos/{repository_name}"
self.repository_metadata["cloneUrlSsh"] = (
f"ssh://git-codecommit.{region}.amazonaws.com/v1/repos/{repository_name}"
)
self.repository_metadata["cloneUrlHttp"] = (
f"https://git-codecommit.{region}.amazonaws.com/v1/repos/{repository_name}"
)
self.repository_metadata["creationDate"] = current_date
self.repository_metadata["lastModifiedDate"] = current_date
self.repository_metadata["repositoryDescription"] = repository_description
self.repository_metadata["repositoryId"] = str(mock_random.uuid4())
self.repository_metadata[
"Arn"
] = f"arn:aws:codecommit:{region}:{account_id}:{repository_name}"
self.repository_metadata["Arn"] = (
f"arn:aws:codecommit:{region}:{account_id}:{repository_name}"
)
self.repository_metadata["accountId"] = account_id

View File

@ -7,7 +7,6 @@ class ResourceNotFoundError(JsonRESTError):
class InvalidNameException(JsonRESTError):
message = "1 validation error detected: Value '{}' at 'identityPoolName' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\w\\s+=,.@-]+"
def __init__(self, name: str):

View File

@ -64,7 +64,6 @@ class AuthFlow(str, enum.Enum):
class CognitoIdpUserPoolAttribute(BaseModel):
STANDARD_SCHEMA = {
"sub": {
"AttributeDataType": "String",
@ -385,7 +384,6 @@ DEFAULT_USER_POOL_CONFIG: Dict[str, Any] = {
class CognitoIdpUserPool(BaseModel):
MAX_ID_LENGTH = 55
def __init__(
@ -426,10 +424,10 @@ class CognitoIdpUserPool(BaseModel):
standard_attribute_name,
standard_attribute_schema,
) in CognitoIdpUserPoolAttribute.STANDARD_SCHEMA.items():
self.schema_attributes[
standard_attribute_name
] = CognitoIdpUserPoolAttribute(
standard_attribute_name, False, standard_attribute_schema
self.schema_attributes[standard_attribute_name] = (
CognitoIdpUserPoolAttribute(
standard_attribute_name, False, standard_attribute_schema
)
)
self.clients: Dict[str, CognitoIdpUserPoolClient] = OrderedDict()

View File

@ -482,9 +482,9 @@ class CognitoIdpResponse(BaseResponse):
confirmation_code, response = cognitoidp_backends[account][
region
].forgot_password(client_id, username)
self.response_headers[
"x-moto-forgot-password-confirmation-code"
] = confirmation_code # type: ignore[assignment]
self.response_headers["x-moto-forgot-password-confirmation-code"] = (
confirmation_code # type: ignore[assignment]
)
return json.dumps(response)
# This endpoint receives no authorization header, so if moto-server is listening

View File

@ -1,4 +1,5 @@
"""Exceptions raised by the comprehend service."""
from typing import List
from moto.core.exceptions import JsonRESTError

View File

@ -1,4 +1,5 @@
"""Handles incoming comprehend requests, invokes methods, returns responses."""
import json
from moto.core.responses import BaseResponse

View File

@ -1,4 +1,5 @@
"""comprehend base URL and path."""
from .responses import ComprehendResponse
url_bases = [

View File

@ -1,4 +1,5 @@
"""Implementation of the AWS Config Service APIs."""
import json
import re
import time
@ -487,7 +488,6 @@ class OrganizationConformancePack(ConfigEmptyDictable):
class Scope(ConfigEmptyDictable):
"""Defines resources that can trigger an evaluation for the rule.
Per boto3 documentation, Scope can be one of:
@ -536,7 +536,6 @@ class Scope(ConfigEmptyDictable):
class SourceDetail(ConfigEmptyDictable):
"""Source and type of event triggering AWS Config resource evaluation.
Applies only to customer rules.
@ -633,7 +632,6 @@ class SourceDetail(ConfigEmptyDictable):
class Source(ConfigEmptyDictable):
"""Defines rule owner, id and notification for triggering evaluation."""
OWNERS = {"AWS", "CUSTOM_LAMBDA"}
@ -713,7 +711,6 @@ class Source(ConfigEmptyDictable):
class ConfigRule(ConfigEmptyDictable):
"""AWS Config Rule to evaluate compliance of resources to configuration.
Can be a managed or custom config rule. Contains the instantiations of
@ -921,7 +918,9 @@ class ConfigBackend(BaseBackend):
self.retention_configuration: Optional[RetentionConfiguration] = None
@staticmethod
def default_vpc_endpoint_service(service_region: str, zones: List[str]) -> List[Dict[str, Any]]: # type: ignore[misc]
def default_vpc_endpoint_service(
service_region: str, zones: List[str]
) -> List[Dict[str, Any]]: # type: ignore[misc]
"""List of dicts representing default VPC endpoints for this service."""
return BaseBackend.default_vpc_endpoint_service_factory(
service_region, zones, "config"

View File

@ -140,7 +140,8 @@ class BaseBackend:
@staticmethod
def default_vpc_endpoint_service(
service_region: str, zones: List[str] # pylint: disable=unused-argument
service_region: str,
zones: List[str], # pylint: disable=unused-argument
) -> List[Dict[str, str]]:
"""Invoke the factory method for any VPC endpoint(s) services."""
return []
@ -188,9 +189,9 @@ class BaseBackend:
# Don't know how private DNS names are different, so for now just
# one will be added.
if private_dns_names:
endpoint_service[
"PrivateDnsName"
] = f"{service}.{service_region}.amazonaws.com"
endpoint_service["PrivateDnsName"] = (
f"{service}.{service_region}.amazonaws.com"
)
endpoint_service["PrivateDnsNameVerificationState"] = "verified"
endpoint_service["PrivateDnsNames"] = [
{"PrivateDnsName": f"{service}.{service_region}.amazonaws.com"}

View File

@ -53,7 +53,6 @@ class BotocoreStubber:
for service, pattern in backend_index.backend_url_patterns:
if pattern.match(clean_url):
if passthrough_service(service):
return None

View File

@ -6,7 +6,9 @@ from .base_backend import SERVICE_BACKEND, BackendDict, InstanceTrackerMeta
class BaseModel(metaclass=InstanceTrackerMeta):
def __new__(
cls, *args: Any, **kwargs: Any # pylint: disable=unused-argument
cls,
*args: Any,
**kwargs: Any, # pylint: disable=unused-argument
) -> "BaseModel":
instance = super(BaseModel, cls).__new__(cls)
cls.instances.append(instance) # type: ignore[attr-defined]
@ -46,7 +48,7 @@ class CloudFormationModel(BaseModel):
cloudformation_json: Dict[str, Any],
account_id: str,
region_name: str,
**kwargs: Any
**kwargs: Any,
) -> Any:
# This must be implemented as a classmethod with parameters:
# cls, resource_name, cloudformation_json, account_id, region_name

View File

@ -13,13 +13,13 @@ T = TypeVar("T")
@overload
def mock_aws(func: "Callable[P, T]") -> "Callable[P, T]":
...
def mock_aws(func: "Callable[P, T]") -> "Callable[P, T]": ...
@overload
def mock_aws(func: None = None, config: Optional[DefaultConfig] = None) -> "MockAWS":
...
def mock_aws(
func: None = None, config: Optional[DefaultConfig] = None
) -> "MockAWS": ...
def mock_aws(

View File

@ -74,7 +74,9 @@ class RESTError(HTTPException):
self.content_type = "application/xml"
def get_headers(
self, *args: Any, **kwargs: Any # pylint: disable=unused-argument
self,
*args: Any,
**kwargs: Any, # pylint: disable=unused-argument
) -> List[Tuple[str, str]]:
return [
("X-Amzn-ErrorType", self.relative_error_type or "UnknownError"),
@ -86,7 +88,9 @@ class RESTError(HTTPException):
return self.error_type
def get_body(
self, *args: Any, **kwargs: Any # pylint: disable=unused-argument
self,
*args: Any,
**kwargs: Any, # pylint: disable=unused-argument
) -> str:
return self.description

View File

@ -369,9 +369,9 @@ class ServerModeMockAWS(MockAWS):
if region:
if "config" in kwargs:
user_agent = kwargs["config"].__dict__.get("user_agent_extra") or ""
kwargs["config"].__dict__[
"user_agent_extra"
] = f"{user_agent} region/{region}"
kwargs["config"].__dict__["user_agent_extra"] = (
f"{user_agent} region/{region}"
)
else:
config = Config(user_agent_extra="region/" + region)
kwargs["config"] = config
@ -406,7 +406,6 @@ class ServerModeMockAWS(MockAWS):
class ProxyModeMockAWS(MockAWS):
_RESET_IN_PROGRESS = False
def __init__(self, *args: Any, **kwargs: Any):

View File

@ -645,7 +645,9 @@ class BaseResponse(_TemplateEnvironmentMixin, ActionAuthenticatorMixin):
return if_none
def _get_int_param(
self, param_name: str, if_none: TYPE_IF_NONE = None # type: ignore[assignment]
self,
param_name: str,
if_none: TYPE_IF_NONE = None, # type: ignore[assignment]
) -> Union[int, TYPE_IF_NONE]:
val = self._get_param(param_name)
if val is not None:
@ -653,7 +655,9 @@ class BaseResponse(_TemplateEnvironmentMixin, ActionAuthenticatorMixin):
return if_none
def _get_bool_param(
self, param_name: str, if_none: TYPE_IF_NONE = None # type: ignore[assignment]
self,
param_name: str,
if_none: TYPE_IF_NONE = None, # type: ignore[assignment]
) -> Union[bool, TYPE_IF_NONE]:
val = self._get_param(param_name)
if val is not None:

View File

@ -281,7 +281,7 @@ def tags_from_query_string(
def tags_from_cloudformation_tags_list(
tags_list: List[Dict[str, str]]
tags_list: List[Dict[str, str]],
) -> Dict[str, str]:
"""Return tags in dict form from cloudformation resource tags form (list of dicts)"""
tags = {}

View File

@ -300,7 +300,6 @@ class DataBrewBackend(BaseBackend):
dataset_path_options: Dict[str, Any],
tags: Dict[str, str],
) -> "FakeDataset":
if dataset_name not in self.datasets:
raise ResourceNotFoundException("One or more resources can't be found.")
@ -621,7 +620,6 @@ class BaseModelABCMeta(ABCMeta, type(BaseModel)): # type: ignore[misc]
class FakeJob(BaseModel, metaclass=BaseModelABCMeta): # type: ignore[misc]
ENCRYPTION_MODES = ("SSE-S3", "SSE-KMS")
LOG_SUBSCRIPTION_VALUES = ("ENABLE", "DISABLE")

View File

@ -29,7 +29,10 @@ class DataBrewResponse(BaseResponse):
tags = self.parameters.get("Tags")
return json.dumps(
self.databrew_backend.create_recipe(
recipe_name, recipe_description, recipe_steps, tags # type: ignore[arg-type]
recipe_name,
recipe_description,
recipe_steps,
tags, # type: ignore[arg-type]
).as_dict()
)
@ -98,7 +101,9 @@ class DataBrewResponse(BaseResponse):
recipe_steps = self.parameters.get("Steps")
self.databrew_backend.update_recipe(
recipe_name, recipe_description, recipe_steps # type: ignore[arg-type]
recipe_name,
recipe_description,
recipe_steps, # type: ignore[arg-type]
)
return json.dumps({"Name": recipe_name})
@ -141,7 +146,10 @@ class DataBrewResponse(BaseResponse):
tags = self.parameters.get("Tags")
ruleset = self.databrew_backend.update_ruleset(
ruleset_name, ruleset_description, ruleset_rules, tags # type: ignore[arg-type]
ruleset_name,
ruleset_description,
ruleset_rules,
tags, # type: ignore[arg-type]
)
return json.dumps(ruleset.as_dict())

View File

@ -91,7 +91,7 @@ class Pipeline(CloudFormationModel):
cloudformation_json: Dict[str, Any],
account_id: str,
region_name: str,
**kwargs: Any
**kwargs: Any,
) -> "Pipeline":
datapipeline_backend = datapipeline_backends[account_id][region_name]
properties = cloudformation_json["Properties"]

View File

@ -46,7 +46,6 @@ class Task(BaseModel):
class TaskExecution(BaseModel):
# For simplicity, task_execution can never fail
# Some documentation refers to this list:
# 'Status': 'QUEUED'|'LAUNCHING'|'PREPARING'|'TRANSFERRING'|'VERIFYING'|'SUCCESS'|'ERROR'
@ -105,7 +104,9 @@ class DataSyncBackend(BaseBackend):
self.task_executions: Dict[str, TaskExecution] = OrderedDict()
@staticmethod
def default_vpc_endpoint_service(service_region: str, zones: List[str]) -> List[Dict[str, Any]]: # type: ignore[misc]
def default_vpc_endpoint_service(
service_region: str, zones: List[str]
) -> List[Dict[str, Any]]: # type: ignore[misc]
"""Default VPC endpoint service."""
return BaseBackend.default_vpc_endpoint_service_factory(
service_region, zones, "datasync"

View File

@ -1,4 +1,5 @@
"""DAXBackend class with methods for supported APIs."""
from typing import Any, Dict, Iterable, List
from moto.core.base_backend import BackendDict, BaseBackend
@ -61,9 +62,9 @@ class DaxEndpoint:
def to_json(self, full: bool = False) -> Dict[str, Any]:
dct: Dict[str, Any] = {"Port": self.port}
if full:
dct[
"Address"
] = f"{self.name}.{self.cluster_hex}.dax-clusters.{self.region}.amazonaws.com"
dct["Address"] = (
f"{self.name}.{self.cluster_hex}.dax-clusters.{self.region}.amazonaws.com"
)
dct["URL"] = f"dax://{dct['Address']}"
return dct

View File

@ -1,4 +1,5 @@
"""dax base URL and path."""
from .responses import DAXResponse
url_bases = [

View File

@ -19,7 +19,9 @@ class DatabaseMigrationServiceBackend(BaseBackend):
self.replication_tasks: Dict[str, "FakeReplicationTask"] = {}
@staticmethod
def default_vpc_endpoint_service(service_region: str, zones: List[str]) -> List[Dict[str, Any]]: # type: ignore[misc]
def default_vpc_endpoint_service(
service_region: str, zones: List[str]
) -> List[Dict[str, Any]]: # type: ignore[misc]
"""Default VPC endpoint service."""
return BaseBackend.default_vpc_endpoint_service_factory(
service_region, zones, "dms"

View File

@ -1,4 +1,5 @@
"""Exceptions raised by the Directory Service service."""
from typing import List, Tuple
from moto.core.exceptions import JsonRESTError

View File

@ -1,4 +1,5 @@
"""DirectoryServiceBackend class with methods for supported APIs."""
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Tuple
@ -87,7 +88,8 @@ class Directory(BaseModel): # pylint: disable=too-many-instance-attributes
self.connect_settings["VpcId"] # type: ignore[index]
)
self.eni_ids, self.subnet_ips = self.create_eni(
self.security_group_id, self.connect_settings["SubnetIds"] # type: ignore[index]
self.security_group_id,
self.connect_settings["SubnetIds"], # type: ignore[index]
)
self.connect_settings["SecurityGroupId"] = self.security_group_id # type: ignore[index]
self.connect_settings["ConnectIps"] = self.subnet_ips # type: ignore[index]
@ -98,7 +100,8 @@ class Directory(BaseModel): # pylint: disable=too-many-instance-attributes
self.vpc_settings["VpcId"] # type: ignore[index]
)
self.eni_ids, self.subnet_ips = self.create_eni(
self.security_group_id, self.vpc_settings["SubnetIds"] # type: ignore[index]
self.security_group_id,
self.vpc_settings["SubnetIds"], # type: ignore[index]
)
self.vpc_settings["SecurityGroupId"] = self.security_group_id # type: ignore[index]
self.dns_ip_addrs = self.subnet_ips

View File

@ -1,4 +1,5 @@
"""Handles Directory Service requests, invokes methods, returns responses."""
import json
from moto.core.exceptions import InvalidToken

View File

@ -1,4 +1,5 @@
"""ds base URL and path."""
from .responses import DirectoryServiceResponse
url_bases = [

View File

@ -2,6 +2,7 @@
Note that ValidationExceptions are accumulative.
"""
import re
from typing import Any
@ -35,7 +36,7 @@ def validate_args(validators: Any) -> None:
err_msgs = []
# This eventually could be a switch (python 3.10), elminating the need
# for the above map and individual functions.
for (fieldname, value) in validators:
for fieldname, value in validators:
msg = validation_map[fieldname](value)
if msg:
err_msgs.append((fieldname, value, msg))

View File

@ -477,7 +477,9 @@ class DynamoDBBackend(BaseBackend):
validated_ast.normalize()
try:
UpdateExpressionExecutor(
validated_ast, item, expression_attribute_names # type: ignore[arg-type]
validated_ast,
item,
expression_attribute_names, # type: ignore[arg-type]
).execute()
except ItemSizeTooLarge:
raise ItemSizeToUpdateTooLarge()

View File

@ -76,7 +76,9 @@ class LocalSecondaryIndex(SecondaryIndex):
}
@staticmethod
def create(dct: Dict[str, Any], table_key_attrs: List[str]) -> "LocalSecondaryIndex": # type: ignore[misc]
def create(
dct: Dict[str, Any], table_key_attrs: List[str]
) -> "LocalSecondaryIndex": # type: ignore[misc]
return LocalSecondaryIndex(
index_name=dct["IndexName"],
schema=dct["KeySchema"],
@ -112,7 +114,9 @@ class GlobalSecondaryIndex(SecondaryIndex):
}
@staticmethod
def create(dct: Dict[str, Any], table_key_attrs: List[str]) -> "GlobalSecondaryIndex": # type: ignore[misc]
def create(
dct: Dict[str, Any], table_key_attrs: List[str]
) -> "GlobalSecondaryIndex": # type: ignore[misc]
return GlobalSecondaryIndex(
index_name=dct["IndexName"],
schema=dct["KeySchema"],
@ -443,9 +447,9 @@ class Table(CloudFormationModel):
}
if self.latest_stream_label:
results[base_key]["LatestStreamLabel"] = self.latest_stream_label
results[base_key][
"LatestStreamArn"
] = f"{self.table_arn}/stream/{self.latest_stream_label}"
results[base_key]["LatestStreamArn"] = (
f"{self.table_arn}/stream/{self.latest_stream_label}"
)
if self.stream_specification and self.stream_specification["StreamEnabled"]:
results[base_key]["StreamSpecification"] = self.stream_specification
if self.sse_specification and self.sse_specification.get("Enabled") is True:
@ -657,7 +661,6 @@ class Table(CloudFormationModel):
filter_expression: Any = None,
**filter_kwargs: Any,
) -> Tuple[List[Item], int, Optional[Dict[str, Any]]]:
# FIND POSSIBLE RESULTS
if index_name:
all_indexes = self.all_indexes()

View File

@ -257,7 +257,9 @@ class UpdateExpressionFunctionEvaluator(DepthFirstTraverser): # type: ignore[mi
raise NotImplementedError(f"Unsupported function for moto {function_name}")
@classmethod
def get_list_from_ddb_typed_value(cls, node: DDBTypedValue, function_name: str) -> DynamoType: # type: ignore[misc]
def get_list_from_ddb_typed_value(
cls, node: DDBTypedValue, function_name: str
) -> DynamoType: # type: ignore[misc]
assert isinstance(node, DDBTypedValue)
dynamo_value = node.get_value()
assert isinstance(dynamo_value, DynamoType)
@ -322,7 +324,9 @@ class ExecuteOperations(DepthFirstTraverser): # type: ignore[misc]
return dynamo_value
@classmethod
def get_sum(cls, left_operand: DynamoType, right_operand: DynamoType) -> DDBTypedValue: # type: ignore[misc]
def get_sum(
cls, left_operand: DynamoType, right_operand: DynamoType
) -> DDBTypedValue: # type: ignore[misc]
"""
Args:
left_operand(DynamoType):
@ -337,7 +341,9 @@ class ExecuteOperations(DepthFirstTraverser): # type: ignore[misc]
raise IncorrectOperandType("+", left_operand.type)
@classmethod
def get_subtraction(cls, left_operand: DynamoType, right_operand: DynamoType) -> DDBTypedValue: # type: ignore[misc]
def get_subtraction(
cls, left_operand: DynamoType, right_operand: DynamoType
) -> DDBTypedValue: # type: ignore[misc]
"""
Args:
left_operand(DynamoType):

View File

@ -29,7 +29,7 @@ def include_consumed_capacity(
Callable[["DynamoHandler"], Union[str, TYPE_RESPONSE]],
]:
def _inner(
f: Callable[..., Union[str, TYPE_RESPONSE]]
f: Callable[..., Union[str, TYPE_RESPONSE]],
) -> Callable[["DynamoHandler"], Union[str, TYPE_RESPONSE]]:
@wraps(f)
def _wrapper(

View File

@ -165,7 +165,9 @@ class Table(BaseModel):
def put_item(self, item_attrs: Dict[str, Any]) -> Item:
hash_value = DynamoType(item_attrs.get(self.hash_key_attr)) # type: ignore[arg-type]
if self.has_range_key:
range_value: Optional[DynamoType] = DynamoType(item_attrs.get(self.range_key_attr)) # type: ignore[arg-type]
range_value: Optional[DynamoType] = DynamoType(
item_attrs.get(self.range_key_attr)
) # type: ignore[arg-type]
else:
range_value = None

View File

@ -60,9 +60,9 @@ class ShardIterator(BaseModel):
self.sequence_number,
)
self.streams_backend.shard_iterators[
new_shard_iterator.arn
] = new_shard_iterator
self.streams_backend.shard_iterators[new_shard_iterator.arn] = (
new_shard_iterator
)
return {"NextShardIterator": new_shard_iterator.arn, "Records": items}
@ -128,7 +128,10 @@ class DynamoDBStreamsBackend(BaseBackend):
assert table.stream_shard.id == shard_id # type: ignore[union-attr]
shard_iterator = ShardIterator(
self, table.stream_shard, shard_iterator_type, sequence_number # type: ignore[arg-type]
self,
table.stream_shard,
shard_iterator_type,
sequence_number, # type: ignore[arg-type]
)
self.shard_iterators[shard_iterator.arn] = shard_iterator

View File

@ -119,9 +119,9 @@ class EBSBackend(BaseBackend):
"""
snapshot1 = self.snapshots[first_snapshot_id]
snapshot2 = self.snapshots[second_snapshot_id]
changed_blocks: Dict[
str, Tuple[str, Optional[str]]
] = dict() # {idx: (token1, token2), ..}
changed_blocks: Dict[str, Tuple[str, Optional[str]]] = (
dict()
) # {idx: (token1, token2), ..}
for idx in snapshot1.blocks:
block1 = snapshot1.blocks[idx]
if idx in snapshot2.blocks:

View File

@ -1,4 +1,5 @@
"""Handles incoming ebs requests, invokes methods, returns responses."""
import json
from typing import Any
@ -24,14 +25,18 @@ class EBSResponse(BaseResponse):
if request.method == "POST":
return self.start_snapshot()
def snapshot_block(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def snapshot_block(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers, use_raw_body=True)
if request.method == "PUT":
return self.put_snapshot_block(full_url, headers)
if request.method == "GET":
return self.get_snapshot_block()
def snapshot_blocks(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[return]
def snapshot_blocks(
self, request: Any, full_url: str, headers: Any
) -> TYPE_RESPONSE: # type: ignore[return]
self.setup_class(request, full_url, headers)
if request.method == "GET":
return self.list_snapshot_blocks()

View File

@ -1,4 +1,5 @@
"""ebs base URL and path."""
from .responses import EBSResponse
url_bases = [r"https?://ebs\.(.+)\.amazonaws\.com"]

View File

@ -164,7 +164,9 @@ class EC2Backend(
ip[2] += 16 # type: ignore
@staticmethod
def default_vpc_endpoint_service(service_region: str, zones: List[str]) -> List[Dict[str, Any]]: # type: ignore[misc]
def default_vpc_endpoint_service(
service_region: str, zones: List[str]
) -> List[Dict[str, Any]]: # type: ignore[misc]
"""Default VPC endpoint service."""
return BaseBackend.default_vpc_endpoint_service_factory(
service_region, zones, "ec2"

View File

@ -172,7 +172,8 @@ class AmiBackend:
latest_amis = cast(
List[Dict[str, Any]],
load_resource(
__name__, f"../resources/{path}/{self.region_name}.json" # type: ignore[attr-defined]
__name__,
f"../resources/{path}/{self.region_name}.json", # type: ignore[attr-defined]
),
)
for ami in latest_amis:

View File

@ -83,7 +83,6 @@ class DHCPOptionsSetBackend:
netbios_name_servers: Optional[List[str]] = None,
netbios_node_type: Optional[str] = None,
) -> DHCPOptionsSet:
NETBIOS_NODE_TYPES = [1, 2, 4, 8]
for field_value in domain_name_servers, ntp_servers, netbios_name_servers:

View File

@ -86,7 +86,7 @@ class VolumeAttachment(CloudFormationModel):
cloudformation_json: Any,
account_id: str,
region_name: str,
**kwargs: Any
**kwargs: Any,
) -> "VolumeAttachment":
from ..models import ec2_backends
@ -160,7 +160,7 @@ class Volume(TaggedEC2Resource, CloudFormationModel):
cloudformation_json: Any,
account_id: str,
region_name: str,
**kwargs: Any
**kwargs: Any,
) -> "Volume":
from ..models import ec2_backends

View File

@ -55,7 +55,7 @@ class ElasticAddress(TaggedEC2Resource, CloudFormationModel):
cloudformation_json: Any,
account_id: str,
region_name: str,
**kwargs: Any
**kwargs: Any,
) -> "ElasticAddress":
from ..models import ec2_backends

View File

@ -309,7 +309,7 @@ class NetworkInterfaceBackend:
enis = list(self.enis.values())
if filters:
for (_filter, _filter_value) in filters.items():
for _filter, _filter_value in filters.items():
if _filter == "network-interface-id":
_filter = "id"
enis = [

View File

@ -28,7 +28,6 @@ class Fleet(TaggedEC2Resource):
valid_until: str,
tag_specifications: List[Dict[str, Any]],
):
self.ec2_backend = ec2_backend
self.id = fleet_id
self.spot_options = spot_options
@ -269,7 +268,6 @@ class FleetsBackend:
valid_until: str,
tag_specifications: List[Dict[str, Any]],
) -> Fleet:
fleet_id = random_fleet_id()
fleet = Fleet(
self,
@ -309,7 +307,6 @@ class FleetsBackend:
def delete_fleets(
self, fleet_ids: List[str], terminate_instances: bool
) -> List[Fleet]:
fleets = []
for fleet_id in fleet_ids:
fleet = self.fleets[fleet_id]

View File

@ -50,7 +50,9 @@ class IamInstanceProfileAssociationBackend:
iam_association_id = random_iam_instance_profile_association_id()
instance_profile = filter_iam_instance_profiles(
self.account_id, iam_instance_profile_arn, iam_instance_profile_name # type: ignore[attr-defined]
self.account_id,
iam_instance_profile_arn,
iam_instance_profile_name, # type: ignore[attr-defined]
)
if instance_id in self.iam_instance_profile_associations.keys():
@ -63,9 +65,9 @@ class IamInstanceProfileAssociationBackend:
instance_profile,
)
# Regarding to AWS there can be only one association with ec2.
self.iam_instance_profile_associations[
instance_id
] = iam_instance_profile_association
self.iam_instance_profile_associations[instance_id] = (
iam_instance_profile_association
)
return iam_instance_profile_association
def describe_iam_instance_profile_associations(
@ -125,7 +127,9 @@ class IamInstanceProfileAssociationBackend:
iam_instance_profile_arn: Optional[str] = None,
) -> IamInstanceProfileAssociation:
instance_profile = filter_iam_instance_profiles(
self.account_id, iam_instance_profile_arn, iam_instance_profile_name # type: ignore[attr-defined]
self.account_id,
iam_instance_profile_arn,
iam_instance_profile_name, # type: ignore[attr-defined]
)
iam_instance_profile_association = None

View File

@ -383,7 +383,9 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel):
return self._state.name == "running"
def delete(
self, account_id: str, region: str # pylint: disable=unused-argument
self,
account_id: str,
region: str, # pylint: disable=unused-argument
) -> None:
self.terminate()
@ -666,7 +668,8 @@ class InstanceBackend:
raise InvalidInstanceTypeError(kwargs["instance_type"])
security_groups = [
self.get_security_group_by_name_or_id(name) for name in security_group_names # type: ignore[attr-defined]
self.get_security_group_by_name_or_id(name)
for name in security_group_names # type: ignore[attr-defined]
]
for sg_id in kwargs.pop("security_group_ids", []):

View File

@ -127,9 +127,8 @@ class LaunchTemplate(TaggedEC2Resource, CloudFormationModel):
cloudformation_json: Any,
account_id: str,
region_name: str,
**kwargs: Any
**kwargs: Any,
) -> "LaunchTemplate":
from ..models import ec2_backends
backend = ec2_backends[account_id][region_name]
@ -160,7 +159,6 @@ class LaunchTemplate(TaggedEC2Resource, CloudFormationModel):
account_id: str,
region_name: str,
) -> "LaunchTemplate":
from ..models import ec2_backends
backend = ec2_backends[account_id][region_name]
@ -184,7 +182,6 @@ class LaunchTemplate(TaggedEC2Resource, CloudFormationModel):
account_id: str,
region_name: str,
) -> None:
from ..models import ec2_backends
backend = ec2_backends[account_id][region_name]

View File

@ -103,7 +103,9 @@ class ManagedPrefixListBackend:
return self.managed_prefix_lists.get(prefix_list_id)
def delete_managed_prefix_list(self, prefix_list_id: str) -> ManagedPrefixList:
managed_prefix_list: ManagedPrefixList = self.managed_prefix_lists.get(prefix_list_id) # type: ignore
managed_prefix_list: ManagedPrefixList = self.managed_prefix_lists.get(
prefix_list_id
) # type: ignore
managed_prefix_list.state = "delete-complete"
return managed_prefix_list

View File

@ -64,7 +64,7 @@ class NatGateway(CloudFormationModel, TaggedEC2Resource):
cloudformation_json: Any,
account_id: str,
region_name: str,
**kwargs: Any
**kwargs: Any,
) -> "NatGateway":
from ..models import ec2_backends

View File

@ -79,7 +79,6 @@ class NetworkAclBackend:
port_range_from: Optional[int],
port_range_to: Optional[int],
) -> "NetworkAclEntry":
network_acl = self.get_network_acl(network_acl_id)
if any(
entry.egress == egress and entry.rule_number == rule_number
@ -129,7 +128,6 @@ class NetworkAclBackend:
port_range_from: int,
port_range_to: int,
) -> "NetworkAclEntry":
self.delete_network_acl_entry(network_acl_id, rule_number, egress)
network_acl_entry = self.create_network_acl_entry(
network_acl_id,
@ -148,7 +146,6 @@ class NetworkAclBackend:
def replace_network_acl_association(
self, association_id: str, network_acl_id: str
) -> "NetworkAclAssociation":
# lookup existing association for subnet and delete it
default_acl = next(
value

View File

@ -488,7 +488,9 @@ class RouteBackend:
)
route.instance = self.get_instance(instance_id) if instance_id else None # type: ignore[attr-defined]
route.interface = self.get_network_interface(interface_id) if interface_id else None # type: ignore[attr-defined]
route.interface = (
self.get_network_interface(interface_id) if interface_id else None
) # type: ignore[attr-defined]
route.vpc_pcx = (
self.get_vpc_peering_connection(vpc_peering_connection_id) # type: ignore[attr-defined]
if vpc_peering_connection_id

View File

@ -226,7 +226,7 @@ class SecurityGroup(TaggedEC2Resource, CloudFormationModel):
cloudformation_json: Any,
account_id: str,
region_name: str,
**kwargs: Any
**kwargs: Any,
) -> "SecurityGroup":
from ..models import ec2_backends
@ -310,7 +310,9 @@ class SecurityGroup(TaggedEC2Resource, CloudFormationModel):
security_group.delete(account_id, region_name)
def delete(
self, account_id: str, region_name: str # pylint: disable=unused-argument
self,
account_id: str,
region_name: str, # pylint: disable=unused-argument
) -> None:
"""Not exposed as part of the ELB API - used for CloudFormation."""
self.ec2_backend.delete_security_group(group_id=self.id)
@ -627,7 +629,9 @@ class SecurityGroupBackend:
return results
@staticmethod
def _match_sg_rules(rules_list: List[SecurityRule], filters: Any) -> List[SecurityRule]: # type: ignore[misc]
def _match_sg_rules(
rules_list: List[SecurityRule], filters: Any
) -> List[SecurityRule]: # type: ignore[misc]
results = []
for rule in rules_list:
if rule.match_tags(filters):
@ -802,7 +806,9 @@ class SecurityGroupBackend:
security_rule_ids: Optional[List[str]] = None,
vpc_id: Optional[str] = None,
) -> None:
group: SecurityGroup = self.get_security_group_by_name_or_id(group_name_or_id, vpc_id) # type: ignore[assignment]
group: SecurityGroup = self.get_security_group_by_name_or_id(
group_name_or_id, vpc_id
) # type: ignore[assignment]
if security_rule_ids:
group.ingress_rules = [
@ -971,7 +977,9 @@ class SecurityGroupBackend:
security_rule_ids: Optional[List[str]] = None,
vpc_id: Optional[str] = None,
) -> None:
group: SecurityGroup = self.get_security_group_by_name_or_id(group_name_or_id, vpc_id) # type: ignore[assignment]
group: SecurityGroup = self.get_security_group_by_name_or_id(
group_name_or_id, vpc_id
) # type: ignore[assignment]
if security_rule_ids:
group.egress_rules = [
@ -1266,7 +1274,7 @@ class SecurityGroupIngress(CloudFormationModel):
cloudformation_json: Any,
account_id: str,
region_name: str,
**kwargs: Any
**kwargs: Any,
) -> "SecurityGroupIngress":
from ..models import ec2_backends

Some files were not shown because too many files have changed in this diff Show More