Coverage for value_object_pattern/usables/identifiers/ulid_value_object.py: 64.71%

15 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-11-21 14:31 +0000

1""" 

2Provide a canonical ULID string value object. 

3""" 

4 

5from re import Pattern, compile as re_compile 1abcdefghij

6from typing import NoReturn 1abcdefghij

7 

8from value_object_pattern.decorators import process, validation 1abcdefghij

9from value_object_pattern.usables import NotEmptyStringValueObject, TrimmedStringValueObject 1abcdefghij

10 

11 

12class UlidValueObject(NotEmptyStringValueObject, TrimmedStringValueObject): 1abcdefghij

13 """ 

14 Validate and normalize a canonical Universally Unique Lexicographically Sortable Identifier. 

15 

16 ULIDs contain 26 case-insensitive Crockford Base32 characters. The letters `I`, `L`, `O`, and `U` are excluded, 

17 and the first character is restricted to `0` through `7` so the encoded value does not exceed 128 bits. Valid 

18 values are stored in uppercase. 

19 

20 References: 

21 ULID specification: https://github.com/ulid/spec 

22 

23 Example: 

24 ```python 

25 from value_object_pattern.usables.identifiers import UlidValueObject 

26 

27 identifier = UlidValueObject(value='01arz3ndektsv4rrffq69g5fav') 

28 print(repr(identifier)) 

29 # >>> UlidValueObject(value='01ARZ3NDEKTSV4RRFFQ69G5FAV') 

30 ``` 

31 """ 

32 

33 _ULID_REGEX: Pattern[str] = re_compile(r'^[0-7][0-9A-HJKMNP-TV-Z]{25}$') 1abcdefghij

34 

35 @process(order=0) 1abcdefghij

36 def _normalize_ulid(self, value: str) -> str: 1abcdefghij

37 """ 

38 Normalize the ULID to uppercase. 

39 

40 Args: 

41 value (str): The validated ULID string. 

42 

43 Returns: 

44 str: The uppercase ULID string. 

45 """ 

46 return value.upper() 

47 

48 @validation(order=1) 1abcdefghij

49 def _ensure_value_is_ulid(self, value: str) -> None: 1abcdefghij

50 """ 

51 Ensure the value is a canonical 128-bit ULID string. 

52 

53 Args: 

54 value (str): The ULID string to validate. 

55 

56 Raises: 

57 ValueError: If the value is not a canonical ULID. 

58 """ 

59 if self._ULID_REGEX.fullmatch(string=value.upper()) is None: 

60 self._raise_value_is_not_ulid(value=value) 

61 

62 def _raise_value_is_not_ulid(self, value: str) -> NoReturn: 1abcdefghij

63 """ 

64 Raise an error for an invalid ULID string. 

65 

66 Args: 

67 value (str): The invalid ULID string. 

68 

69 Raises: 

70 ValueError: Always raised with the invalid value. 

71 """ 

72 raise ValueError(f'UlidValueObject value <<<{value}>>> is not a valid ULID.')