Skip to content

Commit

Permalink
fixed context serialization #825
Browse files Browse the repository at this point in the history
  • Loading branch information
vitalik committed Aug 17, 2023
1 parent 2e04e6d commit 43b8e0c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 6 deletions.
10 changes: 7 additions & 3 deletions ninja/operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,14 +225,18 @@ def _get_values(
values.update(data)
except pydantic.ValidationError as e:
items = []
for i in e.errors():
for i in e.errors(include_url=False):
i["loc"] = (
model.__ninja_param_source__,
) + model.__ninja_flatten_map_reverse__.get(i["loc"], i["loc"])
# removing pydantic hints
del i["input"] # type: ignore
if "url" in i:
del i["url"] # type: ignore
if (
"ctx" in i
and "error" in i["ctx"]
and isinstance(i["ctx"]["error"], Exception)
):
i["ctx"]["error"] = str(i["ctx"]["error"])
items.append(dict(i))
errors.extend(items)
if errors:
Expand Down
42 changes: 39 additions & 3 deletions tests/test_body.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from ninja import Body, Form, NinjaAPI
from pydantic import field_validator

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

api = NinjaAPI()
Expand All @@ -16,17 +18,51 @@ def create_task2(request, start: int = Body(2), end: int = Form(1)):
return [start, end]


class UserIn(Schema):
# for testing validation errors context
email: str

@field_validator("email")
@classmethod
def validate_email(cls, v):
if "@" not in v:
raise ValueError("invalid email")
return v


@api.post("/users")
def create_user(request, payload: UserIn):
return payload.dict()


client = TestClient(api)


def test_body():
client = TestClient(api)
assert client.post("/task", json={"start": 1, "end": 2}).json() == [1, 2]
assert client.post("/task", json={"start": 1}).json() == {
"detail": [{"type": "missing", "loc": ["body", "end"], "msg": "Field required"}]
}


def test_body_form():
client = TestClient(api)
data = client.post("/task2", POST={"start": "1", "end": "2"}).json()
print(data)
assert client.post("/task2", POST={"start": "1", "end": "2"}).json() == [1, 2]
assert client.post("/task2").json() == [2, 1]


def test_body_validation_error():
resp = client.post("/users", json={"email": "[email protected]"})
assert resp.status_code == 200

resp = client.post("/users", json={"email": "invalid.com"})
assert resp.status_code == 422
assert resp.json()["detail"] == [
{
"type": "value_error",
"loc": ["body", "payload", "email"],
"msg": "Value error, invalid email",
"ctx": {"error": "invalid email"},
}
]

0 comments on commit 43b8e0c

Please sign in to comment.