Skip to content

Commit

Permalink
fix(charm-libs): better error message on bad version type
Browse files Browse the repository at this point in the history
  • Loading branch information
lengau committed Oct 11, 2024
1 parent 534c028 commit 681cdc0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
5 changes: 3 additions & 2 deletions charmcraft/models/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ class CharmLib(models.CraftBaseModel):
version: str = pydantic.Field(
title="Version filter for the charm. Either an API version or a specific [api].[patch].",
pattern=r"[0-9]+(\.[0-9]+)?",
coerce_numbers_to_str=False,
)

@pydantic.field_validator("lib", mode="before")
Expand Down Expand Up @@ -122,12 +123,12 @@ def _validate_api_version(cls, value: str) -> str:
int(api)
except ValueError:
raise ValueError(f"API version not valid. Expected an integer, got {api!r}") from None
return str(value)
return value

@pydantic.field_validator("version", mode="before")
def _validate_patch_version(cls, value: str) -> str:
"""Validate the optional patch version, providing a useful error message."""
api, separator, patch = value.partition(".")
api, separator, patch = str(value).partition(".")
if not separator:
return value
try:
Expand Down
9 changes: 9 additions & 0 deletions tests/unit/models/test_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,15 @@ def test_invalid_patch_version(version: str):
project.CharmLib(lib="charm_name.lib_name", version=version)


@pytest.mark.parametrize("version", [1, 1.1])
def test_bad_version_type(version: str):
with pytest.raises(
pydantic.ValidationError,
match="1 validation error for CharmLib\nversion\n Input should be a valid string",
):
project.CharmLib(lib="charm_name.lib_name", version=version)


@pytest.mark.parametrize(
("run_on", "expected"),
[
Expand Down

0 comments on commit 681cdc0

Please sign in to comment.