From 423c1e4ac1af635c3de854efd9dd9af7858fd855 Mon Sep 17 00:00:00 2001 From: roy Date: Tue, 20 Aug 2024 23:56:36 +0800 Subject: [PATCH] add file field test case --- tests/test_files.py | 47 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/tests/test_files.py b/tests/test_files.py index 7c81c6f..6704163 100644 --- a/tests/test_files.py +++ b/tests/test_files.py @@ -1,9 +1,10 @@ from tempfile import NamedTemporaryFile +from typing import List import pytest +from pydantic import ConfigDict from testapp.models import Attachment -from pydantic import ConfigDict from djantic import ModelSchema @@ -50,3 +51,47 @@ class AttachmentSchema(ModelSchema): "description": attachment.description, "image": attachment.image.name, } + + +@pytest.mark.django_db +def test_model_validate(): + class AttachmentSchema(ModelSchema): + model_config = ConfigDict(model=Attachment) + + image_file = NamedTemporaryFile(suffix=".jpg") + attachment = Attachment.objects.create( + description="My image upload", + image=image_file.name, + ) + raw_init_item = AttachmentSchema.model_validate( + attachment, + from_attributes=True, + ) + + wrapper_item = AttachmentSchema.from_django(attachment) + assert wrapper_item == raw_init_item + + +@pytest.mark.django_db +def test_nest_validate(): + class AttachmentSchema(ModelSchema): + model_config = ConfigDict(model=Attachment) + + class AttachmentListSchema(ModelSchema): + items: List[AttachmentSchema] + + image_file = NamedTemporaryFile(suffix=".jpg") + attachment = Attachment.objects.create( + description="My image upload", + image=image_file.name, + ) + raw_init_item = AttachmentSchema.model_validate( + attachment, + from_attributes=True, + ) + AttachmentListSchema.model_validate( + { + "items": [raw_init_item], + }, + from_attributes=True, + )