From 0daf29fc4fe3f645ba2ed55ab3fac493d1300c94 Mon Sep 17 00:00:00 2001 From: Robbe Sneyders Date: Sun, 26 Jun 2022 00:22:42 +0200 Subject: [PATCH] Activate mypy check in pre-commit --- .pre-commit-config.yaml | 12 ++++++++++++ connexion/__init__.py | 4 ++-- connexion/apis/abstract.py | 7 +++---- connexion/cli.py | 6 +++--- connexion/decorators/validation.py | 21 ++++++--------------- connexion/middleware/main.py | 2 +- connexion/middleware/routing.py | 5 +++-- connexion/middleware/security.py | 2 +- connexion/middleware/swagger_ui.py | 2 +- connexion/resolver.py | 2 +- connexion/spec.py | 9 +++++++-- tox.ini | 10 ---------- 12 files changed, 40 insertions(+), 42 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3f140980a..f81d001f5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -41,3 +41,15 @@ repos: name: black tests files: "^tests/" args: ["tests"] + + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v0.961 + hooks: + - id: mypy + files: "^connexion/" + args: ["--ignore-missing-imports", "connexion"] + additional_dependencies: + - types-jsonschema + - types-PyYAML + - types-requests + pass_filenames: false diff --git a/connexion/__init__.py b/connexion/__init__.py index 6240ac7ca..862747164 100755 --- a/connexion/__init__.py +++ b/connexion/__init__.py @@ -24,8 +24,8 @@ from .apps.flask_app import FlaskApp except ImportError as e: # pragma: no cover _flask_not_installed_error = not_installed_error(e) - FlaskApi = _flask_not_installed_error - FlaskApp = _flask_not_installed_error + FlaskApi = _flask_not_installed_error # type: ignore + FlaskApp = _flask_not_installed_error # type: ignore App = FlaskApp Api = FlaskApi diff --git a/connexion/apis/abstract.py b/connexion/apis/abstract.py index 31e12d4af..178ddb382 100644 --- a/connexion/apis/abstract.py +++ b/connexion/apis/abstract.py @@ -14,7 +14,7 @@ from ..http_facts import METHODS from ..jsonifier import Jsonifier from ..lifecycle import ConnexionResponse -from ..operations import AbstractOperation, make_operation +from ..operations import make_operation from ..options import ConnexionOptions from ..resolver import Resolver from ..spec import Specification @@ -180,9 +180,7 @@ def add_operation(self, path: str, method: str) -> None: raise NotImplementedError @abc.abstractmethod - def _add_operation_internal( - self, method: str, path: str, operation: AbstractOperation - ) -> None: + def _add_operation_internal(self, method: str, path: str, operation: t.Any) -> None: """ Adds the operation according to the user framework in use. It will be used to register the operation on the user framework router. @@ -192,6 +190,7 @@ def _add_resolver_error_handler(self, method: str, path: str, err: ResolverError """ Adds a handler for ResolverError for the given method and path. """ + self.resolver_error_handler = t.cast(t.Callable, self.resolver_error_handler) operation = self.resolver_error_handler( err, ) diff --git a/connexion/cli.py b/connexion/cli.py index 4e1bcf4fa..9d82a456d 100644 --- a/connexion/cli.py +++ b/connexion/cli.py @@ -73,14 +73,14 @@ def main(): @click.option( "--wsgi-server", "-w", - type=click.Choice(AVAILABLE_SERVERS.keys()), + type=click.Choice(AVAILABLE_SERVERS.keys()), # type: ignore callback=validate_server_requirements, help="Which WSGI server container to use. (deprecated, use --server instead)", ) @click.option( "--server", "-s", - type=click.Choice(AVAILABLE_SERVERS.keys()), + type=click.Choice(AVAILABLE_SERVERS.keys()), # type: ignore callback=validate_server_requirements, help="Which server container to use.", ) @@ -147,7 +147,7 @@ def main(): "--app-framework", "-f", default=FLASK_APP, - type=click.Choice(AVAILABLE_APPS.keys()), + type=click.Choice(AVAILABLE_APPS.keys()), # type: ignore help="The app framework used to run the server", ) def run( diff --git a/connexion/decorators/validation.py b/connexion/decorators/validation.py index a8b2b5fc2..e346f9de6 100644 --- a/connexion/decorators/validation.py +++ b/connexion/decorators/validation.py @@ -6,7 +6,7 @@ import copy import functools import logging -from typing import AnyStr, Union +import typing as t from jsonschema import Draft4Validator, ValidationError, draft4_format_checker from jsonschema.validators import extend @@ -209,8 +209,7 @@ def _error_path_message(cls, exception): error_path_msg = f" - '{error_path}'" if error_path else "" return error_path_msg - def validate_schema(self, data, url): - # type: (dict, AnyStr) -> Union[ConnexionResponse, None] + def validate_schema(self, data: dict, url: str) -> t.Optional[ConnexionResponse]: if self.is_null_value_valid and is_null(data): return None @@ -219,16 +218,10 @@ def validate_schema(self, data, url): except ValidationError as exception: error_path_msg = self._error_path_message(exception=exception) logger.error( - "{url} validation error: {error}{error_path_msg}".format( - url=url, error=exception.message, error_path_msg=error_path_msg - ), + f"{str(url)} validation error: {exception.message}{error_path_msg}", extra={"validator": "body"}, ) - raise BadRequestProblem( - detail="{message}{error_path_msg}".format( - message=exception.message, error_path_msg=error_path_msg - ) - ) + raise BadRequestProblem(detail=f"{exception.message}{error_path_msg}") return None @@ -244,14 +237,12 @@ def __init__(self, schema, validator=None): ValidatorClass = validator or Draft4ResponseValidator self.validator = ValidatorClass(schema, format_checker=draft4_format_checker) - def validate_schema(self, data, url): - # type: (dict, AnyStr) -> Union[ConnexionResponse, None] + def validate_schema(self, data: dict, url: str) -> t.Optional[ConnexionResponse]: try: self.validator.validate(data) except ValidationError as exception: logger.error( - "{url} validation error: {error}".format(url=url, error=exception), - extra={"validator": "response"}, + f"{url} validation error: {exception}", extra={"validator": "response"} ) raise exception diff --git a/connexion/middleware/main.py b/connexion/middleware/main.py index 80bbb348b..5120f86df 100644 --- a/connexion/middleware/main.py +++ b/connexion/middleware/main.py @@ -47,7 +47,7 @@ def _apply_middlewares( """ apps = [] for middleware in reversed(middlewares): - app = middleware(app) + app = middleware(app) # type: ignore apps.append(app) return app, reversed(apps) diff --git a/connexion/middleware/routing.py b/connexion/middleware/routing.py index 4d30e6cdd..39411ac51 100644 --- a/connexion/middleware/routing.py +++ b/connexion/middleware/routing.py @@ -57,7 +57,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await self.app(scope, receive, send) return - _scope.set(scope.copy()) + _scope.set(scope.copy()) # type: ignore # Needs to be set so starlette router throws exceptions instead of returning error responses scope["app"] = self @@ -71,10 +71,11 @@ class RoutingAPI(AbstractRoutingAPI): def __init__( self, specification: t.Union[pathlib.Path, str, dict], + *, + next_app: ASGIApp, base_path: t.Optional[str] = None, arguments: t.Optional[dict] = None, resolver: t.Optional[Resolver] = None, - next_app: ASGIApp = None, resolver_error_handler: t.Optional[t.Callable] = None, debug: bool = False, **kwargs diff --git a/connexion/middleware/security.py b/connexion/middleware/security.py index b14e6e8a1..b81b32526 100644 --- a/connexion/middleware/security.py +++ b/connexion/middleware/security.py @@ -139,7 +139,7 @@ def __init__( @classmethod def from_operation( cls, - operation: AbstractOperation, + operation: t.Union[AbstractOperation, Specification], security_handler_factory: SecurityHandlerFactory, ): return cls( diff --git a/connexion/middleware/swagger_ui.py b/connexion/middleware/swagger_ui.py index bc85443cb..73c991416 100644 --- a/connexion/middleware/swagger_ui.py +++ b/connexion/middleware/swagger_ui.py @@ -55,7 +55,7 @@ def add_api( self.router.mount(api.base_path, app=api.router) async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - _original_scope.set(scope.copy()) + _original_scope.set(scope.copy()) # type: ignore await self.router(scope, receive, send) async def default_fn(self, _scope: Scope, receive: Receive, send: Send) -> None: diff --git a/connexion/resolver.py b/connexion/resolver.py index e9400fd2b..77fcc8985 100644 --- a/connexion/resolver.py +++ b/connexion/resolver.py @@ -226,7 +226,7 @@ def __init__(self, *args, class_arguments: _class_arguments_type = None, **kwarg "Requests to a collection endpoint will be routed to .get()" ) super(MethodViewResolver, self).__init__(*args, **kwargs) - self.initialized_views = [] + self.initialized_views: list = [] def resolve_operation_id(self, operation): """ diff --git a/connexion/spec.py b/connexion/spec.py index 8472615f5..1115cd63f 100644 --- a/connexion/spec.py +++ b/connexion/spec.py @@ -110,6 +110,11 @@ def version(self): def security(self): return self._spec.get("security") + @property + @abc.abstractmethod + def security_schemes(self): + raise NotImplementedError + def __getitem__(self, k): return self._spec[k] @@ -207,7 +212,7 @@ class Swagger2Specification(Specification): operation_cls = Swagger2Operation openapi_schema = json.loads( - pkgutil.get_data("connexion", "resources/schemas/v2.0/schema.json") + pkgutil.get_data("connexion", "resources/schemas/v2.0/schema.json") # type: ignore ) @classmethod @@ -260,7 +265,7 @@ class OpenAPISpecification(Specification): operation_cls = OpenAPIOperation openapi_schema = json.loads( - pkgutil.get_data("connexion", "resources/schemas/v3.0/schema.json") + pkgutil.get_data("connexion", "resources/schemas/v3.0/schema.json") # type: ignore ) @classmethod diff --git a/tox.ini b/tox.ini index 1041668a4..ef39c4f71 100644 --- a/tox.ini +++ b/tox.ini @@ -41,13 +41,3 @@ commands= [testenv:pre-commit] deps=pre-commit commands=pre-commit run --all-files --show-diff-on-failure - -[testenv:mypy] -deps= - mypy==0.910 - types-PyYAML - types-requests - types-setuptools - types-ujson -ignore_outcome=true -commands=mypy --exclude='examples/' connexion tests