File: union_discriminator.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 (49 lines) | stat: -rw-r--r-- 1,276 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
from dataclasses import dataclass
from typing import Annotated

import pytest

from apischema import ValidationError, deserialize, discriminator, serialize
from apischema.json_schema import deserialization_schema


@dataclass
class Cat:
    pass


@dataclass
class Dog:
    pass


@dataclass
class Lizard:
    pass


Pet = Annotated[Cat | Dog | Lizard, discriminator("type", {"dog": Dog})]

assert deserialize(Pet, {"type": "dog"}) == Dog()
assert deserialize(Pet, {"type": "Cat"}) == Cat()
assert serialize(Pet, Dog()) == {"type": "dog"}
with pytest.raises(ValidationError) as err:
    assert deserialize(Pet, {"type": "not a pet"})
assert err.value.errors == [
    {"loc": ["type"], "err": "not one of ['dog', 'Cat', 'Lizard'] (oneOf)"}
]

assert deserialization_schema(Pet) == {
    "oneOf": [
        {"$ref": "#/$defs/Cat"},
        {"$ref": "#/$defs/Dog"},
        {"$ref": "#/$defs/Lizard"},
    ],
    "discriminator": {"propertyName": "type", "mapping": {"dog": "#/$defs/Dog"}},
    "$defs": {
        "Dog": {"type": "object", "additionalProperties": False},
        "Cat": {"type": "object", "additionalProperties": False},
        "Lizard": {"type": "object", "additionalProperties": False},
    },
    "$schema": "http://json-schema.org/draft/2020-12/schema#",
}