diff --git a/dataclasses_avroschema/fields/base.py b/dataclasses_avroschema/fields/base.py index cb374ef9..e31cb340 100644 --- a/dataclasses_avroschema/fields/base.py +++ b/dataclasses_avroschema/fields/base.py @@ -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 diff --git a/dataclasses_avroschema/pydantic/__init__.py b/dataclasses_avroschema/pydantic/__init__.py index 5b9443f5..741c8021 100644 --- a/dataclasses_avroschema/pydantic/__init__.py +++ b/dataclasses_avroschema/pydantic/__init__.py @@ -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"] \ No newline at end of file diff --git a/dataclasses_avroschema/pydantic/parser.py b/dataclasses_avroschema/pydantic/parser.py index 88d7e2d0..7bb15f6f 100644 --- a/dataclasses_avroschema/pydantic/parser.py +++ b/dataclasses_avroschema/pydantic/parser.py @@ -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]: diff --git a/tests/schemas/pydantic/test_pydantic.py b/tests/schemas/pydantic/test_pydantic.py index 5310cebf..5b3befbb 100644 --- a/tests/schemas/pydantic/test_pydantic.py +++ b/tests/schemas/pydantic/test_pydantic.py @@ -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