|
1 | 1 | import dataclasses
|
2 | 2 | import json
|
3 | 3 | import re
|
| 4 | +from typing import Union |
4 | 5 |
|
5 | 6 | import pytest
|
| 7 | +from typing_extensions import Literal |
6 | 8 |
|
7 | 9 | from pydantic_core import PydanticSerializationUnexpectedValue, SchemaSerializer, core_schema
|
8 | 10 |
|
9 | 11 |
|
| 12 | +class BaseModel: |
| 13 | + def __init__(self, **kwargs) -> None: |
| 14 | + for name, value in kwargs.items(): |
| 15 | + setattr(self, name, value) |
| 16 | + |
| 17 | + |
10 | 18 | @pytest.mark.parametrize('input_value,expected_value', [(True, True), (False, False), (1, 1), (123, 123), (-42, -42)])
|
11 | 19 | def test_union_bool_int(input_value, expected_value):
|
12 | 20 | s = SchemaSerializer(core_schema.union_schema([core_schema.bool_schema(), core_schema.int_schema()]))
|
@@ -360,3 +368,31 @@ def __init__(self, name: str, price: float):
|
360 | 368 | assert s.to_python(User(name='foo', surname='bar')) == {'name': 'foo', 'surname': 'bar'}
|
361 | 369 | assert s.to_python(DBUser(name='foo', surname='bar', password_hash='x')) == {'name': 'foo', 'surname': 'bar'}
|
362 | 370 | assert s.to_json(DBUser(name='foo', surname='bar', password_hash='x')) == b'{"name":"foo","surname":"bar"}'
|
| 371 | + |
| 372 | + |
| 373 | +@pytest.mark.parametrize(('data', 'json_value'), [(False, 'false'), ('abc', '"abc"')]) |
| 374 | +def test_union_literal_with_other_type(data, json_value): |
| 375 | + class Model(BaseModel): |
| 376 | + value: Union[Literal[False], str] |
| 377 | + value_types_reversed: Union[str, Literal[False]] |
| 378 | + |
| 379 | + s = SchemaSerializer( |
| 380 | + core_schema.model_schema( |
| 381 | + Model, |
| 382 | + core_schema.model_fields_schema( |
| 383 | + { |
| 384 | + 'value': core_schema.model_field( |
| 385 | + core_schema.union_schema([core_schema.literal_schema([False]), core_schema.str_schema()]) |
| 386 | + ), |
| 387 | + 'value_types_reversed': core_schema.model_field( |
| 388 | + core_schema.union_schema([core_schema.str_schema(), core_schema.literal_schema([False])]) |
| 389 | + ), |
| 390 | + } |
| 391 | + ), |
| 392 | + ) |
| 393 | + ) |
| 394 | + |
| 395 | + m = Model(value=data, value_types_reversed=data) |
| 396 | + |
| 397 | + assert s.to_python(m) == {'value': data, 'value_types_reversed': data} |
| 398 | + assert s.to_json(m) == f'{{"value":{json_value},"value_types_reversed":{json_value}}}'.encode() |
0 commit comments