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

Fix issues with serialization and GDA compatibility #139

Merged
merged 3 commits into from
Apr 21, 2023
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
1 change: 1 addition & 0 deletions src/blueapi/utils/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class BlueapiModelConfig(BaseConfig):

alias_generator = _to_camel
extra = Extra.forbid
allow_population_by_field_name = True


class BlueapiPlanModelConfig(BlueapiModelConfig):
Expand Down
4 changes: 3 additions & 1 deletion src/blueapi/utils/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ def serialize(obj: Any) -> Any:
"""

if isinstance(obj, BaseModel):
return obj.dict()
# Serialize by alias so that our camelCase models leave the service
# with camelCase field names
return obj.dict(by_alias=True)
elif hasattr(obj, "__pydantic_model__"):
return serialize(getattr(obj, "__pydantic_model__"))
else:
Expand Down
25 changes: 25 additions & 0 deletions tests/utils/test_base_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from blueapi.utils import BlueapiBaseModel


class FooBar(BlueapiBaseModel):
hello: str = "hello"
hello_world: str = "hello world"


def test_snake_case_constructor() -> None:
FooBar(
hello="hello",
hello_world="hello world",
)


def test_camel_case_parsing() -> None:
assert FooBar.parse_obj(
{
"hello": "hello",
"helloWorld": "hello world",
}
) == FooBar(
hello="hello",
hello_world="hello world",
)