File: test_not_required_with_future_annotations.py

package info (click to toggle)
python-mashumaro 3.17-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,408 kB
  • sloc: python: 19,981; sh: 16; makefile: 5
file content (56 lines) | stat: -rw-r--r-- 1,721 bytes parent folder | download
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
from __future__ import annotations

from dataclasses import dataclass
from typing import TypedDict

from typing_extensions import NotRequired

from mashumaro import DataClassDictMixin
from mashumaro.codecs.basic import decode, encode
from mashumaro.jsonschema import build_json_schema


class MyDict(TypedDict):
    a: str
    b: NotRequired[int]


@dataclass
class MyDataClass(DataClassDictMixin):
    data: MyDict


def test_typeddict_with_not_required_and_future_annotations():
    # test workaround for https://github.com/Fatal1ty/mashumaro/issues/292
    assert decode({"a": "test", "b": 42}, MyDict) == {"a": "test", "b": 42}
    assert decode({"a": "test", "b": "42"}, MyDict) == {"a": "test", "b": 42}
    assert decode({"a": "test"}, MyDict) == {"a": "test"}

    assert encode(MyDict(a="test"), MyDict) == {"a": "test"}
    assert encode({"a": "test"}, MyDict) == {"a": "test"}
    assert encode(MyDict(a="test", b=42), MyDict) == {"a": "test", "b": 42}

    assert MyDataClass(MyDict(a="test", b=42)).to_dict() == {
        "data": {"a": "test", "b": 42}
    }
    assert MyDataClass(MyDict(a="test")).to_dict() == {"data": {"a": "test"}}

    assert MyDataClass.from_dict(
        {"data": {"a": "test", "b": 42}}
    ) == MyDataClass(MyDict(a="test", b=42))
    assert MyDataClass.from_dict({"data": {"a": "test"}}) == MyDataClass(
        MyDict(a="test")
    )


def test_jsonschema_for_not_required_and_future_annotations():
    schema = build_json_schema(MyDict).to_dict()
    assert schema == {
        "type": "object",
        "properties": {
            "a": {"type": "string"},
            "b": {"type": "integer"},
        },
        "required": ["a"],
        "additionalProperties": False,
    }