def test_read_write(self, tmpfile, num, comp): options = {} if comp is not None: options['compression'] = comp options['level'] = 1 + num * 2 options['shuffle'] = num % 2 entries = [ ('a', 'json', {'a': 'b'}), ('b', 'array', np.array([1, 2, 3], 'float32')), ('c', 'json', 42), ('d', 'array', np.rec.fromarrays([[1, 2], [3, 4]], names='x, y')), ('e', 'array', ['foo', 'bar']) ] index = {'a': 0, 'b': 1, 'c': 0, 'd': 1, 'e': 1} with File(tmpfile, 'w') as f: for key, tp, data in entries: getattr(f, 'write_' + tp)(key, data) assert ''.join(f) == 'abcde' assert {k: v[0] for k, v in f._index.items()} == index f = File(tmpfile) assert ''.join(f) == 'abcde' assert {k: v[0] for k, v in f._index.items()} == index for key, tp, data in entries: if tp == 'json': assert f.read(key) == data else: np.testing.assert_array_equal(f.read(key), data)
def test_close_handle(self, tmpfile): f = File(tmpfile, 'w') f.close() pytest.raises_regexp(IOError, 'the file handle has been closed', f.read, 'foo') pytest.raises_regexp(IOError, 'the file handle has been closed', f.write_array, 'foo', [1, 2]) pytest.raises_regexp(IOError, 'the file handle has been closed', f.write_json, 'foo', [1, 2]) f.close() assert f.filename == tmpfile assert f.writable f = File(tmpfile) f.close() f.close() with File(tmpfile) as f: assert f._handle is not None assert f._handle is None pytest.raises_regexp(IOError, 'the file handle has been closed', f.read, 'foo')
def test_invalid_key(self, tmpfile): f = File(tmpfile, 'w') pytest.raises_regexp(ValueError, 'invalid key: expected string', f.write_json, 42, 0) pytest.raises_regexp(ValueError, 'invalid key: empty string', f.write_json, '', 0) f.write_json('foo', 'bar') pytest.raises_regexp(ValueError, "key already exists: 'foo'", f.write_json, 'foo', 'baz') f.close() f = File(tmpfile) pytest.raises_regexp(ValueError, 'invalid key: expected string', f.read, 42) pytest.raises_regexp(KeyError, 'bar', f.read, 'bar')
def test_iter(self, tmpfile): f = File(tmpfile, 'w') f.write_array('c', 10) f.write_array('a', [1, 2, 3]) f.write_json('b', {'foo': 'bar'}) f.write_json('d', 42) assert list(f) == ['a', 'b', 'c', 'd'] f.close() f = File(tmpfile) assert list(f) == ['a', 'b', 'c', 'd']