Skip to content

Commit

Permalink
feat: make_default of SequenceSchema can cope with default items (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
dada-engineer committed Mar 18, 2024
1 parent 1c55768 commit 6267bb6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
6 changes: 5 additions & 1 deletion src/py_avro_schema/_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,10 @@ def data(self, names: NamesType) -> JSONObj:
"items": self.items_schema.data(names=names),
}

def make_default(self, py_default: Any) -> Any:
origin = get_origin(self.py_type) or self.py_type
return origin(self.items_schema.make_default(item) for item in py_default)


class DictSchema(Schema):
"""An Avro map schema for a given Python mapping"""
Expand Down Expand Up @@ -905,7 +909,7 @@ def _record_field(self, name: str, py_field: pydantic.fields.FieldInfo) -> Recor

def make_default(self, py_default: pydantic.BaseModel) -> JSONObj:
"""Return an Avro schema compliant default value for a given Python value"""
return {key: _schema_obj(py_default.__annotations__[key]).make_default(value) for key, value in py_default}
return {key: _schema_obj(self._annotation(key)).make_default(value) for key, value in py_default}

def _annotation(self, field_name: str) -> Type:
"""
Expand Down
19 changes: 18 additions & 1 deletion tests/test_dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import decimal
import enum
import re
from typing import Annotated, Dict, List, Optional
from typing import Annotated, Dict, List, Optional, Tuple

import pytest
import typeguard
Expand Down Expand Up @@ -823,3 +823,20 @@ class PyType:
],
}
assert_schema(PyType, expected, do_doc=True)


def test_sequence_schema_defaults_with_items():
@dataclasses.dataclass
class PyType:
field_a: List[str] = dataclasses.field(default_factory=lambda: ["foo", "bar"])
field_b: Tuple[str, str] = dataclasses.field(default_factory=lambda: ("foo", "bar"))

expected = {
"fields": [
{"default": ["foo", "bar"], "name": "field_a", "type": {"items": "string", "type": "array"}},
{"default": ("foo", "bar"), "name": "field_b", "type": {"items": "string", "type": "array"}},
],
"name": "PyType",
"type": "record",
}
assert_schema(PyType, expected)

0 comments on commit 6267bb6

Please sign in to comment.