Skip to content

Commit

Permalink
Fix strict application to function-after with use_enum_values (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle committed Apr 19, 2024
1 parent bb857bd commit 6322b24
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
6 changes: 6 additions & 0 deletions pydantic/_internal/_known_annotated_metadata.py
Expand Up @@ -195,6 +195,12 @@ def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | No
raise ValueError(f'Unknown constraint {constraint}')
allowed_schemas = CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint]

# if it becomes necessary to handle more than one constraint
# in this recursive case with function-after or function-wrap, we should refactor
if schema_type in {'function-before', 'function-wrap', 'function-after'} and constraint == 'strict':
schema['schema'] = apply_known_metadata(annotation, schema['schema']) # type: ignore # schema is function-after schema
return schema

if schema_type in allowed_schemas:
if constraint == 'union_mode' and schema_type == 'union':
schema['mode'] = value # type: ignore # schema is UnionSchema
Expand Down
16 changes: 16 additions & 0 deletions tests/test_types.py
Expand Up @@ -6658,3 +6658,19 @@ def test_can_serialize_deque_passed_to_sequence() -> None:

assert ta.dump_python(my_dec) == my_dec
assert ta.dump_json(my_dec) == b'[1,2,3]'


def test_strict_enum_with_use_enum_values() -> None:
class SomeEnum(int, Enum):
SOME_KEY = 1

class Foo(BaseModel):
model_config = ConfigDict(strict=False, use_enum_values=True)
foo: Annotated[SomeEnum, Strict(strict=True)]

f = Foo(foo=SomeEnum.SOME_KEY)
assert f.foo == 1

# validation error raised bc foo field uses strict mode
with pytest.raises(ValidationError):
Foo(foo='1')

0 comments on commit 6322b24

Please sign in to comment.