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
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

View File

@@ -24,8 +24,8 @@ try:
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

View File

@@ -14,7 +14,7 @@ from ..exceptions import ResolverError
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 @@ class AbstractRoutingAPI(AbstractSpecAPI):
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 @@ class AbstractRoutingAPI(AbstractSpecAPI):
"""
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,
)

View File

@@ -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(

View File

@@ -6,7 +6,7 @@ import collections
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 @@ class RequestBodyValidator:
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 @@ class RequestBodyValidator:
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 @@ class ResponseBodyValidator:
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

View File

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

View File

@@ -57,7 +57,7 @@ class RoutingMiddleware(AppMiddleware):
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

View File

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

View File

@@ -55,7 +55,7 @@ class SwaggerUIMiddleware(AppMiddleware):
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:

View File

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

View File

@@ -110,6 +110,11 @@ class Specification(Mapping):
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

10
tox.ini
View File

@@ -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