Skip to content

Commit

Permalink
fix(models): coerce numbers to strings by default
Browse files Browse the repository at this point in the history
  • Loading branch information
lengau committed Sep 6, 2024
1 parent c8ccf47 commit f27032f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions craft_application/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class CraftBaseModel(pydantic.BaseModel):
extra="forbid",
populate_by_name=True,
alias_generator=alias_generator,
coerce_numbers_to_str=True,
)

def marshal(self) -> dict[str, str | list[str] | dict[str, Any]]:
Expand Down
20 changes: 20 additions & 0 deletions tests/unit/models/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import pydantic
import pytest
from craft_application import errors, models
from hypothesis import given, strategies
from overrides import override


Expand Down Expand Up @@ -58,3 +59,22 @@ def test_model_reference_slug_errors():
)
assert str(err.value) == expected
assert err.value.doc_slug == "/mymodel.html"


class CoerceModel(models.CraftBaseModel):

stringy: str


@given(
strategies.one_of(
strategies.integers(),
strategies.floats(),
strategies.decimals(),
strategies.text(),
)
)
def test_model_coerces_to_strings(value):
result = CoerceModel.model_validate({"stringy": value})

assert result.stringy == str(value)

0 comments on commit f27032f

Please sign in to comment.