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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support strict specification for UUID types #7865

Merged
merged 2 commits into from Oct 18, 2023
Merged
Show file tree
Hide file tree
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
5 changes: 4 additions & 1 deletion pydantic/_internal/_known_annotated_metadata.py
Expand Up @@ -33,11 +33,12 @@
FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
BOOL_CONSTRAINTS = STRICT
UUID_CONSTRAINTS = STRICT

DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
LAX_OR_STRICT_CONSTRAINTS = {*STRICT}
LAX_OR_STRICT_CONSTRAINTS = STRICT

UNION_CONSTRAINTS = {'union_mode'}
URL_CONSTRAINTS = {
Expand Down Expand Up @@ -86,6 +87,8 @@
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('url', 'multi-host-url'))
for constraint in BOOL_CONSTRAINTS:
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('bool',))
for constraint in UUID_CONSTRAINTS:
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('uuid',))
for constraint in LAX_OR_STRICT_CONSTRAINTS:
CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint].update(('lax-or-strict',))

Expand Down
10 changes: 9 additions & 1 deletion pydantic/types.py
Expand Up @@ -1071,7 +1071,15 @@ def __get_pydantic_json_schema__(
return field_schema

def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
return core_schema.uuid_schema(version=self.uuid_version)
if isinstance(self, source):
# used directly as a type
return core_schema.uuid_schema(version=self.uuid_version)
else:
# update existing schema with self.uuid_version
schema = handler(source)
_check_annotated_type(schema['type'], 'uuid', self.__class__.__name__)
schema['version'] = self.uuid_version # type: ignore
return schema

def __hash__(self) -> int:
return hash(type(self.uuid_version))
Expand Down
38 changes: 29 additions & 9 deletions tests/test_types.py
Expand Up @@ -2861,22 +2861,29 @@ class UUIDModel(BaseModel):


def test_uuid_strict() -> None:
class UUIDModel(BaseModel):
class StrictByConfig(BaseModel):
a: UUID1
b: UUID3
c: UUID4
d: UUID5
e: uuid.UUID

model_config = ConfigDict(strict=True)

class StrictByField(BaseModel):
a: UUID1 = Field(..., strict=True)
b: UUID3 = Field(..., strict=True)
c: UUID4 = Field(..., strict=True)
d: UUID5 = Field(..., strict=True)
e: uuid.UUID = Field(..., strict=True)

a = uuid.UUID('7fb48116-ca6b-11ed-a439-3274d3adddac') # uuid1
b = uuid.UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') # uuid3
c = uuid.UUID('260d1600-3680-4f4f-a968-f6fa622ffd8d') # uuid4
d = uuid.UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') # uuid5
e = uuid.UUID('7fb48116-ca6b-11ed-a439-3274d3adddac') # any uuid

with pytest.raises(ValidationError) as exc_info:
UUIDModel(a=str(a), b=str(b), c=str(c), d=str(d))
assert exc_info.value.errors(include_url=False) == [
strict_errors = [
{
'type': 'is_instance_of',
'loc': ('a',),
Expand Down Expand Up @@ -2905,13 +2912,26 @@ class UUIDModel(BaseModel):
'input': '886313e1-3b8a-5372-9b90-0c9aee199e5d',
'ctx': {'class': 'UUID'},
},
{
'type': 'is_instance_of',
'loc': ('e',),
'msg': 'Input should be an instance of UUID',
'input': '7fb48116-ca6b-11ed-a439-3274d3adddac',
'ctx': {'class': 'UUID'},
},
]

m = UUIDModel(a=a, b=b, c=c, d=d)
assert isinstance(m.a, type(a)) and m.a == a
assert isinstance(m.b, type(b)) and m.b == b
assert isinstance(m.c, type(c)) and m.c == c
assert isinstance(m.d, type(d)) and m.d == d
for model in [StrictByConfig, StrictByField]:
with pytest.raises(ValidationError) as exc_info:
model(a=str(a), b=str(b), c=str(c), d=str(d), e=str(e))
assert exc_info.value.errors(include_url=False) == strict_errors

m = model(a=a, b=b, c=c, d=d, e=e)
assert isinstance(m.a, type(a)) and m.a == a
assert isinstance(m.b, type(b)) and m.b == b
assert isinstance(m.c, type(c)) and m.c == c
assert isinstance(m.d, type(d)) and m.d == d
assert isinstance(m.e, type(e)) and m.e == e


@pytest.mark.parametrize(
Expand Down