File: test_annotated.py

package info (click to toggle)
python-mashumaro 3.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,400 kB
  • sloc: python: 19,890; sh: 16; makefile: 5
file content (61 lines) | stat: -rw-r--r-- 1,728 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
58
59
60
61
from dataclasses import dataclass
from datetime import date, datetime

from typing_extensions import Annotated

from mashumaro import DataClassDictMixin
from mashumaro.config import BaseConfig


def test_annotated():
    @dataclass
    class DataClass(DataClassDictMixin):
        x: Annotated[date, None]

    obj = DataClass(date(2022, 2, 6))
    assert DataClass.from_dict({"x": "2022-02-06"}) == obj
    assert obj.to_dict() == {"x": "2022-02-06"}


def test_annotated_with_overridden_methods():
    @dataclass
    class DataClass(DataClassDictMixin):
        foo: Annotated[date, "foo"]
        bar: Annotated[date, "bar"]
        baz: Annotated[date, "baz"]

        class Config(BaseConfig):
            serialization_strategy = {
                Annotated[date, "foo"]: {
                    "serialize": date.toordinal,
                    "deserialize": date.fromordinal,
                },
                Annotated[date, "bar"]: {
                    "serialize": date.isoformat,
                    "deserialize": date.fromisoformat,
                },
                date: {
                    "serialize": lambda x: x.strftime("%Y%m%d"),
                    "deserialize": (
                        lambda x: datetime.strptime(x, "%Y%m%d").date()
                    ),
                },
            }

    obj = DataClass(
        foo=date(2023, 6, 12),
        bar=date(2023, 6, 12),
        baz=date(2023, 6, 12),
    )
    obj.foo.strftime("%Y%M%D")
    assert (
        DataClass.from_dict(
            {"foo": 738683, "bar": "2023-06-12", "baz": "20230612"}
        )
        == obj
    )
    assert obj.to_dict() == {
        "foo": 738683,
        "bar": "2023-06-12",
        "baz": "20230612",
    }