Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃悰 Fix validation warning for unions of Literal and other type #6628

Merged
merged 1 commit into from
Jul 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 22 additions & 1 deletion tests/test_edge_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import pytest
from dirty_equals import HasRepr, IsStr
from pydantic_core import ErrorDetails, InitErrorDetails, PydanticSerializationError, core_schema
from typing_extensions import Annotated, TypedDict, get_args
from typing_extensions import Annotated, Literal, TypedDict, get_args

from pydantic import (
BaseModel,
Expand Down Expand Up @@ -2563,3 +2563,24 @@ class MyModel(TypedDict):
b: Optional[MyEnum]

TypeAdapter(MyModel)


@pytest.mark.parametrize(
('literal_type', 'other_type', 'data', 'json_value', 'data_reversed', 'json_value_reversed'),
[
(Literal[False], str, False, 'false', False, 'false'),
(Literal[True], str, True, 'true', True, 'true'),
(Literal[False], str, 'abc', '"abc"', 'abc', '"abc"'),
(Literal[False], int, False, 'false', 0, '0'),
(Literal[True], int, True, 'true', 1, '1'),
(Literal[False], int, 42, '42', 42, '42'),
],
)
def test_union_literal_with_other_type(literal_type, other_type, data, json_value, data_reversed, json_value_reversed):
class Model(BaseModel):
value: Union[literal_type, other_type]
value_types_reversed: Union[other_type, literal_type]

m = Model(value=data, value_types_reversed=data)
assert m.model_dump() == {'value': data, 'value_types_reversed': data_reversed}
assert m.model_dump_json() == f'{{"value":{json_value},"value_types_reversed":{json_value_reversed}}}'