fix bug in union writing with tuple notation
MODIFY
fastavro/_write.pyx
fastavro/_write.pyx
@@ -242,15 +242,17 @@ cdef write_union(bytearray fo, datum, schema, dict named_schemas, fname):
cdef int32 most_fields
cdef int32 index
cdef int32 fields
+ cdef str extracted_type
cdef str schema_name
best_match_index = -1
if isinstance(datum, tuple):
(name, datum) = datum
for index, candidate in enumerate(schema):
- if extract_record_type(candidate) == "record":
+ extracted_type = extract_record_type(candidate)
+ if extracted_type == "record":
schema_name = candidate["name"]
else:
- schema_name = candidate
+ schema_name = extracted_type
if name == schema_name:
best_match_index = index
break

MODIFY
fastavro/_write_py.py
fastavro/_write_py.py
@@ -135,10 +135,11 @@ def write_union(encoder, datum, schema, named_schemas, fname):
if isinstance(datum, tuple):
(name, datum) = datum
for index, candidate in enumerate(schema):
- if extract_record_type(candidate) == "record":
+ extracted_type = extract_record_type(candidate)
+ if extracted_type == "record":
schema_name = candidate["name"]
else:
- schema_name = candidate
+ schema_name = extracted_type
if name == schema_name:
best_match_index = index
break

MODIFY
tests/test_fastavro.py
tests/test_fastavro.py
@@ -2505,3 +2505,35 @@ def test_reading_with_skip_using_pure_python():
)
assert roundtrip_records == [skip_record]
+
+
+def test_tuple_writer_picks_correct_union_path():
+ """https://github.com/fastavro/fastavro/issues/509"""
+ schema = {
+ "type": "record",
+ "name": "test_tuple_writer_picks_correct_union_path",
+ "fields": [
+ {
+ "name": "Field",
+ "type": [
+ {"type": "map", "values": "string"},
+ {
+ "type": "record",
+ "name": "Record2",
+ "fields": [{"name": "Field", "type": "string"}],
+ },
+ ],
+ },
+ ],
+ }
+
+ records = [{"Field": ("Record2", {"Field": "value"})}]
+ parsed_schema = fastavro.parse_schema(schema)
+ assert records == roundtrip(parsed_schema, records, return_record_name=True)
+
+ records = [{"Field": ("map", {"Field": "value"})}]
+ expected_roundtrip_value = [{"Field": {"Field": "value"}}]
+ parsed_schema = fastavro.parse_schema(schema)
+ assert expected_roundtrip_value == roundtrip(
+ parsed_schema, records, return_record_name=True
+ )

fix bug in union writing with tuple notation