Skip to content

Commit

Permalink
Activate mypy check in pre-commit (#1560)
Browse files Browse the repository at this point in the history
  • Loading branch information
RobbeSneyders committed Aug 23, 2022
1 parent 64f4254 commit 67bd37f
Show file tree
Hide file tree
Showing 12 changed files with 40 additions and 42 deletions.
12 changes: 12 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 2 additions & 2 deletions connexion/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 3 additions & 4 deletions connexion/apis/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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,
)
Expand Down
6 changes: 3 additions & 3 deletions connexion/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
)
Expand Down Expand Up @@ -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(
Expand Down
21 changes: 6 additions & 15 deletions connexion/decorators/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

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

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

Expand Down
2 changes: 1 addition & 1 deletion connexion/middleware/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
5 changes: 3 additions & 2 deletions connexion/middleware/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion connexion/middleware/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def __init__(
@classmethod
def from_operation(
cls,
operation: AbstractOperation,
operation: t.Union[AbstractOperation, Specification],
security_handler_factory: SecurityHandlerFactory,
):
return cls(
Expand Down
2 changes: 1 addition & 1 deletion connexion/middleware/swagger_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion connexion/resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(MethodResolverBase, self).__init__(*args, **kwargs)
self.initialized_views = []
self.initialized_views: list = []

def resolve_operation_id(self, operation):
"""
Expand Down
9 changes: 7 additions & 2 deletions connexion/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
10 changes: 0 additions & 10 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 67bd37f

Please sign in to comment.