File: test_field_generic_conversion.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 (35 lines) | stat: -rw-r--r-- 1,111 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
from dataclasses import dataclass, field
from operator import itemgetter
from typing import Dict, Generic, Mapping, Sequence, TypeVar

from apischema import alias, serialize
from apischema.json_schema import serialization_schema
from apischema.metadata import conversion

T = TypeVar("T")
V = TypeVar("V")


def sort_by_priority(values_with_priority: Mapping[int, T]) -> Sequence[T]:
    return [v for _, v in sorted(values_with_priority.items(), key=itemgetter(0))]


assert sort_by_priority({1: "a", 0: "b"}) == ["b", "a"]


@dataclass
class Foo(Generic[V]):
    values_with_priority: Dict[int, V] = field(
        metadata=alias("values") | conversion(serialization=sort_by_priority)
    )


def test_field_generic_conversion():
    assert serialize(Foo[str], Foo({1: "a", 0: "b"})) == {"values": ["b", "a"]}
    assert serialization_schema(Foo[str]) == {
        "type": "object",
        "properties": {"values": {"type": "array", "items": {"type": "string"}}},
        "required": ["values"],
        "additionalProperties": False,
        "$schema": "http://json-schema.org/draft/2020-12/schema#",
    }