From f27032fa77f1f6c19505dbfceba0a71ce0ae162a Mon Sep 17 00:00:00 2001 From: Alex Lowe Date: Fri, 6 Sep 2024 09:44:48 -0400 Subject: [PATCH] fix(models): coerce numbers to strings by default As seen in: https://github.com/canonical/snapcraft/issues/4978 https://github.com/canonical/snapcraft/issues/5017 --- craft_application/models/base.py | 1 + tests/unit/models/test_base.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/craft_application/models/base.py b/craft_application/models/base.py index 08e30438..cd261f77 100644 --- a/craft_application/models/base.py +++ b/craft_application/models/base.py @@ -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]]: diff --git a/tests/unit/models/test_base.py b/tests/unit/models/test_base.py index 2d9390a8..da7067c6 100644 --- a/tests/unit/models/test_base.py +++ b/tests/unit/models/test_base.py @@ -19,6 +19,7 @@ import pydantic import pytest from craft_application import errors, models +from hypothesis import given, strategies from overrides import override @@ -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)