File: test_field.py

package info (click to toggle)
python-apischema 0.18.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,636 kB
  • sloc: python: 15,281; makefile: 3; sh: 2
file content (53 lines) | stat: -rw-r--r-- 1,486 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
from dataclasses import dataclass, field

import pytest

from apischema.fields import fields_set, set_fields, unset_fields, with_fields_set


@with_fields_set
@dataclass
class Data:
    without_default: int
    with_default: int = 0
    with_default_factory: int = field(default_factory=lambda: 0)


@dataclass
class Inherited(Data):
    other: int = 42


@with_fields_set
@dataclass
class DecoratedInherited(Data):
    other: int = 42


def test_fields_set():
    with pytest.raises(TypeError):
        fields_set(object())

    assert fields_set(Data(0)) == {"without_default"}
    assert fields_set(Data(without_default=0)) == {"without_default"}
    assert fields_set(Data(0, 1)) == {"without_default", "with_default"}

    data = Data(0)
    data.with_default = 1
    assert fields_set(data) == {"without_default", "with_default"}
    unset_fields(data, "without_default")
    assert fields_set(data) == {"with_default"}
    set_fields(data, "with_default_factory")
    assert fields_set(data) == {"with_default", "with_default_factory"}
    set_fields(data, "with_default", overwrite=True)
    assert fields_set(data) == {"with_default"}
    set_fields(data, "not_a_field")
    assert fields_set(data) == {"with_default", "not_a_field"}

    assert fields_set(Inherited(0, other=0)) == {
        "without_default",
        "with_default",
        "with_default_factory",
        "other",
    }
    assert fields_set(DecoratedInherited(0, other=0)) == {"without_default", "other"}