Skip to content
This repository has been archived by the owner on Aug 19, 2023. It is now read-only.

Add check that literal values are valid to decode_field #164

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
5 changes: 4 additions & 1 deletion dataclasses_jsonschema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from decimal import Decimal
from ipaddress import IPv4Address, IPv6Address
from typing import Optional, Type, Union, Any, Dict, Tuple, List, Callable, TypeVar
from typing_extensions import get_args
import re
from datetime import datetime, date
from dataclasses import fields, is_dataclass, Field, MISSING, dataclass, asdict
Expand Down Expand Up @@ -438,7 +439,9 @@ def _decode_field(cls, field: str, field_type: Any, value: Any) -> Any:
field_type_name = cls._get_field_type_name(field_type)
# Note: Only literal types composed of primitive values are currently supported
if type(value) in JSON_ENCODABLE_TYPES and (field_type in JSON_ENCODABLE_TYPES or is_literal(field_type)):
if is_literal(field_type):
if is_literal(field_type) and value not in get_args(field_type):
roshcagra marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError('Literal value is not in allowed set of values for type.')
elif is_literal(field_type):
def decoder(_, __, val): return val
else:
def decoder(_, ft, val): return ft(val)
Expand Down
23 changes: 23 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1052,3 +1052,26 @@ class Person(JsonSchemaMixin):
data = Person(name="Joe", pet=Dog(breed="Pug")).to_dict()
p = Person.from_dict(data)
assert p.pet == Dog(breed="Pug")


def test_decode_literal():
@dataclass
class Foo(JsonSchemaMixin):
common_field: int
name: Literal['Foo'] = 'Foo'

@dataclass
class Bar(JsonSchemaMixin):
common_field: int
name: Literal['Bar'] = 'Bar'
other_field: Optional[int] = None

@dataclass
class Baz(JsonSchemaMixin):
my_foo_bar: Union[Bar, Foo]

decoded = Baz.from_dict(Baz(my_foo_bar=Foo(common_field=1)).to_dict())

# Even though Bar comes first in the Union for 'my_foor_bar', the literal check on 'name' should
# verify that this is a Foo and not assign it to a Bar
assert type(decoded.my_foo_bar) == Foo