File: test_datetime_custom_encoder.py

package info (click to toggle)
fastapi 0.118.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 34,212 kB
  • sloc: python: 69,848; javascript: 369; sh: 18; makefile: 17
file content (57 lines) | stat: -rw-r--r-- 1,604 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from datetime import datetime, timezone

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel

from .utils import needs_pydanticv1, needs_pydanticv2


@needs_pydanticv2
def test_pydanticv2():
    from pydantic import field_serializer

    class ModelWithDatetimeField(BaseModel):
        dt_field: datetime

        @field_serializer("dt_field")
        def serialize_datetime(self, dt_field: datetime):
            return dt_field.replace(microsecond=0, tzinfo=timezone.utc).isoformat()

    app = FastAPI()
    model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8))

    @app.get("/model", response_model=ModelWithDatetimeField)
    def get_model():
        return model

    client = TestClient(app)
    with client:
        response = client.get("/model")
    assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"}


# TODO: remove when deprecating Pydantic v1
@needs_pydanticv1
def test_pydanticv1():
    class ModelWithDatetimeField(BaseModel):
        dt_field: datetime

        class Config:
            json_encoders = {
                datetime: lambda dt: dt.replace(
                    microsecond=0, tzinfo=timezone.utc
                ).isoformat()
            }

    app = FastAPI()
    model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8))

    @app.get("/model", response_model=ModelWithDatetimeField)
    def get_model():
        return model

    client = TestClient(app)
    with client:
        response = client.get("/model")
    assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"}