forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_io.py
More file actions
2032 lines (1547 loc) · 56.4 KB
/
Copy pathtest_io.py
File metadata and controls
2032 lines (1547 loc) · 56.4 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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
#
# http://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 bz2
from contextlib import contextmanager
from io import (BytesIO, StringIO, TextIOWrapper, BufferedIOBase, IOBase)
import itertools
import gc
import gzip
import math
import os
import pathlib
import pickle
import pytest
import sys
import tempfile
import weakref
import numpy as np
from pyarrow.util import guid
from pyarrow import Codec
import pyarrow as pa
def check_large_seeks(file_factory):
if sys.platform in ('win32', 'darwin'):
pytest.skip("need sparse file support")
try:
filename = tempfile.mktemp(prefix='test_io')
with open(filename, 'wb') as f:
f.truncate(2 ** 32 + 10)
f.seek(2 ** 32 + 5)
f.write(b'mark\n')
with file_factory(filename) as f:
assert f.seek(2 ** 32 + 5) == 2 ** 32 + 5
assert f.tell() == 2 ** 32 + 5
assert f.read(5) == b'mark\n'
assert f.tell() == 2 ** 32 + 10
finally:
os.unlink(filename)
@contextmanager
def assert_file_not_found():
with pytest.raises(FileNotFoundError):
yield
# ----------------------------------------------------------------------
# Python file-like objects
def test_python_file_write():
buf = BytesIO()
f = pa.PythonFile(buf)
assert f.tell() == 0
s1 = b'enga\xc3\xb1ado'
s2 = b'foobar'
f.write(s1)
assert f.tell() == len(s1)
f.write(s2)
expected = s1 + s2
result = buf.getvalue()
assert result == expected
assert not f.closed
f.close()
assert f.closed
with pytest.raises(TypeError, match="binary file expected"):
pa.PythonFile(StringIO())
def test_python_file_read():
data = b'some sample data'
buf = BytesIO(data)
f = pa.PythonFile(buf, mode='r')
assert f.size() == len(data)
assert f.tell() == 0
assert f.read(4) == b'some'
assert f.tell() == 4
f.seek(0)
assert f.tell() == 0
f.seek(5)
assert f.tell() == 5
v = f.read(50)
assert v == b'sample data'
assert len(v) == 11
assert f.size() == len(data)
assert not f.closed
f.close()
assert f.closed
with pytest.raises(TypeError, match="binary file expected"):
pa.PythonFile(StringIO(), mode='r')
@pytest.mark.parametrize("nbytes", (-1, 0, 1, 5, 100))
@pytest.mark.parametrize("file_offset", (-1, 0, 5, 100))
def test_python_file_get_stream(nbytes, file_offset):
data = b'data1data2data3data4data5'
f = pa.PythonFile(BytesIO(data), mode='r')
# negative nbytes or offsets don't make sense here, raise ValueError
if nbytes < 0 or file_offset < 0:
with pytest.raises(pa.ArrowInvalid,
match="should be a positive value"):
f.get_stream(file_offset=file_offset, nbytes=nbytes)
f.close()
return
else:
stream = f.get_stream(file_offset=file_offset, nbytes=nbytes)
# Subsequent calls to 'read' should match behavior if same
# data passed to BytesIO where get_stream should handle if
# nbytes/file_offset results in no bytes b/c out of bounds.
start = min(file_offset, len(data))
end = min(file_offset + nbytes, len(data))
buf = BytesIO(data[start:end])
# read some chunks
assert stream.read(nbytes=4) == buf.read(4)
assert stream.read(nbytes=6) == buf.read(6)
# Read to end of each stream
assert stream.read() == buf.read()
# Try reading past the stream
n = len(data) * 2
assert stream.read(n) == buf.read(n)
# NativeFile[CInputStream] is not seekable
with pytest.raises(OSError, match="seekable"):
stream.seek(0)
stream.close()
assert stream.closed
def test_python_file_read_at():
data = b'some sample data'
buf = BytesIO(data)
f = pa.PythonFile(buf, mode='r')
# test simple read at
v = f.read_at(nbytes=5, offset=3)
assert v == b'e sam'
assert len(v) == 5
# test reading entire file when nbytes > len(file)
w = f.read_at(nbytes=50, offset=0)
assert w == data
assert len(w) == 16
def test_python_file_readall():
data = b'some sample data'
buf = BytesIO(data)
with pa.PythonFile(buf, mode='r') as f:
assert f.readall() == data
def test_python_file_readinto():
length = 10
data = b'some sample data longer than 10'
dst_buf = bytearray(length)
src_buf = BytesIO(data)
with pa.PythonFile(src_buf, mode='r') as f:
assert f.readinto(dst_buf) == 10
assert dst_buf[:length] == data[:length]
assert len(dst_buf) == length
def test_python_file_read_buffer():
length = 10
data = b'0123456798'
dst_buf = bytearray(data)
class DuckReader:
def close(self):
pass
@property
def closed(self):
return False
def read_buffer(self, nbytes):
assert nbytes == length
return memoryview(dst_buf)[:nbytes]
duck_reader = DuckReader()
with pa.PythonFile(duck_reader, mode='r') as f:
buf = f.read_buffer(length)
assert len(buf) == length
assert memoryview(buf).tobytes() == dst_buf[:length]
# buf should point to the same memory, so modyfing it
memoryview(buf)[0] = ord(b'x')
# should modify the original
assert dst_buf[0] == ord(b'x')
def test_python_file_correct_abc():
with pa.PythonFile(BytesIO(b''), mode='r') as f:
assert isinstance(f, BufferedIOBase)
assert isinstance(f, IOBase)
def test_python_file_iterable():
data = b'''line1
line2
line3
'''
buf = BytesIO(data)
buf2 = BytesIO(data)
with pa.PythonFile(buf, mode='r') as f:
for read, expected in zip(f, buf2):
assert read == expected
def test_python_file_large_seeks():
def factory(filename):
return pa.PythonFile(open(filename, 'rb'))
check_large_seeks(factory)
def test_bytes_reader():
# Like a BytesIO, but zero-copy underneath for C++ consumers
data = b'some sample data'
f = pa.BufferReader(data)
assert f.tell() == 0
assert f.size() == len(data)
assert f.read(4) == b'some'
assert f.tell() == 4
f.seek(0)
assert f.tell() == 0
f.seek(0, 2)
assert f.tell() == len(data)
f.seek(5)
assert f.tell() == 5
assert f.read(50) == b'sample data'
assert not f.closed
f.close()
assert f.closed
def test_bytes_reader_non_bytes():
with pytest.raises(TypeError):
pa.BufferReader('some sample data')
def test_bytes_reader_retains_parent_reference():
import gc
# ARROW-421
def get_buffer():
data = b'some sample data' * 1000
reader = pa.BufferReader(data)
reader.seek(5)
return reader.read_buffer(6)
buf = get_buffer()
gc.collect()
assert buf.to_pybytes() == b'sample'
assert buf.parent is not None
def test_python_file_implicit_mode(tmpdir):
path = os.path.join(str(tmpdir), 'foo.txt')
with open(path, 'wb') as f:
pf = pa.PythonFile(f)
assert pf.writable()
assert not pf.readable()
assert not pf.seekable() # PyOutputStream isn't seekable
f.write(b'foobar\n')
with open(path, 'rb') as f:
pf = pa.PythonFile(f)
assert pf.readable()
assert not pf.writable()
assert pf.seekable()
assert pf.read() == b'foobar\n'
bio = BytesIO()
pf = pa.PythonFile(bio)
assert pf.writable()
assert not pf.readable()
assert not pf.seekable()
pf.write(b'foobar\n')
assert bio.getvalue() == b'foobar\n'
def test_python_file_writelines(tmpdir):
lines = [b'line1\n', b'line2\n' b'line3']
path = os.path.join(str(tmpdir), 'foo.txt')
with open(path, 'wb') as f:
try:
f = pa.PythonFile(f, mode='w')
assert f.writable()
f.writelines(lines)
finally:
f.close()
with open(path, 'rb') as f:
try:
f = pa.PythonFile(f, mode='r')
assert f.readable()
assert f.read() == b''.join(lines)
finally:
f.close()
def test_python_file_closing():
bio = BytesIO()
pf = pa.PythonFile(bio)
wr = weakref.ref(pf)
del pf
assert wr() is None # object was destroyed
assert not bio.closed
pf = pa.PythonFile(bio)
pf.close()
assert bio.closed
# ----------------------------------------------------------------------
# Buffers
def check_buffer_pickling(buf):
# Check that buffer survives a pickle roundtrip
for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1):
result = pickle.loads(pickle.dumps(buf, protocol=protocol))
assert len(result) == len(buf)
assert memoryview(result) == memoryview(buf)
assert result.to_pybytes() == buf.to_pybytes()
assert result.is_mutable == buf.is_mutable
def test_buffer_bytes():
val = b'some data'
buf = pa.py_buffer(val)
assert isinstance(buf, pa.Buffer)
assert not buf.is_mutable
assert buf.is_cpu
result = buf.to_pybytes()
assert result == val
check_buffer_pickling(buf)
def test_buffer_null_data():
null_buff = pa.foreign_buffer(address=0, size=0)
assert null_buff.to_pybytes() == b""
assert null_buff.address == 0
# ARROW-16048: we shouldn't expose a NULL address through the Python
# buffer protocol.
m = memoryview(null_buff)
assert m.tobytes() == b""
assert pa.py_buffer(m).address != 0
check_buffer_pickling(null_buff)
def test_buffer_memoryview():
val = b'some data'
buf = pa.py_buffer(val)
assert isinstance(buf, pa.Buffer)
assert not buf.is_mutable
assert buf.is_cpu
result = memoryview(buf)
assert result == val
check_buffer_pickling(buf)
def test_buffer_bytearray():
val = bytearray(b'some data')
buf = pa.py_buffer(val)
assert isinstance(buf, pa.Buffer)
assert buf.is_mutable
assert buf.is_cpu
result = bytearray(buf)
assert result == val
check_buffer_pickling(buf)
def test_buffer_invalid():
with pytest.raises(TypeError,
match="(bytes-like object|buffer interface)"):
pa.py_buffer(None)
def test_buffer_weakref():
buf = pa.py_buffer(b'some data')
wr = weakref.ref(buf)
assert wr() is not None
del buf
assert wr() is None
@pytest.mark.parametrize('val, expected_hex_buffer',
[(b'check', b'636865636B'),
(b'\a0', b'0730'),
(b'', b'')])
def test_buffer_hex(val, expected_hex_buffer):
buf = pa.py_buffer(val)
assert buf.hex() == expected_hex_buffer
def test_buffer_to_numpy():
# Make sure creating a numpy array from an arrow buffer works
byte_array = bytearray(20)
byte_array[0] = 42
buf = pa.py_buffer(byte_array)
array = np.frombuffer(buf, dtype="uint8")
assert array[0] == byte_array[0]
byte_array[0] += 1
assert array[0] == byte_array[0]
assert array.base == buf
def test_buffer_from_numpy():
# C-contiguous
arr = np.arange(12, dtype=np.int8).reshape((3, 4))
buf = pa.py_buffer(arr)
assert buf.is_cpu
assert buf.is_mutable
assert buf.to_pybytes() == arr.tobytes()
# F-contiguous; note strides information is lost
buf = pa.py_buffer(arr.T)
assert buf.is_cpu
assert buf.is_mutable
assert buf.to_pybytes() == arr.tobytes()
# Non-contiguous
with pytest.raises(ValueError, match="not contiguous"):
buf = pa.py_buffer(arr.T[::2])
def test_buffer_address():
b1 = b'some data!'
b2 = bytearray(b1)
b3 = bytearray(b1)
buf1 = pa.py_buffer(b1)
buf2 = pa.py_buffer(b1)
buf3 = pa.py_buffer(b2)
buf4 = pa.py_buffer(b3)
assert buf1.address > 0
assert buf1.address == buf2.address
assert buf3.address != buf2.address
assert buf4.address != buf3.address
arr = np.arange(5)
buf = pa.py_buffer(arr)
assert buf.address == arr.ctypes.data
def test_buffer_equals():
# Buffer.equals() returns true iff the buffers have the same contents
def eq(a, b):
assert a.equals(b)
assert a == b
assert not (a != b)
def ne(a, b):
assert not a.equals(b)
assert not (a == b)
assert a != b
b1 = b'some data!'
b2 = bytearray(b1)
b3 = bytearray(b1)
b3[0] = 42
buf1 = pa.py_buffer(b1)
buf2 = pa.py_buffer(b2)
buf3 = pa.py_buffer(b2)
buf4 = pa.py_buffer(b3)
buf5 = pa.py_buffer(np.frombuffer(b2, dtype=np.int16))
eq(buf1, buf1)
eq(buf1, buf2)
eq(buf2, buf3)
ne(buf2, buf4)
# Data type is indifferent
eq(buf2, buf5)
def test_buffer_eq_bytes():
buf = pa.py_buffer(b'some data')
assert buf == b'some data'
assert buf == bytearray(b'some data')
assert buf != b'some dat1'
with pytest.raises(TypeError):
buf == 'some data'
def test_buffer_getitem():
data = bytearray(b'some data!')
buf = pa.py_buffer(data)
n = len(data)
for ix in range(-n, n - 1):
assert buf[ix] == data[ix]
with pytest.raises(IndexError):
buf[n]
with pytest.raises(IndexError):
buf[-n - 1]
def test_buffer_slicing():
data = b'some data!'
buf = pa.py_buffer(data)
sliced = buf.slice(2)
expected = pa.py_buffer(b'me data!')
assert sliced.equals(expected)
sliced2 = buf.slice(2, 4)
expected2 = pa.py_buffer(b'me d')
assert sliced2.equals(expected2)
# 0 offset
assert buf.slice(0).equals(buf)
# Slice past end of buffer
assert len(buf.slice(len(buf))) == 0
with pytest.raises(IndexError):
buf.slice(-1)
with pytest.raises(IndexError):
buf.slice(len(buf) + 1)
assert buf[11:].to_pybytes() == b""
# Slice stop exceeds buffer length
with pytest.raises(IndexError):
buf.slice(1, len(buf))
assert buf[1:11].to_pybytes() == buf.to_pybytes()[1:]
# Negative length
with pytest.raises(IndexError):
buf.slice(1, -1)
# Test slice notation
assert buf[2:].equals(buf.slice(2))
assert buf[2:5].equals(buf.slice(2, 3))
assert buf[-5:].equals(buf.slice(len(buf) - 5))
assert buf[-5:-2].equals(buf.slice(len(buf) - 5, 3))
with pytest.raises(IndexError):
buf[::-1]
with pytest.raises(IndexError):
buf[::2]
n = len(buf)
for start in range(-n * 2, n * 2):
for stop in range(-n * 2, n * 2):
assert buf[start:stop].to_pybytes() == buf.to_pybytes()[start:stop]
def test_buffer_hashing():
# Buffers are unhashable
with pytest.raises(TypeError, match="unhashable"):
hash(pa.py_buffer(b'123'))
def test_buffer_protocol_respects_immutability():
# ARROW-3228; NumPy's frombuffer ctor determines whether a buffer-like
# object is mutable by first attempting to get a mutable buffer using
# PyObject_FromBuffer. If that fails, it assumes that the object is
# immutable
a = b'12345'
arrow_ref = pa.py_buffer(a)
numpy_ref = np.frombuffer(arrow_ref, dtype=np.uint8)
assert not numpy_ref.flags.writeable
def test_foreign_buffer():
obj = np.array([1, 2], dtype=np.int32)
addr = obj.__array_interface__["data"][0]
size = obj.nbytes
buf = pa.foreign_buffer(addr, size, obj)
wr = weakref.ref(obj)
del obj
assert np.frombuffer(buf, dtype=np.int32).tolist() == [1, 2]
assert wr() is not None
del buf
assert wr() is None
def test_allocate_buffer():
buf = pa.allocate_buffer(100)
assert buf.size == 100
assert buf.is_mutable
assert buf.parent is None
bit = b'abcde'
writer = pa.FixedSizeBufferWriter(buf)
writer.write(bit)
assert buf.to_pybytes()[:5] == bit
def test_allocate_buffer_resizable():
buf = pa.allocate_buffer(100, resizable=True)
assert isinstance(buf, pa.ResizableBuffer)
buf.resize(200)
assert buf.size == 200
@pytest.mark.parametrize("compression", [
pytest.param(
"bz2", marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError)
),
"brotli",
"gzip",
"lz4",
"zstd",
"snappy"
])
def test_compress_decompress(compression):
if not Codec.is_available(compression):
pytest.skip("{} support is not built".format(compression))
INPUT_SIZE = 10000
test_data = (np.random.randint(0, 255, size=INPUT_SIZE)
.astype(np.uint8)
.tobytes())
test_buf = pa.py_buffer(test_data)
compressed_buf = pa.compress(test_buf, codec=compression)
compressed_bytes = pa.compress(test_data, codec=compression,
asbytes=True)
assert isinstance(compressed_bytes, bytes)
decompressed_buf = pa.decompress(compressed_buf, INPUT_SIZE,
codec=compression)
decompressed_bytes = pa.decompress(compressed_bytes, INPUT_SIZE,
codec=compression, asbytes=True)
assert isinstance(decompressed_bytes, bytes)
assert decompressed_buf.equals(test_buf)
assert decompressed_bytes == test_data
with pytest.raises(ValueError):
pa.decompress(compressed_bytes, codec=compression)
@pytest.mark.parametrize("compression", [
pytest.param(
"bz2", marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError)
),
"brotli",
"gzip",
"lz4",
"zstd",
"snappy"
])
def test_compression_level(compression):
if not Codec.is_available(compression):
pytest.skip("{} support is not built".format(compression))
codec = Codec(compression)
if codec.name == "snappy":
assert codec.compression_level is None
else:
assert isinstance(codec.compression_level, int)
# These codecs do not support a compression level
no_level = ['snappy']
if compression in no_level:
assert not Codec.supports_compression_level(compression)
with pytest.raises(ValueError):
Codec(compression, 0)
with pytest.raises(ValueError):
Codec.minimum_compression_level(compression)
with pytest.raises(ValueError):
Codec.maximum_compression_level(compression)
with pytest.raises(ValueError):
Codec.default_compression_level(compression)
return
INPUT_SIZE = 10000
test_data = (np.random.randint(0, 255, size=INPUT_SIZE)
.astype(np.uint8)
.tobytes())
test_buf = pa.py_buffer(test_data)
min_level = Codec.minimum_compression_level(compression)
max_level = Codec.maximum_compression_level(compression)
default_level = Codec.default_compression_level(compression)
assert min_level < max_level
assert default_level >= min_level
assert default_level <= max_level
for compression_level in range(min_level, max_level+1):
codec = Codec(compression, compression_level)
compressed_buf = codec.compress(test_buf)
compressed_bytes = codec.compress(test_data, asbytes=True)
assert isinstance(compressed_bytes, bytes)
decompressed_buf = codec.decompress(compressed_buf, INPUT_SIZE)
decompressed_bytes = codec.decompress(compressed_bytes, INPUT_SIZE,
asbytes=True)
assert isinstance(decompressed_bytes, bytes)
assert decompressed_buf.equals(test_buf)
assert decompressed_bytes == test_data
with pytest.raises(ValueError):
codec.decompress(compressed_bytes)
# The ability to set a seed this way is not present on older versions of
# numpy (currently in our python 3.6 CI build). Some inputs might just
# happen to compress the same between the two levels so using seeded
# random numbers is necessary to help get more reliable results
#
# The goal of this part is to ensure the compression_level is being
# passed down to the C++ layer, not to verify the compression algs
# themselves
if not hasattr(np.random, 'default_rng'):
pytest.skip('Requires newer version of numpy')
rng = np.random.default_rng(seed=42)
values = rng.integers(0, 100, 1000)
arr = pa.array(values)
hard_to_compress_buffer = arr.buffers()[1]
weak_codec = Codec(compression, min_level)
weakly_compressed_buf = weak_codec.compress(hard_to_compress_buffer)
strong_codec = Codec(compression, max_level)
strongly_compressed_buf = strong_codec.compress(hard_to_compress_buffer)
assert len(weakly_compressed_buf) > len(strongly_compressed_buf)
def test_buffer_memoryview_is_immutable():
val = b'some data'
buf = pa.py_buffer(val)
assert not buf.is_mutable
assert isinstance(buf, pa.Buffer)
result = memoryview(buf)
assert result.readonly
with pytest.raises(TypeError) as exc:
result[0] = b'h'
assert 'cannot modify read-only' in str(exc.value)
b = bytes(buf)
with pytest.raises(TypeError) as exc:
b[0] = b'h'
assert 'cannot modify read-only' in str(exc.value)
def test_uninitialized_buffer():
# ARROW-2039: calling Buffer() directly creates an uninitialized object
# ARROW-2638: prevent calling extension class constructors directly
with pytest.raises(TypeError):
pa.Buffer()
def test_memory_output_stream():
# 10 bytes
val = b'dataabcdef'
f = pa.BufferOutputStream()
K = 1000
for i in range(K):
f.write(val)
buf = f.getvalue()
assert len(buf) == len(val) * K
assert buf.to_pybytes() == val * K
def test_inmemory_write_after_closed():
f = pa.BufferOutputStream()
f.write(b'ok')
assert not f.closed
f.getvalue()
assert f.closed
with pytest.raises(ValueError):
f.write(b'not ok')
def test_buffer_protocol_ref_counting():
def make_buffer(bytes_obj):
return bytearray(pa.py_buffer(bytes_obj))
buf = make_buffer(b'foo')
gc.collect()
assert buf == b'foo'
# ARROW-1053
val = b'foo'
refcount_before = sys.getrefcount(val)
for i in range(10):
make_buffer(val)
gc.collect()
assert refcount_before == sys.getrefcount(val)
def test_nativefile_write_memoryview():
f = pa.BufferOutputStream()
data = b'ok'
arr = np.frombuffer(data, dtype='S1')
f.write(arr)
f.write(bytearray(data))
f.write(pa.py_buffer(data))
with pytest.raises(TypeError):
f.write(data.decode('utf8'))
buf = f.getvalue()
assert buf.to_pybytes() == data * 3
# ----------------------------------------------------------------------
# Mock output stream
def test_mock_output_stream():
# Make sure that the MockOutputStream and the BufferOutputStream record the
# same size
# 10 bytes
val = b'dataabcdef'
f1 = pa.MockOutputStream()
f2 = pa.BufferOutputStream()
K = 1000
for i in range(K):
f1.write(val)
f2.write(val)
assert f1.size() == len(f2.getvalue())
# Do the same test with a table
record_batch = pa.RecordBatch.from_arrays([pa.array([1, 2, 3])], ['a'])
f1 = pa.MockOutputStream()
f2 = pa.BufferOutputStream()
stream_writer1 = pa.RecordBatchStreamWriter(f1, record_batch.schema)
stream_writer2 = pa.RecordBatchStreamWriter(f2, record_batch.schema)
stream_writer1.write_batch(record_batch)
stream_writer2.write_batch(record_batch)
stream_writer1.close()
stream_writer2.close()
assert f1.size() == len(f2.getvalue())
# ----------------------------------------------------------------------
# OS files and memory maps
@pytest.fixture
def sample_disk_data(request, tmpdir):
SIZE = 4096
arr = np.random.randint(0, 256, size=SIZE).astype('u1')
data = arr.tobytes()[:SIZE]
path = os.path.join(str(tmpdir), guid())
with open(path, 'wb') as f:
f.write(data)
def teardown():
_try_delete(path)
request.addfinalizer(teardown)
return path, data
def _check_native_file_reader(FACTORY, sample_data,
allow_read_out_of_bounds=True):
path, data = sample_data
f = FACTORY(path, mode='r')
assert f.read(10) == data[:10]
assert f.read(0) == b''
assert f.tell() == 10
assert f.read() == data[10:]
assert f.size() == len(data)
f.seek(0)
assert f.tell() == 0
# Seeking past end of file not supported in memory maps
if allow_read_out_of_bounds:
f.seek(len(data) + 1)
assert f.tell() == len(data) + 1
assert f.read(5) == b''
# Test whence argument of seek, ARROW-1287
assert f.seek(3) == 3
assert f.seek(3, os.SEEK_CUR) == 6
assert f.tell() == 6
ex_length = len(data) - 2
assert f.seek(-2, os.SEEK_END) == ex_length
assert f.tell() == ex_length
def test_memory_map_reader(sample_disk_data):
_check_native_file_reader(pa.memory_map, sample_disk_data,
allow_read_out_of_bounds=False)
def test_memory_map_retain_buffer_reference(sample_disk_data):
path, data = sample_disk_data
cases = []
with pa.memory_map(path, 'rb') as f:
cases.append((f.read_buffer(100), data[:100]))
cases.append((f.read_buffer(100), data[100:200]))
cases.append((f.read_buffer(100), data[200:300]))
# Call gc.collect() for good measure
gc.collect()
for buf, expected in cases:
assert buf.to_pybytes() == expected
def test_os_file_reader(sample_disk_data):
_check_native_file_reader(pa.OSFile, sample_disk_data)