File: test_deserialize_with_coercion.py

package info (click to toggle)
python-apischema 0.18.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,608 kB
  • sloc: python: 15,266; sh: 7; makefile: 7
file content (29 lines) | stat: -rw-r--r-- 684 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
from __future__ import annotations

import json
from dataclasses import dataclass
from typing import Any, Mapping, Sequence, Union

from apischema import deserialize


def _coerce_json(cls, data):
    if not isinstance(data, cls) and isinstance(data, str):
        return json.loads(data)
    else:
        return data


@dataclass
class MyClass:
    my_property: Union[Sequence[str], Mapping[str, Any]]


def test_coerce_json():
    key = "test"
    value = 2
    ret = deserialize(
        MyClass, {"my_property": f'{{"{key}": {value}}}'}, coerce=_coerce_json
    )
    assert isinstance(ret, MyClass)
    assert isinstance(ret.my_property, dict) and ret.my_property[key] == value