diff --git a/admin/create_secrets_files.py b/admin/create_secrets_files.py index 58aca18fe..402f17dc0 100644 --- a/admin/create_secrets_files.py +++ b/admin/create_secrets_files.py @@ -108,7 +108,7 @@ def main() -> None: """, ) - file.write_text(file_contents) + file.write_text(data=file_contents) sys.stdout.write(f"Created database {file.name}\n") files_to_create.pop() diff --git a/docs/source/conf.py b/docs/source/conf.py index 308d9bbf1..d02c56bbc 100755 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -43,7 +43,7 @@ # This method of getting the release from the version goes hand in hand with # the ``post-release`` versioning scheme chosen in the ``setuptools-scm`` # configuration. -release = version.split(".post")[0] +release = version.split(sep=".post")[0] project_metadata = importlib.metadata.metadata(distribution_name=project) diff --git a/src/mock_vws/_database_matchers.py b/src/mock_vws/_database_matchers.py index 5e78cf083..211e4c70f 100644 --- a/src/mock_vws/_database_matchers.py +++ b/src/mock_vws/_database_matchers.py @@ -35,9 +35,12 @@ def get_database_matching_client_keys( Raises: ValueError: No database matches the given request. """ - content_type = request_headers.get("Content-Type", "").split(sep=";")[0] - auth_header = request_headers.get("Authorization") - date = request_headers.get("Date", "") + request_headers_dict = dict(request_headers) + content_type = request_headers_dict.get("Content-Type", "").split(sep=";")[ + 0 + ] + auth_header = request_headers_dict.get("Authorization") + date = request_headers_dict.get("Date", "") for database in databases: expected_authorization_header = authorization_header( @@ -80,9 +83,11 @@ def get_database_matching_server_keys( Raises: ValueError: No database matches the given request. """ - content_type = request_headers.get("Content-Type", "").split(sep=";")[0] - auth_header = request_headers.get("Authorization") - date = request_headers.get("Date", "") + request_headers_dict = dict(request_headers) + content_type_header = request_headers_dict.get("Content-Type", "") + content_type = content_type_header.split(sep=";")[0] + auth_header = request_headers_dict.get("Authorization") + date = request_headers_dict.get("Date", "") for database in databases: expected_authorization_header = authorization_header( diff --git a/src/mock_vws/_flask_server/healthcheck.py b/src/mock_vws/_flask_server/healthcheck.py index a20f3a8cc..39c37a5e2 100644 --- a/src/mock_vws/_flask_server/healthcheck.py +++ b/src/mock_vws/_flask_server/healthcheck.py @@ -15,9 +15,9 @@ def flask_app_healthy(port: int) -> bool: """ Check if the Flask app is healthy. """ - conn = http.client.HTTPConnection("localhost", port) + conn = http.client.HTTPConnection(host="localhost", port=port) try: - conn.request("GET", "/some-random-endpoint") + conn.request(method="GET", url="/some-random-endpoint") response = conn.getresponse() except (TimeoutError, http.client.HTTPException, socket.gaierror): return False diff --git a/src/mock_vws/_flask_server/target_manager.py b/src/mock_vws/_flask_server/target_manager.py index 78f944eb1..8c06246f0 100644 --- a/src/mock_vws/_flask_server/target_manager.py +++ b/src/mock_vws/_flask_server/target_manager.py @@ -66,7 +66,7 @@ class TargetManagerSettings(BaseSettings): @TARGET_MANAGER_FLASK_APP.route( - "/databases/", + rule="/databases/", methods=[HTTPMethod.DELETE], ) @beartype @@ -88,7 +88,7 @@ def delete_database(database_name: str) -> Response: return Response(response="", status=HTTPStatus.OK) -@TARGET_MANAGER_FLASK_APP.route("/databases", methods=[HTTPMethod.GET]) +@TARGET_MANAGER_FLASK_APP.route(rule="/databases", methods=[HTTPMethod.GET]) @beartype def get_databases() -> Response: """ @@ -101,7 +101,7 @@ def get_databases() -> Response: ) -@TARGET_MANAGER_FLASK_APP.route("/databases", methods=[HTTPMethod.POST]) +@TARGET_MANAGER_FLASK_APP.route(rule="/databases", methods=[HTTPMethod.POST]) @beartype def create_database() -> Response: """Create a new database. @@ -184,7 +184,7 @@ def create_database() -> Response: TARGET_MANAGER.add_database(database=database) except ValueError as exc: return Response( - response=str(exc), + response=str(object=exc), status=HTTPStatus.CONFLICT, ) @@ -195,7 +195,7 @@ def create_database() -> Response: @TARGET_MANAGER_FLASK_APP.route( - "/databases//targets", + rule="/databases//targets", methods=[HTTPMethod.POST], ) @beartype @@ -233,7 +233,7 @@ def create_target(database_name: str) -> Response: @TARGET_MANAGER_FLASK_APP.route( - "/databases//targets/", + rule="/databases//targets/", methods={HTTPMethod.DELETE}, ) @beartype @@ -258,7 +258,7 @@ def delete_target(database_name: str, target_id: str) -> Response: @TARGET_MANAGER_FLASK_APP.route( - "/databases//targets/", + rule="/databases//targets/", methods=[HTTPMethod.PUT], ) def update_target(database_name: str, target_id: str) -> Response: diff --git a/src/mock_vws/_flask_server/vwq.py b/src/mock_vws/_flask_server/vwq.py index 924941bca..dee12db42 100644 --- a/src/mock_vws/_flask_server/vwq.py +++ b/src/mock_vws/_flask_server/vwq.py @@ -109,7 +109,7 @@ def set_terminate_wsgi_input() -> None: request.environ["wsgi.input_terminated"] = True -@CLOUDRECO_FLASK_APP.errorhandler(ValidatorError) +@CLOUDRECO_FLASK_APP.errorhandler(code_or_exception=ValidatorError) def handle_exceptions(exc: ValidatorError) -> Response: """ Return the error response associated with the given exception. @@ -125,7 +125,7 @@ def handle_exceptions(exc: ValidatorError) -> Response: return response -@CLOUDRECO_FLASK_APP.route("/v1/query", methods=[HTTPMethod.POST]) +@CLOUDRECO_FLASK_APP.route(rule="/v1/query", methods=[HTTPMethod.POST]) def query() -> Response: """ Perform an image recognition query. diff --git a/src/mock_vws/_flask_server/vws.py b/src/mock_vws/_flask_server/vws.py index 402b41e2c..2d2f9ac9f 100644 --- a/src/mock_vws/_flask_server/vws.py +++ b/src/mock_vws/_flask_server/vws.py @@ -140,7 +140,7 @@ def validate_request() -> None: ) -@VWS_FLASK_APP.errorhandler(ValidatorError) +@VWS_FLASK_APP.errorhandler(code_or_exception=ValidatorError) def handle_exceptions(exc: ValidatorError) -> Response: """ Return the error response associated with the given exception. @@ -156,7 +156,7 @@ def handle_exceptions(exc: ValidatorError) -> Response: return response -@VWS_FLASK_APP.route("/targets", methods=[HTTPMethod.POST]) +@VWS_FLASK_APP.route(rule="/targets", methods=[HTTPMethod.POST]) @beartype def add_target() -> Response: """Add a target. @@ -228,7 +228,9 @@ def add_target() -> Response: ) -@VWS_FLASK_APP.route("/targets/", methods=[HTTPMethod.GET]) +@VWS_FLASK_APP.route( + rule="/targets/", methods=[HTTPMethod.GET] +) @beartype def get_target(target_id: str) -> Response: """Get details of a target. @@ -283,7 +285,7 @@ def get_target(target_id: str) -> Response: @VWS_FLASK_APP.route( - "/targets/", + rule="/targets/", methods=[HTTPMethod.DELETE], ) def delete_target(target_id: str) -> Response: @@ -337,7 +339,7 @@ def delete_target(target_id: str) -> Response: ) -@VWS_FLASK_APP.route("/summary", methods=[HTTPMethod.GET]) +@VWS_FLASK_APP.route(rule="/summary", methods=[HTTPMethod.GET]) @beartype def database_summary() -> Response: """Get a database summary report. @@ -390,7 +392,10 @@ def database_summary() -> Response: ) -@VWS_FLASK_APP.route("/summary/", methods=[HTTPMethod.GET]) +@VWS_FLASK_APP.route( + rule="/summary/", + methods=[HTTPMethod.GET], +) def target_summary(target_id: str) -> Response: """Get a summary report for a target. @@ -415,7 +420,7 @@ def target_summary(target_id: str) -> Response: "result_code": ResultCodes.SUCCESS.value, "database_name": database.database_name, "target_name": target.name, - "upload_date": target.upload_date.strftime("%Y-%m-%d"), + "upload_date": target.upload_date.strftime(format="%Y-%m-%d"), "active_flag": target.active_flag, "tracking_rating": target.tracking_rating, "total_recos": target.total_recos, @@ -441,7 +446,7 @@ def target_summary(target_id: str) -> Response: @VWS_FLASK_APP.route( - "/duplicates/", + rule="/duplicates/", methods=[HTTPMethod.GET], ) @beartype @@ -503,7 +508,7 @@ def get_duplicates(target_id: str) -> Response: ) -@VWS_FLASK_APP.route("/targets", methods=[HTTPMethod.GET]) +@VWS_FLASK_APP.route(rule="/targets", methods=[HTTPMethod.GET]) def target_list() -> Response: """Get a list of all targets. @@ -543,7 +548,9 @@ def target_list() -> Response: ) -@VWS_FLASK_APP.route("/targets/", methods=[HTTPMethod.PUT]) +@VWS_FLASK_APP.route( + rule="/targets/", methods=[HTTPMethod.PUT] +) def update_target(target_id: str) -> Response: """Update a target. diff --git a/src/mock_vws/_query_tools.py b/src/mock_vws/_query_tools.py index 9a4a7a0a0..520afd9ab 100644 --- a/src/mock_vws/_query_tools.py +++ b/src/mock_vws/_query_tools.py @@ -54,8 +54,11 @@ def get_query_match_response_text( content_length=len(request_body), ) - max_num_results = fields.get("max_num_results", "1") - include_target_data = fields.get("include_target_data", "top").lower() + max_num_results = fields.get(key="max_num_results", default="1") + include_target_data = fields.get( + key="include_target_data", + default="top", + ).lower() image_part = files["image"] image_value = image_part.stream.read() diff --git a/src/mock_vws/_query_validators/content_type_validators.py b/src/mock_vws/_query_validators/content_type_validators.py index 89b8dddd8..bd474c6ab 100644 --- a/src/mock_vws/_query_validators/content_type_validators.py +++ b/src/mock_vws/_query_validators/content_type_validators.py @@ -38,7 +38,8 @@ def validate_content_type_header( NoContentTypeError: The content type header is either empty or not given. """ - content_type_header = request_headers.get("Content-Type", "") + request_headers_dict = dict(request_headers) + content_type_header = request_headers_dict.get("Content-Type", "") if not content_type_header: _LOGGER.warning(msg="The content type header is empty.") raise NoContentTypeError diff --git a/src/mock_vws/_query_validators/date_validators.py b/src/mock_vws/_query_validators/date_validators.py index b5cfb2dea..d02e44aaa 100644 --- a/src/mock_vws/_query_validators/date_validators.py +++ b/src/mock_vws/_query_validators/date_validators.py @@ -88,7 +88,7 @@ def validate_date_in_range(*, request_headers: Mapping[str, str]) -> None: date_header = request_headers["Date"] gmt = ZoneInfo(key="GMT") - date = datetime.datetime.fromtimestamp(0, tz=gmt) + date = datetime.datetime.fromtimestamp(timestamp=0, tz=gmt) for date_format in _accepted_date_formats(): with contextlib.suppress(ValueError): date = datetime.datetime.strptime( diff --git a/src/mock_vws/_query_validators/exceptions.py b/src/mock_vws/_query_validators/exceptions.py index bf1cb7b37..87b87390a 100644 --- a/src/mock_vws/_query_validators/exceptions.py +++ b/src/mock_vws/_query_validators/exceptions.py @@ -53,7 +53,7 @@ def __init__(self) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -85,7 +85,7 @@ def __init__(self) -> None: "Server": "nginx", "Date": date, "WWW-Authenticate": "KWS", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -121,7 +121,7 @@ def __init__(self) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -164,7 +164,7 @@ def __init__(self) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -207,7 +207,7 @@ def __init__(self) -> None: "Server": "nginx", "Date": date, "WWW-Authenticate": "VWS", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -245,7 +245,7 @@ def __init__(self) -> None: "Server": "nginx", "Date": date, "WWW-Authenticate": "VWS", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -277,7 +277,7 @@ def __init__(self) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -310,7 +310,7 @@ def __init__(self) -> None: "Server": "nginx", "Date": date, "WWW-Authenticate": "KWS", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -344,7 +344,7 @@ def __init__(self) -> None: "Server": "nginx", "Date": date, "WWW-Authenticate": "KWS", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -376,7 +376,7 @@ def __init__(self) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -418,7 +418,7 @@ def __init__(self) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -455,7 +455,7 @@ def __init__(self, given_value: str) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -492,7 +492,7 @@ def __init__(self, given_value: str) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -531,7 +531,7 @@ def __init__(self, given_value: str) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -562,7 +562,7 @@ def __init__(self) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -593,7 +593,7 @@ def __init__(self) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -628,7 +628,7 @@ def __init__(self) -> None: "Connection": "keep-alive", "Server": "nginx", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -652,7 +652,7 @@ def __init__(self) -> None: # pragma: no cover self.response_text = "" self.headers = { "Connection": "keep-alive", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -675,7 +675,7 @@ def __init__(self) -> None: self.response_text = "" self.headers = { "Connection": "Close", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -719,7 +719,7 @@ def __init__(self) -> None: # pragma: no cover "Date": date, "Server": "nginx", "Content-Type": "text/html", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -771,5 +771,5 @@ def __init__(self) -> None: "Server": "nginx", "Cache-Control": "must-revalidate,no-cache,no-store", "Date": date, - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } diff --git a/src/mock_vws/_query_validators/image_validators.py b/src/mock_vws/_query_validators/image_validators.py index e299b4384..203c606de 100644 --- a/src/mock_vws/_query_validators/image_validators.py +++ b/src/mock_vws/_query_validators/image_validators.py @@ -44,7 +44,7 @@ def validate_image_field_given( boundary=boundary.encode(encoding="utf-8"), content_length=len(request_body), ) - if files.get("image") is not None: + if files.get(key="image") is not None: return _LOGGER.warning(msg="The image field is not given.") diff --git a/src/mock_vws/_query_validators/include_target_data_validators.py b/src/mock_vws/_query_validators/include_target_data_validators.py index 684a880e8..5f8277ade 100644 --- a/src/mock_vws/_query_validators/include_target_data_validators.py +++ b/src/mock_vws/_query_validators/include_target_data_validators.py @@ -40,7 +40,7 @@ def validate_include_target_data( boundary=boundary.encode(encoding="utf-8"), content_length=len(request_body), ) - include_target_data = fields.get("include_target_data", "top") + include_target_data = fields.get(key="include_target_data", default="top") allowed_included_target_data = {"top", "all", "none"} if include_target_data.lower() in allowed_included_target_data: return diff --git a/src/mock_vws/_query_validators/num_results_validators.py b/src/mock_vws/_query_validators/num_results_validators.py index bbfe12d0c..ff4b99ae1 100644 --- a/src/mock_vws/_query_validators/num_results_validators.py +++ b/src/mock_vws/_query_validators/num_results_validators.py @@ -46,7 +46,7 @@ def validate_max_num_results( boundary=boundary.encode(encoding="utf-8"), content_length=len(request_body), ) - max_num_results = fields.get("max_num_results", "1") + max_num_results = fields.get(key="max_num_results", default="1") try: max_num_results_int = int(max_num_results) diff --git a/src/mock_vws/_requests_mock_server/mock_web_query_api.py b/src/mock_vws/_requests_mock_server/mock_web_query_api.py index abc125c5c..bbe00b7a5 100644 --- a/src/mock_vws/_requests_mock_server/mock_web_query_api.py +++ b/src/mock_vws/_requests_mock_server/mock_web_query_api.py @@ -136,6 +136,6 @@ def query(self, request: PreparedRequest) -> _ResponseType: "Content-Type": "application/json", "Server": "nginx", "Date": date, - "Content-Length": str(len(response_text)), + "Content-Length": str(object=len(response_text)), } return HTTPStatus.OK, headers, response_text diff --git a/src/mock_vws/_requests_mock_server/mock_web_services_api.py b/src/mock_vws/_requests_mock_server/mock_web_services_api.py index 7aea34ad6..dbe81ac11 100644 --- a/src/mock_vws/_requests_mock_server/mock_web_services_api.py +++ b/src/mock_vws/_requests_mock_server/mock_web_services_api.py @@ -195,7 +195,7 @@ def add_target(self, request: PreparedRequest) -> _ResponseType: "Content-Type": "application/json", "server": "envoy", "Date": date, - "Content-Length": str(len(body_json)), + "Content-Length": str(object=len(body_json)), "x-envoy-upstream-service-time": "5", "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", @@ -260,7 +260,7 @@ def delete_target(self, request: PreparedRequest) -> _ResponseType: body_json = json_dump(body=body) headers = { "Connection": "keep-alive", - "Content-Length": str(len(body_json)), + "Content-Length": str(object=len(body_json)), "Content-Type": "application/json", "Date": date, "server": "envoy", @@ -321,7 +321,7 @@ def database_summary(self, request: PreparedRequest) -> _ResponseType: body_json = json_dump(body=body) headers = { "Connection": "keep-alive", - "Content-Length": str(len(body_json)), + "Content-Length": str(object=len(body_json)), "Content-Type": "application/json", "Date": date, "server": "envoy", @@ -375,7 +375,7 @@ def target_list(self, request: PreparedRequest) -> _ResponseType: body_json = json_dump(body=body) headers = { "Connection": "keep-alive", - "Content-Length": str(len(body_json)), + "Content-Length": str(object=len(body_json)), "Content-Type": "application/json", "Date": date, "server": "envoy", @@ -440,7 +440,7 @@ def get_target(self, request: PreparedRequest) -> _ResponseType: body_json = json_dump(body=body) headers = { "Connection": "keep-alive", - "Content-Length": str(len(body_json)), + "Content-Length": str(object=len(body_json)), "Content-Type": "application/json", "Date": date, "server": "envoy", @@ -510,7 +510,7 @@ def get_duplicates(self, request: PreparedRequest) -> _ResponseType: body_json = json_dump(body=body) headers = { "Connection": "keep-alive", - "Content-Length": str(len(body_json)), + "Content-Length": str(object=len(body_json)), "Content-Type": "application/json", "Date": date, "server": "envoy", @@ -626,7 +626,7 @@ def update_target(self, request: PreparedRequest) -> _ResponseType: "Content-Type": "application/json", "server": "envoy", "Date": date, - "Content-Length": str(len(body_json)), + "Content-Length": str(object=len(body_json)), "x-envoy-upstream-service-time": "5", "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", @@ -676,7 +676,7 @@ def target_summary(self, request: PreparedRequest) -> _ResponseType: "result_code": ResultCodes.SUCCESS.value, "database_name": database.database_name, "target_name": target.name, - "upload_date": target.upload_date.strftime("%Y-%m-%d"), + "upload_date": target.upload_date.strftime(format="%Y-%m-%d"), "active_flag": target.active_flag, "tracking_rating": target.tracking_rating, "total_recos": target.total_recos, @@ -686,7 +686,7 @@ def target_summary(self, request: PreparedRequest) -> _ResponseType: body_json = json_dump(body=body) headers = { "Connection": "keep-alive", - "Content-Length": str(len(body_json)), + "Content-Length": str(object=len(body_json)), "Content-Type": "application/json", "Date": date, "server": "envoy", diff --git a/src/mock_vws/_services_validators/content_length_validators.py b/src/mock_vws/_services_validators/content_length_validators.py index a9728e4d6..9e2cc966b 100644 --- a/src/mock_vws/_services_validators/content_length_validators.py +++ b/src/mock_vws/_services_validators/content_length_validators.py @@ -33,7 +33,11 @@ def validate_content_length_header_is_int( integer """ body_length = len(request_body) - given_content_length = request_headers.get("Content-Length", body_length) + request_headers_dict = dict(request_headers) + given_content_length = request_headers_dict.get( + "Content-Length", + body_length, + ) try: int(given_content_length) @@ -59,7 +63,11 @@ def validate_content_length_header_not_too_large( that the content length is greater than the body length. """ body_length = len(request_body) - given_content_length = request_headers.get("Content-Length", body_length) + request_headers_dict = dict(request_headers) + given_content_length = request_headers_dict.get( + "Content-Length", + body_length, + ) given_content_length_value = int(given_content_length) # We skip coverage here as running a test to cover this is very slow. if given_content_length_value > body_length: # pragma: no cover @@ -84,7 +92,11 @@ def validate_content_length_header_not_too_small( the content length is smaller than the body length. """ body_length = len(request_body) - given_content_length = request_headers.get("Content-Length", body_length) + request_headers_dict = dict(request_headers) + given_content_length = request_headers_dict.get( + "Content-Length", + body_length, + ) given_content_length_value = int(given_content_length) if given_content_length_value < body_length: diff --git a/src/mock_vws/_services_validators/content_type_validators.py b/src/mock_vws/_services_validators/content_type_validators.py index 0e98eb8bd..4c97c4cdf 100644 --- a/src/mock_vws/_services_validators/content_type_validators.py +++ b/src/mock_vws/_services_validators/content_type_validators.py @@ -30,10 +30,14 @@ def validate_content_type_header_given( AuthenticationFailureError: No ``Content-Type`` header is given and the request requires one. """ + request_headers_dict = dict(request_headers) request_needs_content_type = bool( request_method in {HTTPMethod.POST, HTTPMethod.PUT}, ) - if request_headers.get("Content-Type") or not request_needs_content_type: + if ( + request_headers_dict.get("Content-Type") + or not request_needs_content_type + ): return _LOGGER.warning(msg="No Content-Type header is given.") diff --git a/src/mock_vws/_services_validators/exceptions.py b/src/mock_vws/_services_validators/exceptions.py index 0eeda683f..c978ad25d 100644 --- a/src/mock_vws/_services_validators/exceptions.py +++ b/src/mock_vws/_services_validators/exceptions.py @@ -59,7 +59,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -99,7 +99,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -139,7 +139,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -178,7 +178,7 @@ def __init__(self, *, status_code: HTTPStatus) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -218,7 +218,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -258,7 +258,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -287,7 +287,7 @@ def __init__(self) -> None: resources_dir = Path(__file__).parent.parent / "resources" filename = "oops_error_occurred_response.html" oops_resp_file = resources_dir / filename - text = str(oops_resp_file.read_text()) + text = str(object=oops_resp_file.read_text()) self.response_text = text date = email.utils.formatdate( timeval=None, @@ -300,7 +300,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -340,7 +340,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -380,7 +380,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -420,7 +420,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -451,7 +451,7 @@ def __init__(self) -> None: # pragma: no cover ) self.response_text = "stream timeout" self.headers = { - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "Date": date, "server": "envoy", "Content-Type": "text/plain", @@ -492,7 +492,7 @@ def __init__(self) -> None: ) self.headers = { "Connection": "close", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "Date": date, "Server": "awselb/2.0", "Content-Type": "text/html", @@ -525,7 +525,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), } @@ -562,7 +562,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", @@ -601,7 +601,7 @@ def __init__(self) -> None: "server": "envoy", "Date": date, "x-envoy-upstream-service-time": "5", - "Content-Length": str(len(self.response_text)), + "Content-Length": str(object=len(self.response_text)), "strict-transport-security": "max-age=31536000", "x-aws-region": "us-east-2, us-west-2", "x-content-type-options": "nosniff", diff --git a/src/mock_vws/image_matchers.py b/src/mock_vws/image_matchers.py index b1a3c2fc2..eba39996a 100644 --- a/src/mock_vws/image_matchers.py +++ b/src/mock_vws/image_matchers.py @@ -83,16 +83,19 @@ def __call__( first_image_resized = first_image.resize(size=target_size) second_image_resized = second_image.resize(size=target_size) - first_image_np = np.array(first_image_resized, dtype=np.float32) - first_image_tensor = torch.tensor(first_image_np).float() / 255 + first_image_np = np.array(object=first_image_resized, dtype=np.float32) + first_image_tensor = torch.tensor(data=first_image_np).float() / 255 first_image_tensor = first_image_tensor.view( first_image_resized.size[1], first_image_resized.size[0], len(first_image_resized.getbands()), ) - second_image_np = np.array(second_image_resized, dtype=np.float32) - second_image_tensor = torch.tensor(second_image_np).float() / 255 + second_image_np = np.array( + object=second_image_resized, + dtype=np.float32, + ) + second_image_tensor = torch.tensor(data=second_image_np).float() / 255 second_image_tensor = second_image_tensor.view( second_image_resized.size[1], second_image_resized.size[0], diff --git a/src/mock_vws/target_raters.py b/src/mock_vws/target_raters.py index 8e2cb1d65..f3c74068f 100644 --- a/src/mock_vws/target_raters.py +++ b/src/mock_vws/target_raters.py @@ -29,8 +29,8 @@ def _get_brisque_target_tracking_rating(*, image_content: bytes) -> int: """ image_file = io.BytesIO(initial_bytes=image_content) image = Image.open(fp=image_file) - image_np = np.array(image, dtype=np.float32) - image_tensor = torch.tensor(image_np).float() / 255 + image_np = np.array(object=image, dtype=np.float32) + image_tensor = torch.tensor(data=image_np).float() / 255 image_tensor = image_tensor.view( image.size[1], image.size[0], diff --git a/tests/conftest.py b/tests/conftest.py index b8c06558f..4c05f7cc1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -108,7 +108,7 @@ def endpoint(request: pytest.FixtureRequest) -> Endpoint: """ Return details of an endpoint for the Target API or the Query API. """ - endpoint_fixture: Endpoint = request.getfixturevalue(request.param) + endpoint_fixture: Endpoint = request.getfixturevalue(argname=request.param) return endpoint_fixture diff --git a/tests/mock_vws/fixtures/prepared_requests.py b/tests/mock_vws/fixtures/prepared_requests.py index dac456b0b..b9c8e4f50 100644 --- a/tests/mock_vws/fixtures/prepared_requests.py +++ b/tests/mock_vws/fixtures/prepared_requests.py @@ -76,7 +76,7 @@ def add_target( headers = { "Authorization": authorization_string, "Date": date, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), "Content-Type": content_type, } @@ -124,7 +124,7 @@ def delete_target( headers = { "Authorization": authorization_string, "Date": date, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), } return Endpoint( @@ -166,7 +166,7 @@ def database_summary(vuforia_database: VuforiaDatabase) -> Endpoint: headers = { "Authorization": authorization_string, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), "Date": date, } @@ -215,7 +215,7 @@ def get_duplicates( headers = { "Authorization": authorization_string, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), "Date": date, } @@ -263,7 +263,7 @@ def get_target( headers = { "Authorization": authorization_string, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), "Date": date, } @@ -306,7 +306,7 @@ def target_list(vuforia_database: VuforiaDatabase) -> Endpoint: headers = { "Authorization": authorization_string, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), "Date": date, } @@ -354,7 +354,7 @@ def target_summary( headers = { "Authorization": authorization_string, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), "Date": date, } @@ -404,7 +404,7 @@ def update_target( headers = { "Authorization": authorization_string, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), "Content-Type": content_type, "Date": date, } @@ -454,7 +454,7 @@ def query( headers = { "Authorization": authorization_string, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), "Date": date, "Content-Type": content_type_header, } diff --git a/tests/mock_vws/fixtures/vuforia_backends.py b/tests/mock_vws/fixtures/vuforia_backends.py index 23f70d7e3..2c67081f7 100644 --- a/tests/mock_vws/fixtures/vuforia_backends.py +++ b/tests/mock_vws/fixtures/vuforia_backends.py @@ -232,7 +232,7 @@ def pytest_collection_modifyitems( if config.getoption(name=skip_docker_build_tests_option): for item in items: if "requires_docker_build" in item.keywords: - item.add_marker(skip_docker_build_tests_marker) + item.add_marker(marker=skip_docker_build_tests_marker) @beartype diff --git a/tests/mock_vws/test_content_length.py b/tests/mock_vws/test_content_length.py index 264900328..12160dc2e 100644 --- a/tests/mock_vws/test_content_length.py +++ b/tests/mock_vws/test_content_length.py @@ -63,7 +63,7 @@ def test_not_integer(endpoint: Endpoint) -> None: if netloc == "cloudreco.vuforia.com": assert not response.text assert response.headers == { - "Content-Length": str(len(response.text)), + "Content-Length": str(object=len(response.text)), "Connection": "Close", } return @@ -81,7 +81,7 @@ def test_not_integer(endpoint: Endpoint) -> None: ) assert response.text == expected_response_text expected_headers = { - "Content-Length": str(len(response.text)), + "Content-Length": str(object=len(response.text)), "Content-Type": "text/html", "Connection": "close", "Server": "awselb/2.0", @@ -99,7 +99,9 @@ def test_too_large(endpoint: Endpoint) -> None: # pragma: no cover pytest.skip(reason="No Content-Type header for this request") netloc = urlparse(url=endpoint.base_url).netloc - content_length = str(int(endpoint.headers["Content-Length"]) + 1) + content_length = str( + object=int(endpoint.headers["Content-Length"]) + 1 + ) new_headers = { **endpoint.headers, @@ -126,7 +128,7 @@ def test_too_large(endpoint: Endpoint) -> None: # pragma: no cover assert response.status_code == HTTPStatus.GATEWAY_TIMEOUT assert not response.text assert response.headers == { - "Content-Length": str(len(response.text)), + "Content-Length": str(object=len(response.text)), "Connection": "keep-alive", } return @@ -136,7 +138,7 @@ def test_too_large(endpoint: Endpoint) -> None: # pragma: no cover # We have seen both of these response texts. assert response.text in {"stream timeout", ""} expected_headers = { - "Content-Length": str(len(response.text)), + "Content-Length": str(object=len(response.text)), "Connection": "close", "Content-Type": "text/plain", "server": "envoy", @@ -159,7 +161,7 @@ def test_too_small(endpoint: Endpoint) -> None: new_headers = { **endpoint.headers, - "Content-Length": str(content_length), + "Content-Length": str(object=content_length), } new_endpoint = Endpoint( diff --git a/tests/mock_vws/test_database_summary.py b/tests/mock_vws/test_database_summary.py index cf43d5a1b..d1ce06f32 100644 --- a/tests/mock_vws/test_database_summary.py +++ b/tests/mock_vws/test_database_summary.py @@ -37,7 +37,7 @@ def _log_attempt_number(retry_state: RetryCallState) -> None: # We wait 0.2 seconds rather than less than that to decrease the number # of calls made to the API, to decrease the likelihood of hitting the # request quota. - wait=wait_fixed(0.2), + wait=wait_fixed(wait=0.2), # Wait up to 700 seconds (arbitrary, though we saw timeouts with 500 # seconds) for the number of images in various categories to match the # expected number. This is necessary because the database summary endpoint diff --git a/tests/mock_vws/test_date_header.py b/tests/mock_vws/test_date_header.py index 4556ca53d..9c4c2302d 100644 --- a/tests/mock_vws/test_date_header.py +++ b/tests/mock_vws/test_date_header.py @@ -110,7 +110,7 @@ def test_incorrect_date_format(endpoint: Endpoint) -> None: gmt = ZoneInfo(key="GMT") with freeze_time(time_to_freeze=datetime.now(tz=gmt)): now = datetime.now(tz=gmt) - date_incorrect_format = now.strftime("%a %b %d %H:%M:%S") + date_incorrect_format = now.strftime(format="%a %b %d %H:%M:%S") authorization_string = authorization_header( access_key=endpoint.access_key, diff --git a/tests/mock_vws/test_docker.py b/tests/mock_vws/test_docker.py index 9f254b126..68f3bdbfa 100644 --- a/tests/mock_vws/test_docker.py +++ b/tests/mock_vws/test_docker.py @@ -111,8 +111,8 @@ def test_build_and_run( try: target_manager_image, _ = client.images.build( - path=str(repository_root), - dockerfile=str(dockerfile), + path=str(object=repository_root), + dockerfile=str(object=dockerfile), tag=target_manager_tag, target="target-manager", rm=True, @@ -132,16 +132,16 @@ def test_build_and_run( ) vwq_image, _ = client.images.build( - path=str(repository_root), - dockerfile=str(dockerfile), + path=str(object=repository_root), + dockerfile=str(object=dockerfile), tag=vwq_tag, target="vwq", rm=True, ) vws_image, _ = client.images.build( - path=str(repository_root), - dockerfile=str(dockerfile), + path=str(object=repository_root), + dockerfile=str(object=dockerfile), tag=vws_tag, target="vws", rm=True, diff --git a/tests/mock_vws/test_flask_app_usage.py b/tests/mock_vws/test_flask_app_usage.py index a10f4e82c..551dc9907 100644 --- a/tests/mock_vws/test_flask_app_usage.py +++ b/tests/mock_vws/test_flask_app_usage.py @@ -101,7 +101,7 @@ def test_custom( seconds = 5.0 monkeypatch.setenv( name="PROCESSING_TIME_SECONDS", - value=str(seconds), + value=str(object=seconds), ) database = VuforiaDatabase() databases_url = _EXAMPLE_URL_FOR_TARGET_MANAGER + "/databases" diff --git a/tests/mock_vws/test_get_duplicates.py b/tests/mock_vws/test_get_duplicates.py index 671c90d58..c52b64730 100644 --- a/tests/mock_vws/test_get_duplicates.py +++ b/tests/mock_vws/test_get_duplicates.py @@ -78,7 +78,7 @@ def test_duplicates_not_same( similar_image_buffer = io.BytesIO() pil_similar_image = Image.open(fp=similar_image_data) # Re-save means similar but not identical. - pil_similar_image.save(similar_image_buffer, format="JPEG") + pil_similar_image.save(fp=similar_image_buffer, format="JPEG") assert similar_image_buffer.getvalue() != image_data.getvalue() original_target_id = vws_client.add_target( diff --git a/tests/mock_vws/test_invalid_json.py b/tests/mock_vws/test_invalid_json.py index fd2d68110..afc3b75ea 100644 --- a/tests/mock_vws/test_invalid_json.py +++ b/tests/mock_vws/test_invalid_json.py @@ -55,7 +55,7 @@ def test_invalid_json(endpoint: Endpoint) -> None: **endpoint.headers, "Authorization": authorization_string, "Date": date, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), } new_endpoint = Endpoint( @@ -135,7 +135,7 @@ def test_invalid_json_with_skewed_time(endpoint: Endpoint) -> None: new_headers = { **endpoint.headers, "Authorization": authorization_string, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), "Date": date, } diff --git a/tests/mock_vws/test_query.py b/tests/mock_vws/test_query.py index 84457a62f..151240777 100644 --- a/tests/mock_vws/test_query.py +++ b/tests/mock_vws/test_query.py @@ -573,7 +573,7 @@ def test_match_exact( application_metadata=metadata_encoded, ) - approximate_target_created = calendar.timegm(time.gmtime()) + approximate_target_created = calendar.timegm(tuple=time.gmtime()) vws_client.wait_for_target_processed(target_id=target_id) @@ -665,7 +665,7 @@ def test_match_similar( similar_image_data = copy.copy(x=high_quality_image) pil_similar_image = Image.open(fp=similar_image_data) # Re-save means similar but not identical. - pil_similar_image.save(similar_image_buffer, format="JPEG") + pil_similar_image.save(fp=similar_image_buffer, format="JPEG") (matching_target,) = cloud_reco_client.query( image=similar_image_buffer, @@ -1829,7 +1829,7 @@ def test_updated_target( application_metadata=metadata_encoded, ) - calendar.timegm(time.gmtime()) + calendar.timegm(tuple=time.gmtime()) vws_client.wait_for_target_processed(target_id=target_id) @@ -1851,7 +1851,7 @@ def test_updated_target( application_metadata=new_metadata_encoded, ) - approximate_target_updated = calendar.timegm(time.gmtime()) + approximate_target_updated = calendar.timegm(tuple=time.gmtime()) vws_client.wait_for_target_processed(target_id=target_id) @@ -1910,7 +1910,7 @@ def test_deleted_active( # # We retry to allow for this difference. for attempt in Retrying( - wait=wait_fixed(0.1), + wait=wait_fixed(wait=0.1), stop=stop_after_delay(max_delay=3), retry=retry_if_exception_type( exception_types=(AssertionError,), @@ -2018,7 +2018,7 @@ def test_date_formats( gmt = ZoneInfo(key="GMT") now = datetime.datetime.now(tz=gmt) - date = now.strftime(datetime_format) + date = now.strftime(format=datetime_format) request_path = "/v1/query" content, content_type_header = encode_multipart_formdata(fields=body) method = HTTPMethod.POST diff --git a/tests/mock_vws/test_requests_mock_usage.py b/tests/mock_vws/test_requests_mock_usage.py index 0da5d1789..3cb3471f6 100644 --- a/tests/mock_vws/test_requests_mock_usage.py +++ b/tests/mock_vws/test_requests_mock_usage.py @@ -247,14 +247,14 @@ def test_no_scheme() -> None: 'Invalid URL "vuforia.vws.example.com": No scheme supplied. ' 'Perhaps you meant "https://vuforia.vws.example.com".' ) - assert str(vws_exc.value) == expected + assert str(object=vws_exc.value) == expected with pytest.raises(expected_exception=MissingSchemeError) as vwq_exc: MockVWS(base_vwq_url="vuforia.vwq.example.com") expected = ( 'Invalid URL "vuforia.vwq.example.com": No scheme supplied. ' 'Perhaps you meant "https://vuforia.vwq.example.com".' ) - assert str(vwq_exc.value) == expected + assert str(object=vwq_exc.value) == expected class TestTargets: @@ -376,7 +376,12 @@ def test_date_changes() -> None: The date that the response is sent is in the response Date header. """ new_year = 2012 - new_time = datetime.datetime(new_year, 1, 1, tzinfo=datetime.UTC) + new_time = datetime.datetime( + year=new_year, + month=1, + day=1, + tzinfo=datetime.UTC, + ) with MockVWS(), freeze_time(time_to_freeze=new_time): response = requests.get( url="https://vws.vuforia.com/summary", @@ -445,7 +450,7 @@ def test_duplicate_keys() -> None: (bad_database_name_db, database_name_conflict_error), ): with pytest.raises( - ValueError, + expected_exception=ValueError, match=expected_message + "$", ): mock.add_database(database=bad_database) diff --git a/tests/mock_vws/test_target_summary.py b/tests/mock_vws/test_target_summary.py index f1d61c237..c432e78b4 100644 --- a/tests/mock_vws/test_target_summary.py +++ b/tests/mock_vws/test_target_summary.py @@ -94,7 +94,7 @@ def test_after_processing( It also shows that ``reco_rating`` is not provided even when the status is success. """ - image_file = request.getfixturevalue(image_fixture_name) + image_file = request.getfixturevalue(argname=image_fixture_name) target_id = vws_client.add_target( name="example", diff --git a/tests/mock_vws/test_unexpected_json.py b/tests/mock_vws/test_unexpected_json.py index beaac61f9..c7f96856e 100644 --- a/tests/mock_vws/test_unexpected_json.py +++ b/tests/mock_vws/test_unexpected_json.py @@ -52,7 +52,7 @@ def test_does_not_take_data(endpoint: Endpoint) -> None: "Authorization": authorization_string, "Date": date, "Content-Type": content_type, - "Content-Length": str(len(content)), + "Content-Length": str(object=len(content)), } new_endpoint = Endpoint( diff --git a/tests/mock_vws/utils/assertions.py b/tests/mock_vws/utils/assertions.py index 2ad4752cf..936e207bb 100644 --- a/tests/mock_vws/utils/assertions.py +++ b/tests/mock_vws/utils/assertions.py @@ -154,7 +154,7 @@ def assert_vws_response( "x-envoy-upstream-service-time", } assert {str.lower(key) for key in response.headers} == response_header_keys - assert response.headers["Content-Length"] == str(len(response.text)) + assert response.headers["Content-Length"] == str(object=len(response.text)) assert response.headers["Content-Type"] == "application/json" assert response.headers["server"] == "envoy" assert response.headers["x-content-type-options"] == "nosniff" @@ -201,7 +201,7 @@ def assert_query_success(*, response: Response) -> None: expected_response_header_not_chunked = { "Connection": "keep-alive", - "Content-Length": str(response.tell_position), + "Content-Length": str(object=response.tell_position), "Content-Type": "application/json", "Server": "nginx", } @@ -276,7 +276,9 @@ def assert_vwq_failure( assert response.headers.get("transfer-encoding", "chunked") == "chunked" assert response.headers["Connection"] == connection if "Content-Length" in response.headers: # pragma: no cover - assert response.headers["Content-Length"] == str(len(response.text)) + assert response.headers["Content-Length"] == str( + object=len(response.text) + ) # In some tests we see that sometimes there is no Content-Length header # here. else: # pragma: no cover