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

Added pydantic serialization to ULID #21

Merged
merged 4 commits into from
Apr 2, 2024
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
11 changes: 11 additions & 0 deletions tests/test_ulid.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import time
import uuid
from collections.abc import Callable
Expand Down Expand Up @@ -177,3 +178,13 @@ class Model(BaseModel):
for value in [b"not-enough", "not-enough"]:
with pytest.raises(ValidationError):
Model(ulid=value)

model_dict = model.model_dump()
ulid_from_dict = model_dict["ulid"]
assert ulid_from_dict == ulid
assert isinstance(ulid_from_dict, ULID)
assert Model(**model_dict) == model

model_json = model.model_dump_json()
assert isinstance(json.loads(model_json)["ulid"], str)
assert Model.model_validate_json(model_json) == model
3 changes: 3 additions & 0 deletions ulid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler
core_schema.no_info_plain_validator_function(ULID),
]
),
serialization=core_schema.to_string_ser_schema(
when_used="json-unless-none",
),
)

@classmethod
Expand Down