File: test_exclude.py

package info (click to toggle)
dataclasses-json 0.6.7-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 568 kB
  • sloc: python: 3,757; makefile: 7
file content (51 lines) | stat: -rw-r--r-- 1,451 bytes parent folder | download | duplicates (3)
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
from dataclasses import dataclass, field

from dataclasses_json.api import DataClassJsonMixin, config
from dataclasses_json.cfg import Exclude


@dataclass
class EncodeExclude(DataClassJsonMixin):
    public_field: str
    private_field: str = field(metadata=config(exclude=Exclude.ALWAYS))


@dataclass
class EncodeInclude(DataClassJsonMixin):
    public_field: str
    private_field: str = field(metadata=config(exclude=Exclude.NEVER))


@dataclass
class EncodeCustom(DataClassJsonMixin):
    public_field: str
    sensitive_field: str = field(
        metadata=config(exclude=lambda v: v.startswith("secret"))
    )


def test_exclude():
    dclass = EncodeExclude(public_field="public", private_field="private")
    encoded = dclass.to_dict()
    assert "public_field" in encoded
    assert "private_field" not in encoded


def test_include():
    dclass = EncodeInclude(public_field="public", private_field="private")
    encoded = dclass.to_dict()
    assert "public_field" in encoded
    assert "private_field" in encoded
    assert encoded["private_field"] == "private"


def test_custom_action_included():
    dclass = EncodeCustom(public_field="public", sensitive_field="notsecret")
    encoded = dclass.to_dict()
    assert "sensitive_field" in encoded


def test_custom_action_excluded():
    dclass = EncodeCustom(public_field="public", sensitive_field="secret")
    encoded = dclass.to_dict()
    assert "sensitive_field" not in encoded