Activate mypy check in pre-commit (#1560)

This commit is contained in:
Robbe Sneyders
2022-08-23 09:02:14 +02:00
committed by GitHub
parent 64f42547dc
commit 67bd37fe77
12 changed files with 40 additions and 42 deletions

View File

@@ -41,3 +41,15 @@ repos:
name: black tests name: black tests
files: "^tests/" files: "^tests/"
args: ["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

View File

@@ -24,8 +24,8 @@ try:
from .apps.flask_app import FlaskApp from .apps.flask_app import FlaskApp
except ImportError as e: # pragma: no cover except ImportError as e: # pragma: no cover
_flask_not_installed_error = not_installed_error(e) _flask_not_installed_error = not_installed_error(e)
FlaskApi = _flask_not_installed_error FlaskApi = _flask_not_installed_error # type: ignore
FlaskApp = _flask_not_installed_error FlaskApp = _flask_not_installed_error # type: ignore
App = FlaskApp App = FlaskApp
Api = FlaskApi Api = FlaskApi

View File

@@ -14,7 +14,7 @@ from ..exceptions import ResolverError
from ..http_facts import METHODS from ..http_facts import METHODS
from ..jsonifier import Jsonifier from ..jsonifier import Jsonifier
from ..lifecycle import ConnexionResponse from ..lifecycle import ConnexionResponse
from ..operations import AbstractOperation, make_operation from ..operations import make_operation
from ..options import ConnexionOptions from ..options import ConnexionOptions
from ..resolver import Resolver from ..resolver import Resolver
from ..spec import Specification from ..spec import Specification
@@ -180,9 +180,7 @@ class AbstractRoutingAPI(AbstractSpecAPI):
raise NotImplementedError raise NotImplementedError
@abc.abstractmethod @abc.abstractmethod
def _add_operation_internal( def _add_operation_internal(self, method: str, path: str, operation: t.Any) -> None:
self, method: str, path: str, operation: AbstractOperation
) -> None:
""" """
Adds the operation according to the user framework in use. Adds the operation according to the user framework in use.
It will be used to register the operation on the user framework router. It will be used to register the operation on the user framework router.
@@ -192,6 +190,7 @@ class AbstractRoutingAPI(AbstractSpecAPI):
""" """
Adds a handler for ResolverError for the given method and path. 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( operation = self.resolver_error_handler(
err, err,
) )

View File

@@ -73,14 +73,14 @@ def main():
@click.option( @click.option(
"--wsgi-server", "--wsgi-server",
"-w", "-w",
type=click.Choice(AVAILABLE_SERVERS.keys()), type=click.Choice(AVAILABLE_SERVERS.keys()), # type: ignore
callback=validate_server_requirements, callback=validate_server_requirements,
help="Which WSGI server container to use. (deprecated, use --server instead)", help="Which WSGI server container to use. (deprecated, use --server instead)",
) )
@click.option( @click.option(
"--server", "--server",
"-s", "-s",
type=click.Choice(AVAILABLE_SERVERS.keys()), type=click.Choice(AVAILABLE_SERVERS.keys()), # type: ignore
callback=validate_server_requirements, callback=validate_server_requirements,
help="Which server container to use.", help="Which server container to use.",
) )
@@ -147,7 +147,7 @@ def main():
"--app-framework", "--app-framework",
"-f", "-f",
default=FLASK_APP, 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", help="The app framework used to run the server",
) )
def run( def run(

View File

@@ -6,7 +6,7 @@ import collections
import copy import copy
import functools import functools
import logging import logging
from typing import AnyStr, Union import typing as t
from jsonschema import Draft4Validator, ValidationError, draft4_format_checker from jsonschema import Draft4Validator, ValidationError, draft4_format_checker
from jsonschema.validators import extend from jsonschema.validators import extend
@@ -209,8 +209,7 @@ class RequestBodyValidator:
error_path_msg = f" - '{error_path}'" if error_path else "" error_path_msg = f" - '{error_path}'" if error_path else ""
return error_path_msg return error_path_msg
def validate_schema(self, data, url): def validate_schema(self, data: dict, url: str) -> t.Optional[ConnexionResponse]:
# type: (dict, AnyStr) -> Union[ConnexionResponse, None]
if self.is_null_value_valid and is_null(data): if self.is_null_value_valid and is_null(data):
return None return None
@@ -219,16 +218,10 @@ class RequestBodyValidator:
except ValidationError as exception: except ValidationError as exception:
error_path_msg = self._error_path_message(exception=exception) error_path_msg = self._error_path_message(exception=exception)
logger.error( logger.error(
"{url} validation error: {error}{error_path_msg}".format( f"{str(url)} validation error: {exception.message}{error_path_msg}",
url=url, error=exception.message, error_path_msg=error_path_msg
),
extra={"validator": "body"}, extra={"validator": "body"},
) )
raise BadRequestProblem( raise BadRequestProblem(detail=f"{exception.message}{error_path_msg}")
detail="{message}{error_path_msg}".format(
message=exception.message, error_path_msg=error_path_msg
)
)
return None return None
@@ -244,14 +237,12 @@ class ResponseBodyValidator:
ValidatorClass = validator or Draft4ResponseValidator ValidatorClass = validator or Draft4ResponseValidator
self.validator = ValidatorClass(schema, format_checker=draft4_format_checker) self.validator = ValidatorClass(schema, format_checker=draft4_format_checker)
def validate_schema(self, data, url): def validate_schema(self, data: dict, url: str) -> t.Optional[ConnexionResponse]:
# type: (dict, AnyStr) -> Union[ConnexionResponse, None]
try: try:
self.validator.validate(data) self.validator.validate(data)
except ValidationError as exception: except ValidationError as exception:
logger.error( logger.error(
"{url} validation error: {error}".format(url=url, error=exception), f"{url} validation error: {exception}", extra={"validator": "response"}
extra={"validator": "response"},
) )
raise exception raise exception

View File

@@ -47,7 +47,7 @@ class ConnexionMiddleware:
""" """
apps = [] apps = []
for middleware in reversed(middlewares): for middleware in reversed(middlewares):
app = middleware(app) app = middleware(app) # type: ignore
apps.append(app) apps.append(app)
return app, reversed(apps) return app, reversed(apps)

View File

@@ -57,7 +57,7 @@ class RoutingMiddleware(AppMiddleware):
await self.app(scope, receive, send) await self.app(scope, receive, send)
return 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 # Needs to be set so starlette router throws exceptions instead of returning error responses
scope["app"] = self scope["app"] = self
@@ -71,10 +71,11 @@ class RoutingAPI(AbstractRoutingAPI):
def __init__( def __init__(
self, self,
specification: t.Union[pathlib.Path, str, dict], specification: t.Union[pathlib.Path, str, dict],
*,
next_app: ASGIApp,
base_path: t.Optional[str] = None, base_path: t.Optional[str] = None,
arguments: t.Optional[dict] = None, arguments: t.Optional[dict] = None,
resolver: t.Optional[Resolver] = None, resolver: t.Optional[Resolver] = None,
next_app: ASGIApp = None,
resolver_error_handler: t.Optional[t.Callable] = None, resolver_error_handler: t.Optional[t.Callable] = None,
debug: bool = False, debug: bool = False,
**kwargs **kwargs

View File

@@ -139,7 +139,7 @@ class SecurityOperation:
@classmethod @classmethod
def from_operation( def from_operation(
cls, cls,
operation: AbstractOperation, operation: t.Union[AbstractOperation, Specification],
security_handler_factory: SecurityHandlerFactory, security_handler_factory: SecurityHandlerFactory,
): ):
return cls( return cls(

View File

@@ -55,7 +55,7 @@ class SwaggerUIMiddleware(AppMiddleware):
self.router.mount(api.base_path, app=api.router) self.router.mount(api.base_path, app=api.router)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: 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) await self.router(scope, receive, send)
async def default_fn(self, _scope: Scope, receive: Receive, send: Send) -> None: async def default_fn(self, _scope: Scope, receive: Receive, send: Send) -> None:

View File

@@ -226,7 +226,7 @@ class MethodResolverBase(RestyResolver):
"Requests to a collection endpoint will be routed to .get()" "Requests to a collection endpoint will be routed to .get()"
) )
super(MethodResolverBase, self).__init__(*args, **kwargs) super(MethodResolverBase, self).__init__(*args, **kwargs)
self.initialized_views = [] self.initialized_views: list = []
def resolve_operation_id(self, operation): def resolve_operation_id(self, operation):
""" """

View File

@@ -110,6 +110,11 @@ class Specification(Mapping):
def security(self): def security(self):
return self._spec.get("security") return self._spec.get("security")
@property
@abc.abstractmethod
def security_schemes(self):
raise NotImplementedError
def __getitem__(self, k): def __getitem__(self, k):
return self._spec[k] return self._spec[k]
@@ -207,7 +212,7 @@ class Swagger2Specification(Specification):
operation_cls = Swagger2Operation operation_cls = Swagger2Operation
openapi_schema = json.loads( 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 @classmethod
@@ -260,7 +265,7 @@ class OpenAPISpecification(Specification):
operation_cls = OpenAPIOperation operation_cls = OpenAPIOperation
openapi_schema = json.loads( 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 @classmethod

10
tox.ini
View File

@@ -41,13 +41,3 @@ commands=
[testenv:pre-commit] [testenv:pre-commit]
deps=pre-commit deps=pre-commit
commands=pre-commit run --all-files --show-diff-on-failure 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