1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
|
#!/usr/bin/env python3
##
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import contextlib
import itertools
import os
import tempfile
import unittest
import avro.codecs
import avro.datafile
import avro.io
import avro.schema
CODECS_TO_VALIDATE = avro.codecs.KNOWN_CODECS.keys()
TEST_PAIRS = tuple(
(avro.schema.parse(schema), datum)
for schema, datum in (
('"null"', None),
('"boolean"', True),
('"string"', "adsfasdf09809dsf-=adsf"),
('"bytes"', b"12345abcd"),
('"int"', 1234),
('"long"', 1234),
('"float"', 1234.0),
('"double"', 1234.0),
('{"type": "fixed", "name": "Test", "size": 1}', b"B"),
('{"type": "enum", "name": "Test", "symbols": ["A", "B"]}', "B"),
('{"type": "array", "items": "long"}', [1, 3, 2]),
('{"type": "map", "values": "long"}', {"a": 1, "b": 3, "c": 2}),
('["string", "null", "long"]', None),
(
"""\
{"type": "record",
"name": "Test",
"fields": [{"name": "f", "type": "long"}]}
""",
{"f": 5},
),
(
"""\
{"type": "record",
"name": "Lisp",
"fields": [{"name": "value",
"type": ["null", "string",
{"type": "record",
"name": "Cons",
"fields": [{"name": "car", "type": "Lisp"},
{"name": "cdr", "type": "Lisp"}]}]}]}
""",
{"value": {"car": {"value": "head"}, "cdr": {"value": None}}},
),
)
)
@contextlib.contextmanager
def writer(path, schema=None, codec=avro.datafile.NULL_CODEC, mode="wb"):
with avro.datafile.DataFileWriter(open(path, mode), avro.io.DatumWriter(), schema, codec) as dfw:
yield dfw
@contextlib.contextmanager
def reader(path, mode="rb"):
with avro.datafile.DataFileReader(open(path, mode), avro.io.DatumReader()) as dfr:
yield dfr
class TestDataFile(unittest.TestCase):
files = None
def setUp(self):
"""Initialize tempfiles collection."""
self.files = []
def tempfile(self):
"""Generate a tempfile and register it for cleanup."""
with tempfile.NamedTemporaryFile(delete=False, suffix=".avro") as f:
pass
self.files.append(f.name)
return f.name
def tearDown(self):
"""Clean up temporary files."""
for f in self.files:
os.unlink(f)
def test_append(self):
"""A datafile can be written to, appended to, and read from."""
for codec in CODECS_TO_VALIDATE:
for schema, datum in TEST_PAIRS:
# write data in binary to file once
path = self.tempfile()
with writer(path, schema, codec) as dfw:
dfw.append(datum)
# open file, write, and close nine times
for _ in range(9):
with writer(path, mode="ab+") as dfw:
dfw.append(datum)
# read data in binary from file
with reader(path) as dfr:
data = list(itertools.islice(dfr, 10))
self.assertRaises(StopIteration, next, dfr)
self.assertEqual(len(data), 10)
self.assertEqual(data, [datum] * 10)
def test_round_trip(self):
"""A datafile can be written to and read from."""
for codec in CODECS_TO_VALIDATE:
for schema, datum in TEST_PAIRS:
# write data in binary to file 10 times
path = self.tempfile()
with writer(path, schema, codec) as dfw:
for _ in range(10):
dfw.append(datum)
# read data in binary from file
with reader(path) as dfr:
data = list(itertools.islice(dfr, 10))
self.assertRaises(StopIteration, next, dfr)
self.assertEqual(len(data), 10)
self.assertEqual(data, [datum] * 10)
def test_context_manager(self):
"""A datafile closes its buffer object when it exits a with block."""
path = self.tempfile()
for schema, _ in TEST_PAIRS:
with writer(path, schema) as dfw:
self.assertFalse(dfw.writer.closed)
self.assertTrue(dfw.writer.closed)
with reader(path) as dfr:
self.assertFalse(dfr.reader.closed)
self.assertTrue(dfr.reader.closed)
def test_metadata(self):
"""Metadata can be written to a datafile, and read from it later."""
path = self.tempfile()
for schema, _ in TEST_PAIRS:
with writer(path, schema) as dfw:
dfw.set_meta("test.string", b"foo")
dfw.set_meta("test.number", b"1")
with reader(path) as dfr:
self.assertEqual(b"foo", dfr.get_meta("test.string"))
self.assertEqual(b"1", dfr.get_meta("test.number"))
def test_empty_datafile(self):
"""A reader should not fail to read a file consisting of a single empty block."""
path = self.tempfile()
for schema, _ in TEST_PAIRS:
with writer(path, schema) as dfw:
dfw.flush()
# Write an empty block
dfw.encoder.write_long(0)
dfw.encoder.write_long(0)
dfw.writer.write(dfw.sync_marker)
with reader(path) as dfr:
self.assertRaises(StopIteration, next, dfr)
|