Skip to content
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
13 changes: 13 additions & 0 deletions src/validataclass/exceptions/uuid_exceptions.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file is missing the copyright header.

Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from typing import Any

from validataclass.exceptions import ValidationError


class InvalidUUIDError(ValidationError):
"""
Validation error raised by `UUIDValidator` when input is not a valid UUID.
"""
code = 'invalid_uuid'

def __init__(self, **kwargs: Any):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The init method is redundant, it doesn't do anything other than passing arguments to the init method of the super class. You can remove it.

super().__init__(**kwargs)
39 changes: 39 additions & 0 deletions src/validataclass/validators/uuid_validator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
validataclass
Copyright (c) 2026, binary butterfly GmbH and contributors
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""

from typing import Any
from uuid import UUID

from typing_extensions import override

from .validator import Validator

__all__ = [
'UUIDValidator',
]

from ..exceptions.uuid_exceptions import InvalidUUIDError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sort the imports. The __all__ doesn't belong between imports. Also, please use absolute imports for the exception (basically, everything that's not in the same package should use an absolute import). You can look at other validator files for examples.



class UUIDValidator(Validator[UUID]):
"""
Validator for UUIDs.

Valid input: `str`
Output: `UUID`
"""

@override
def validate(self, input_data: Any, **kwargs: Any) -> UUID:
self._ensure_type(input_data, str)

# Cast to string (for type hinting)
input_str = str(input_data)

try:
return UUID(input_str)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This accepts UUIDs in a variety of different formats, not just the dash-separated groups of hexadecimal numbers. For example, these are all valid too:

UUID('{12345678-1234-5678-1234-567812345678}')  # curly braces
UUID('12345678123456781234567812345678')  # no dashes
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')  # URN prefix

Additionally, the dashes are not just optional, there can be any number of dashes in any place (e.g. ---1-234---56-78-1234-5678-12345-678-1234-567-8- is considered valid).

See uuid docs: https://docs.python.org/3/library/uuid.html#uuid.UUID

The question is, should these all be accepted? If yes, then these formats should be included in the unit tests. If not, then the code needs to be extended and there should be negative tests for these cases. If "it depends on the use case", then there should be a option in the validator for it.

In any case: UUIDs are not completely trivial, so the documentation of the validator should specify which formats it accepts.

except ValueError as e:
raise InvalidUUIDError from e
79 changes: 79 additions & 0 deletions tests/unit/validators/uuid_validator_test.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file is also missing the copyright header.

Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import pytest

from validataclass.exceptions import RequiredValueError, InvalidTypeError
from validataclass.exceptions.uuid_exceptions import InvalidUUIDError
from validataclass.validators.uuid_validator import UUIDValidator


class UUIDValidatorTest:
"""
Unit tests for the UUIDValidator.
"""

# General tests

@staticmethod
def test_invalid_none():
""" Check that UUIDValidator raises exceptions for None as value. """
validator = UUIDValidator()

with pytest.raises(RequiredValueError) as exception_info:
validator.validate(None)

assert exception_info.value.to_dict() == {'code': 'required_value'}

@staticmethod
def test_invalid_wrong_type():
""" Check that UUIDValidator raises exceptions for values that are not of type 'str'. """
validator = UUIDValidator()

with pytest.raises(InvalidTypeError) as exception_info:
validator.validate(123)

assert exception_info.value.to_dict() == {
'code': 'invalid_type',
'expected_type': 'str',
}

@staticmethod
@pytest.mark.parametrize(
'input_data',
[
'',
'unit test apple',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be more test cases for invalid strings: Strings that look like UUIDs in various aspects, but are not valid UUIDs.

For example:

  • Characters that are not allowed in UUIDs. (Letters that aren't hex digits, special characters that aren't valid delimiters)
  • Hexadecimal strings that don't have the correct length (too short, to long)

And, depending on the answer to my other comment about different formats currently all being accepted, maybe more test cases.

],
)
def test_invalid_string(input_data):
""" Test UUIDValidator with invalid strings. """
validator = UUIDValidator()

with pytest.raises(InvalidUUIDError) as exception_info:
validator.validate(input_data)

assert exception_info.value.to_dict() == {'code': 'invalid_uuid'}

@staticmethod
@pytest.mark.parametrize(
'input_data',
[
# Nil UUID
# https://www.rfc-editor.org/info/rfc9562/#section-5.9
"00000000-0000-0000-0000-000000000000",
# UUID Version 1
# https://www.rfc-editor.org/info/rfc9562/#section-5.1
'eb720958-dc2f-11f1-affb-426ea6d26eca',
# UUID Version 3
# https://www.rfc-editor.org/info/rfc9562/#section-5.3
'397792c4-039c-3d7d-ab8d-f79803300084',
# UUID Version 4
# https://www.rfc-editor.org/info/rfc9562/#section-5.4
'77736bec-8d9d-4c7d-b1e4-5f90f4c19b25',
# UUID Version 5
# https://www.rfc-editor.org/info/rfc9562/#section-5.5
'6423fa3e-a882-51db-9091-95d0ded7c88d',
],
)
def test_valid_string(input_data):
""" Test UUIDValidator with valid strings. """
validator = UUIDValidator()
assert str(validator.validate(input_data)) == input_data

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also test that the validator returns a UUID object and not a string.