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

(feat) Support for Pydantic field alias and serialization_alias #583

Merged
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
3 changes: 1 addition & 2 deletions dataclasses_avroschema/fields/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,7 @@ def to_dict(self) -> dict:
return dict(self.render())

@abc.abstractmethod
def get_avro_type(self) -> typing.Any:
... # pragma: no cover
def get_avro_type(self) -> typing.Any: ... # pragma: no cover

def fake(self) -> typing.Any:
return None
Expand Down
3 changes: 3 additions & 0 deletions dataclasses_avroschema/pydantic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@
mapper.LOGICAL_TYPES_FIELDS_CLASSES.update(PYDANTIC_LOGICAL_TYPES_FIELDS_CLASSES) # type: ignore
mapper.ALL_TYPES_FIELD_CLASSES.update(PYDANTIC_INMUTABLE_FIELDS_CLASSES)
mapper.ALL_TYPES_FIELD_CLASSES.update(PYDANTIC_LOGICAL_TYPES_FIELDS_CLASSES)


__all__ = ["AvroBaseModel"]
10 changes: 10 additions & 0 deletions dataclasses_avroschema/pydantic/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ def get_field_metadata(field_info: FieldInfo) -> dict[str, typing.Any]:
)
if field_info.description:
metadata["doc"] = field_info.description # type: ignore

aliases = set(metadata.get("aliases", []))

if field_info.alias is not None:
aliases.add(field_info.alias)
if field_info.serialization_alias is not None:
aliases.add(field_info.serialization_alias)
if aliases:
metadata["aliases"] = list(aliases)

return metadata

def parse_fields(self, exclude: typing.List) -> typing.List[Field]:
Expand Down
16 changes: 16 additions & 0 deletions tests/schemas/pydantic/test_pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,22 @@ class User(AvroBaseModel):
assert User.avro_schema() == json.dumps(expected_schema)


def test_pydantic_record_schema_with_aliases():
class User(AvroBaseModel):
foo: str = Field(alias="FOO")
bar: str = Field(serialization_alias="BAR")

expected_schema = {
"type": "record",
"name": "User",
"fields": [
{"aliases": ["FOO"], "name": "foo", "type": "string"},
{"aliases": ["BAR"], "name": "bar", "type": "string"},
],
}
assert User.avro_schema() == json.dumps(expected_schema)


def test_pydantic_record_schema_complex_types(user_advance_avro_json, color_enum):
class UserAdvance(AvroBaseModel):
name: str
Expand Down
Loading