Skip to content

Commit

Permalink
Better error and explanation if schema used as default instead of ann…
Browse files Browse the repository at this point in the history
…otation (#1152)
  • Loading branch information
vitalik committed Sep 16, 2024
1 parent 457c066 commit 500823b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
9 changes: 9 additions & 0 deletions ninja/signature/details.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,15 @@ def __init__(self, path: str, view_func: Callable[..., Any]) -> None:
self.response_arg = name
continue

if (
arg.annotation is inspect.Parameter.empty
and isinstance(arg.default, type)
and issubclass(arg.default, pydantic.BaseModel)
):
raise ConfigError(
f"Looks like you are using `{name}={arg.default.__name__}` instead of `{name}: {arg.default.__name__}` (annotation)"
)

func_param = self._get_param_type(name, arg)
self.params.append(func_param)

Expand Down
16 changes: 16 additions & 0 deletions tests/test_body.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import pytest
from pydantic import field_validator

from ninja import Body, Form, NinjaAPI, Schema
from ninja.errors import ConfigError
from ninja.testing import TestClient

api = NinjaAPI()
Expand Down Expand Up @@ -66,3 +68,17 @@ def test_body_validation_error():
"ctx": {"error": "invalid email"},
}
]


def test_incorrect_annotation():
api = NinjaAPI()

class Some(Schema):
a: int

with pytest.raises(ConfigError):

@api.post("/some")
def some(request, payload=Some):
# ................. ^------ invalid usage assigning class instead of annotation
return 42

0 comments on commit 500823b

Please sign in to comment.