Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ Added

Fixed
~~~~~
* The :class:`.ULID` constructor now accepts :class:`bytes` and bytes-like values (``bytearray``
and ``memoryview``), which are stored as immutable :class:`bytes`. A 16-character string or an
integer was previously accepted and produced an object whose ``str()`` failed or that was
unhashable, so other types now raise :exc:`TypeError`.
* Pydantic validation of unsupported values such as ``dict``, ``float`` or an out-of-range
``int`` now raises ``pydantic.ValidationError`` instead of leaking :exc:`TypeError` or
:exc:`OverflowError`.
Expand Down
41 changes: 41 additions & 0 deletions tests/test_ulid.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,47 @@ def test_ulid_max_input(constructor: Callable[[Params], ULID], value: Params) ->
constructor(value)


@pytest.mark.parametrize(
"value",
[
"x" * constants.BYTES_LEN,
123,
],
)
def test_ulid_constructor_rejects_non_bytes(value: object) -> None:
with pytest.raises(TypeError, match="Value has to be of type bytes"):
ULID(value) # type: ignore[arg-type]


@pytest.mark.parametrize(
"value",
[
bytes(range(constants.BYTES_LEN)),
bytearray(range(constants.BYTES_LEN)),
memoryview(bytes(range(constants.BYTES_LEN))),
],
)
def test_ulid_constructor_accepts_bytes_like(value: object) -> None:
raw = bytes(range(constants.BYTES_LEN))
ulid = ULID(value) # type: ignore[arg-type]
assert isinstance(ulid.bytes, bytes)
assert ulid.bytes == raw
assert ulid == ULID.from_bytes(raw)
assert hash(ulid) == hash(ULID.from_bytes(raw))


@pytest.mark.parametrize(
"value",
[
b"\x00" * (constants.BYTES_LEN - 1),
memoryview(b"\x00" * (constants.BYTES_LEN - 1)),
],
)
def test_ulid_constructor_rejects_wrong_length(value: object) -> None:
with pytest.raises(ValueError, match="exactly 16 bytes"):
ULID(value) # type: ignore[arg-type]


def test_pydantic_protocol() -> None:
ulid = ULID()

Expand Down
13 changes: 10 additions & 3 deletions ulid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,18 +258,25 @@ class ULID:
'01E75PVKXA3GFABX1M1J9NZZNF'

Args:
value (bytes, None): A sequence of 16 bytes representing an encoded ULID.
value (bytes, None): A sequence of 16 bytes representing an encoded ULID. Bytes-like
values (:class:`bytearray` and :class:`memoryview`) are converted to :class:`bytes`.

Raises:
TypeError: If the provided value is not :class:`bytes` or a bytes-like object.
ValueError: If the provided value is not a valid encoded ULID.
"""

def __init__(
self,
value: bytes | None = None,
) -> None:
if value is not None and len(value) != constants.BYTES_LEN:
raise ValueError("ULID has to be exactly 16 bytes long.")
if value is not None:
if isinstance(value, (bytearray, memoryview)):
value = bytes(value)
elif not isinstance(value, bytes):
raise TypeError("Value has to be of type bytes")
if len(value) != constants.BYTES_LEN:
raise ValueError("ULID has to be exactly 16 bytes long.")
if value is None:
self.bytes: bytes = default_generator.generate().bytes
else:
Expand Down
Loading