Skip to content

Commit

Permalink
fix: ensure to always return one of the values in Literal field type
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Dec 7, 2020
1 parent de0657e commit d01bc90
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
1 change: 1 addition & 0 deletions changes/2166-PrettyWood.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
fix: ensure to always return one of the values in `Literal` field type
8 changes: 6 additions & 2 deletions pydantic/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,9 +443,13 @@ def make_literal_validator(type_: Any) -> Callable[[Any], Any]:
allowed_choices_set = set(permitted_choices)

def literal_validator(v: Any) -> Any:
if v not in allowed_choices_set:
# Ensure to return the value in `Literal`, not the passed value
# In some cases they can indeed be different (see `test_literal_validator_str_enum`)
for x in allowed_choices_set:
if v == x:
return x
else:
raise errors.WrongConstantError(given=v, permitted=permitted_choices)
return v

return literal_validator

Expand Down
16 changes: 16 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections import deque
from datetime import datetime
from enum import Enum
from itertools import product
from typing import Dict, List, Optional, Tuple

Expand Down Expand Up @@ -1135,6 +1136,21 @@ class Model(BaseModel):
]


@pytest.mark.skipif(not Literal, reason='typing_extensions not installed')
def test_literal_validator_str_enum():
class Bar(str, Enum):
FIZ = 'fiz'
FUZ = 'fuz'

class Foo(BaseModel):
bar: Bar
barfiz: Literal[Bar.FIZ]

my_foo = Foo.parse_obj({'bar': 'fiz', 'barfiz': 'fiz'})
assert my_foo.bar is Bar.FIZ
assert my_foo.barfiz is Bar.FIZ


@pytest.mark.skipif(not Literal, reason='typing_extensions not installed')
def test_nested_literal_validator():
L1 = Literal['foo']
Expand Down

0 comments on commit d01bc90

Please sign in to comment.