File: test_pyyaml.py

package info (click to toggle)
python-cattrs 25.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,812 kB
  • sloc: python: 12,236; makefile: 155
file content (83 lines) | stat: -rw-r--r-- 2,425 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""Pyyaml-specific tests."""

from datetime import date, datetime, timezone

from attrs import define
from hypothesis import given
from pytest import raises
from yaml import safe_dump, safe_load

from cattrs._compat import FrozenSetSubscriptable
from cattrs.errors import ClassValidationError
from cattrs.preconf.pyyaml import make_converter

from ..test_preconf import Everything, everythings, native_unions


@given(everythings())
def test_pyyaml(everything: Everything):

    converter = make_converter()
    unstructured = converter.unstructure(everything)
    raw = safe_dump(unstructured)
    assert converter.structure(safe_load(raw), Everything) == everything


@given(everythings())
def test_pyyaml_converter(everything: Everything):
    converter = make_converter()
    raw = converter.dumps(everything)
    assert converter.loads(raw, Everything) == everything


@given(everythings())
def test_pyyaml_converter_unstruct_collection_overrides(everything: Everything):
    converter = make_converter(
        unstruct_collection_overrides={FrozenSetSubscriptable: sorted}
    )
    raw = converter.unstructure(everything)
    assert raw["a_frozenset"] == sorted(raw["a_frozenset"])


@given(union_and_val=native_unions(), detailed_validation=...)
def test_pyyaml_unions(union_and_val: tuple, detailed_validation: bool):
    """Native union passthrough works."""
    converter = make_converter(detailed_validation=detailed_validation)
    type, val = union_and_val

    assert converter.structure(val, type) == val


@given(detailed_validation=...)
def test_pyyaml_dates(detailed_validation: bool):
    """Pyyaml dates work."""
    converter = make_converter(detailed_validation=detailed_validation)

    @define
    class A:
        datetime: datetime
        date: date

    data = """
    datetime: 1970-01-01T00:00:00Z
    date: 1970-01-01"""
    assert converter.loads(data, A) == A(
        datetime(1970, 1, 1, tzinfo=timezone.utc), date(1970, 1, 1)
    )

    bad_data = """
    datetime: 1
    date: 1
    """

    with raises(ClassValidationError if detailed_validation else Exception) as exc_info:
        converter.loads(bad_data, A)

    if detailed_validation:
        assert (
            repr(exc_info.value.exceptions[0])
            == "Exception('Expected datetime, got 1')"
        )
        assert (
            repr(exc_info.value.exceptions[1]) == "ValueError('Expected date, got 1')"
        )