Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fixes pydantic validation of json lists #258

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion sanic_ext/extras/validation/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def _msgspec_validate_instance(model, body, allow_coerce):

def _validate_instance(model, body, allow_coerce):
data = clean_data(model, body) if allow_coerce else body
return model(**data)
return model.model_validate(data)


def _validate_annotations(model, body, schema, allow_multiple, allow_coerce):
Expand Down
45 changes: 45 additions & 0 deletions tests/extra/test_validation_pydantic.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
from typing import List

import pydantic

from pydantic.dataclasses import dataclass
from sanic import json
from sanic.views import HTTPMethodView

from sanic_ext import validate
from sanic_ext.exceptions import ValidationError


SNOOPY_DATA = {"name": "Snoopy", "alter_ego": ["Flying Ace", "Joe Cool"]}
PET_LIST = [{"name": "Snoopy"}, {"name": "Brutus"}, {"name": "Pluto"}]


def test_validate_json(app):
Expand Down Expand Up @@ -49,6 +52,48 @@ async def post(self, _, body: Pet):
assert response.json["pet"] == SNOOPY_DATA


def test_validate_json_list(app):
@dataclass
class Pet:
name: str

class PetList(pydantic.RootModel[List[Pet]]):
root: List[Pet] = pydantic.Field(
...,
)

@app.post("/function")
@validate(json=PetList)
async def handler(_, body: PetList):
return json(
{
"is_pet": all(isinstance(p, Pet) for p in body.root),
"pets": [{"name": p.name} for p in body.root],
}
)

class MethodView(HTTPMethodView, attach=app, uri="/method"):
decorators = [validate(json=PetList)]

async def post(self, _, body: PetList):
return json(
{
"is_pet": all(isinstance(p, Pet) for p in body.root),
"pets": [{"name": p.name} for p in body.root],
}
)

_, response = app.test_client.post("/function", json=PET_LIST)
assert response.status == 200
assert response.json["is_pet"]
assert response.json["pets"] == PET_LIST

_, response = app.test_client.post("/method", json=PET_LIST)
assert response.status == 200
assert response.json["is_pet"]
assert response.json["pets"] == PET_LIST


def test_validate_form(app):
@dataclass
class Pet:
Expand Down