|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +from datetime import datetime, timezone |
3 | 4 | from typing import TYPE_CHECKING, Annotated, Optional, cast |
4 | 5 |
|
5 | 6 | import pydantic as pydantic_v2 |
6 | 7 | import pytest |
| 8 | +from pydantic import AwareDatetime |
7 | 9 | from pydantic import v1 as pydantic_v1 |
8 | 10 | from typing_extensions import Literal |
9 | 11 |
|
10 | 12 | from litestar import Request, post |
11 | 13 | from litestar.dto import DTOConfig |
12 | | -from litestar.plugins.pydantic import PydanticDTO, _model_dump_json |
| 14 | +from litestar.plugins.pydantic import PydanticDTO, _model_dump, _model_dump_json |
| 15 | +from litestar.status_codes import HTTP_201_CREATED |
13 | 16 | from litestar.testing import create_test_client |
14 | 17 | from litestar.types import Empty |
15 | 18 | from litestar.typing import FieldDefinition |
|
23 | 26 | from litestar import Litestar |
24 | 27 |
|
25 | 28 |
|
| 29 | +def test_aware_datetime_serialization_v2(use_experimental_dto_backend: bool) -> None: |
| 30 | + class PydanticAwareDatetimeModel(pydantic_v2.BaseModel): |
| 31 | + tz_aware_datetime: AwareDatetime |
| 32 | + |
| 33 | + class AwareDatetimeDTO(PydanticDTO[PydanticAwareDatetimeModel]): |
| 34 | + config = DTOConfig(experimental_codegen_backend=use_experimental_dto_backend) |
| 35 | + |
| 36 | + @post(dto=AwareDatetimeDTO, signature_types=[PydanticAwareDatetimeModel]) |
| 37 | + def handler(data: PydanticAwareDatetimeModel) -> PydanticAwareDatetimeModel: |
| 38 | + return data |
| 39 | + |
| 40 | + with create_test_client(handler) as client: |
| 41 | + data = PydanticAwareDatetimeModel(tz_aware_datetime=datetime.now(tz=timezone.utc)) |
| 42 | + dict_payload = _model_dump(data) |
| 43 | + json_payload = _model_dump_json(data) |
| 44 | + |
| 45 | + headers = {"Content-Type": "application/json; charset=utf-8"} |
| 46 | + response = client.post( |
| 47 | + "/", |
| 48 | + content=json_payload, |
| 49 | + headers=headers, |
| 50 | + ) |
| 51 | + assert response.status_code == HTTP_201_CREATED |
| 52 | + assert response.json() == dict_payload |
| 53 | + |
| 54 | + |
26 | 55 | def test_schema_required_fields_with_pydantic_dto( |
27 | 56 | use_experimental_dto_backend: bool, base_model: type[BaseModel] |
28 | 57 | ) -> None: |
|
0 commit comments