add test to catch a common mistake of trying to write a single record
MODIFY
fastavro/_write.pyx
fastavro/_write.pyx
@@ -678,6 +678,11 @@ def writer(fo,
sync_interval=1000 * SYNC_SIZE,
metadata=None,
validator=None):
+ # Sanity check that records is not a single dictionary (as that is a common
+ # mistake and the exception that gets raised is not helpful)
+ if isinstance(records, dict):
+ raise ValueError('"records" argument should be an iterable, not dict')
+
output = Writer(
fo,
schema,

MODIFY
fastavro/_write_py.py
fastavro/_write_py.py
@@ -523,7 +523,8 @@ def writer(fo,
fo: file-like
Output stream
records: iterable
- Records to write
+ Records to write. This is commonly a list of the dictionary
+ representation of the records, but it can be any iterable
codec: string, optional
Compression codec, can be 'null', 'deflate' or 'snappy' (if installed)
sync_interval: int, optional
@@ -564,6 +565,11 @@ def writer(fo,
with open('weather.avro', 'wb') as out:
writer(out, parsed_schema, records)
"""
+ # Sanity check that records is not a single dictionary (as that is a common
+ # mistake and the exception that gets raised is not helpful)
+ if isinstance(records, dict):
+ raise ValueError('"records" argument should be an iterable, not dict')
+
output = Writer(
fo,
schema,

MODIFY
tests/test_fastavro.py
tests/test_fastavro.py
@@ -1498,3 +1498,26 @@ def test_passing_same_schema_to_reader():
}]
assert records == roundtrip(schema, records, pass_schema_to_reader=True)
+
+
+def test_helpful_error_when_a_single_record_is_passed_to_writer():
+ """https://github.com/fastavro/fastavro/issues/254"""
+ schema = {
+ 'namespace': 'namespace',
+ 'name': 'name',
+ 'type': 'record',
+ 'fields': [{
+ 'name': 'is_error',
+ 'type': 'boolean',
+ }]
+ }
+
+ record = {
+ 'is_error': True,
+ }
+
+ new_file = MemoryIO()
+ with pytest.raises(ValueError) as exc:
+ fastavro.writer(new_file, schema, record)
+
+ assert "argument should be an iterable, not dict" in str(exc)

add test to catch a common mistake of trying to write a single record