Skip to content

Commit

Permalink
AmpelBaseModel: add switch for serializer errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jvansanten committed May 28, 2024
1 parent b22bd65 commit f745ee4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
4 changes: 3 additions & 1 deletion ampel/base/AmpelBaseModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,14 @@ def dict(
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
warnings: bool = True,
) -> dict[str, Any]:
return self.model_dump(
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none
exclude_none=exclude_none,
warnings=warnings,
)
2 changes: 0 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ profile = "black"
minversion = "6.0"
filterwarnings = [
"error",
# Expected `list[definition-ref]` but got `tuple` - serialized value may not be as expected
"ignore:Pydantic serializer warnings:UserWarning",
]

[tool.mypy]
Expand Down
30 changes: 30 additions & 0 deletions tests/test_AmpelBaseModel.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import re
from collections.abc import Sequence
from types import UnionType
from typing import Generic, TypeVar, Union, get_origin

Expand Down Expand Up @@ -122,3 +124,31 @@ class Base(AmpelUnit):
class Derived(Base, AmpelBaseModel): ...

assert Base().dict() == {"base": 1}


def test_serialize_sequence_field_with_tuple():
class M(AmpelBaseModel):
a: Sequence[int]

model = M(a=(1,))
assert model.dict(warnings=False) == {"a": (1,)}

# We sometimes use `Sequence[T]` as shorthand for `list[T] | tuple[T]`, but
# pydantic uses a list serializer for all Sequence types and complains when
# it sees a tuple. We suppress these warnings by setting warnings=False by
# default, and rely on validators to ensure that our model fields have the
# correct types. See https://github.com/pydantic/pydantic-core/issues/133
# for a discussion of why pydantic doesn't directly support Sequence.
with pytest.warns(
UserWarning,
match=re.escape(
"Pydantic serializer warnings:\n Expected `list[int]` but got `tuple` - serialized value may not be as expected"
),
):
assert model.dict(warnings=True) == {"a": (1,)}

class M(AmpelBaseModel):
a: list[int] | tuple[int, ...]

model = M(a=(1,))
assert model.dict(warnings=True) == {"a": (1,)}

0 comments on commit f745ee4

Please sign in to comment.