From 500823bfd387038053e0ec806fba7b6e668701d9 Mon Sep 17 00:00:00 2001 From: Vitaliy Kucheryaviy Date: Mon, 16 Sep 2024 10:33:37 +0300 Subject: [PATCH] Better error and explanation if schema used as default instead of annotation (#1152) --- ninja/signature/details.py | 9 +++++++++ tests/test_body.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/ninja/signature/details.py b/ninja/signature/details.py index a05903c96..cb79cf1eb 100644 --- a/ninja/signature/details.py +++ b/ninja/signature/details.py @@ -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) diff --git a/tests/test_body.py b/tests/test_body.py index 0f288460c..bbb1d4a70 100644 --- a/tests/test_body.py +++ b/tests/test_body.py @@ -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() @@ -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