File: test_slots.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,776 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, field

import pytest

from mashumaro import DataClassDictMixin, field_options
from mashumaro.core.const import PY_310_MIN

if not PY_310_MIN:
    pytest.skip("requires python>=3.10", allow_module_level=True)


def test_field_options_in_dataclass_with_slots():
    @dataclass(slots=True)
    class DataClass(DataClassDictMixin):
        x: int = field(metadata=field_options(serialize=str, alias="alias"))

    instance = DataClass(123)
    assert DataClass.from_dict({"alias": 123}) == instance
    assert instance.to_dict() == {"x": "123"}


def test_field_options_in_inherited_dataclass_with_slots():
    @dataclass
    class BaseDataClass(DataClassDictMixin):
        y: int

    @dataclass(slots=True)
    class DataClass(BaseDataClass):
        x: int = field(metadata=field_options(serialize=str, alias="alias"))

    instance = DataClass(x=123, y=456)
    assert DataClass.from_dict({"alias": 123, "y": 456}) == instance
    assert instance.to_dict() == {"x": "123", "y": 456}


def test_no_field_options_in_inherited_dataclass_with_slots():
    @dataclass
    class BaseDataClass(DataClassDictMixin):
        y: int

    @dataclass(slots=True)
    class DataClass(BaseDataClass):
        x: int

    instance = DataClass(x=123, y=456)
    assert DataClass.from_dict({"x": 123, "y": 456}) == instance
    assert instance.to_dict() == {"x": 123, "y": 456}


def test_no_field_options_in_inherited_dataclass_with_slots_and_default():
    @dataclass
    class BaseDataClass(DataClassDictMixin):
        y: int

    @dataclass(slots=True)
    class DataClass(BaseDataClass):
        x: int = 123

    instance = DataClass(y=456)
    assert DataClass.from_dict({"y": 456}) == instance
    assert instance.to_dict() == {"x": 123, "y": 456}