Skip to content
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
19 changes: 9 additions & 10 deletions src/py_avro_schema/_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -1188,16 +1188,6 @@ def data(self, names: NamesType) -> JSONObj:
field_data["aliases"] = sorted(self.aliases)
if self.default != dataclasses.MISSING:
default_value = self.schema.make_default(self.default)

# When a field is a string, but it's default value produces a UUID-like, we do not pass through the UUID
# schema (which already sets an empty default). We need to catch here the strings that look like a UUID
# and set a deterministic default.
if (
Option.DETERMINISTIC_DEFAULTS in self.options
and isinstance(default_value, str)
and (_UUID_PATTERN.match(default_value) or is_valid_datetime(default_value))
):
default_value = ""
field_data["default"] = default_value
if self.docs and Option.NO_DOC not in self.options:
field_data["doc"] = self.docs
Expand Down Expand Up @@ -1232,6 +1222,15 @@ def _record_field(self, py_field: dataclasses.Field) -> RecordField:
default = py_field.default
if callable(py_field.default_factory): # type: ignore
default = py_field.default_factory() # type: ignore
# When a field is a string, but it's default value produces a UUID-like, we do not pass through the UUID
# schema (which already sets an empty default). We need to catch here the strings that look like a UUID
# and set a deterministic default.
if (
Option.DETERMINISTIC_DEFAULTS in self.options
and isinstance(default, str)
and (_UUID_PATTERN.match(default) or is_valid_datetime(default))
):
default = ""
aliases, actual_type = get_field_aliases_and_actual_type(py_field.type) # type: ignore
field_obj = RecordField(
py_type=actual_type, # type: ignore
Expand Down
6 changes: 6 additions & 0 deletions tests/test_dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,7 @@ def timestamp_millis() -> str:
@dataclasses.dataclass
class PyType:
time: str = dataclasses.field(default_factory=lambda: timestamp_millis())
version: str = "2017-01-01"

expected = {
"type": "record",
Expand All @@ -963,6 +964,11 @@ class PyType:
"type": "string",
"default": "",
},
{
"name": "version",
"type": "string",
"default": "2017-01-01",
},
],
}
assert_schema(PyType, expected, options=pas.Option.DETERMINISTIC_DEFAULTS)
Loading