Skip to content

Commit 14b4885

Browse files
authored
Added pydantic serialization to ULID (#21)
* Added serializer to the model. * Fixed serializer to work only on Json. * Added serialization tests. * Changed to to string schema.
1 parent 76f9741 commit 14b4885

2 files changed

Lines changed: 14 additions & 0 deletions

File tree

tests/test_ulid.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
import time
23
import uuid
34
from collections.abc import Callable
@@ -177,3 +178,13 @@ class Model(BaseModel):
177178
for value in [b"not-enough", "not-enough"]:
178179
with pytest.raises(ValidationError):
179180
Model(ulid=value)
181+
182+
model_dict = model.model_dump()
183+
ulid_from_dict = model_dict["ulid"]
184+
assert ulid_from_dict == ulid
185+
assert isinstance(ulid_from_dict, ULID)
186+
assert Model(**model_dict) == model
187+
188+
model_json = model.model_dump_json()
189+
assert isinstance(json.loads(model_json)["ulid"], str)
190+
assert Model.model_validate_json(model_json) == model

ulid/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,9 @@ def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler
261261
core_schema.no_info_plain_validator_function(ULID),
262262
]
263263
),
264+
serialization=core_schema.to_string_ser_schema(
265+
when_used="json-unless-none",
266+
),
264267
)
265268

266269
@classmethod

0 commit comments

Comments
 (0)