-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathtest_convert_builtin.py
2498 lines (2015 loc) · 76.7 KB
/
test_convert_builtin.py
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 collections
import datetime
import decimal
import itertools
import math
import re
import hypothesis as h
import numpy as np
import pytest
from pyarrow.pandas_compat import _pandas_api # noqa
import pyarrow as pa
import pyarrow.tests.strategies as past
int_type_pairs = [
(np.int8, pa.int8()),
(np.int16, pa.int16()),
(np.int32, pa.int32()),
(np.int64, pa.int64()),
(np.uint8, pa.uint8()),
(np.uint16, pa.uint16()),
(np.uint32, pa.uint32()),
(np.uint64, pa.uint64())]
np_int_types, pa_int_types = zip(*int_type_pairs)
class StrangeIterable:
def __init__(self, lst):
self.lst = lst
def __iter__(self):
return self.lst.__iter__()
class MyInt:
def __init__(self, value):
self.value = value
def __int__(self):
return self.value
class MyBrokenInt:
def __int__(self):
1/0 # MARKER
def check_struct_type(ty, expected):
"""
Check a struct type is as expected, but not taking order into account.
"""
assert pa.types.is_struct(ty)
assert set(ty) == set(expected)
def test_iterable_types():
arr1 = pa.array(StrangeIterable([0, 1, 2, 3]))
arr2 = pa.array((0, 1, 2, 3))
assert arr1.equals(arr2)
def test_empty_iterable():
arr = pa.array(StrangeIterable([]))
assert len(arr) == 0
assert arr.null_count == 0
assert arr.type == pa.null()
assert arr.to_pylist() == []
def test_limited_iterator_types():
arr1 = pa.array(iter(range(3)), type=pa.int64(), size=3)
arr2 = pa.array((0, 1, 2))
assert arr1.equals(arr2)
def test_limited_iterator_size_overflow():
arr1 = pa.array(iter(range(3)), type=pa.int64(), size=2)
arr2 = pa.array((0, 1))
assert arr1.equals(arr2)
def test_limited_iterator_size_underflow():
arr1 = pa.array(iter(range(3)), type=pa.int64(), size=10)
arr2 = pa.array((0, 1, 2))
assert arr1.equals(arr2)
def test_iterator_without_size():
expected = pa.array((0, 1, 2))
arr1 = pa.array(iter(range(3)))
assert arr1.equals(expected)
# Same with explicit type
arr1 = pa.array(iter(range(3)), type=pa.int64())
assert arr1.equals(expected)
def test_infinite_iterator():
expected = pa.array((0, 1, 2))
arr1 = pa.array(itertools.count(0), size=3)
assert arr1.equals(expected)
# Same with explicit type
arr1 = pa.array(itertools.count(0), type=pa.int64(), size=3)
assert arr1.equals(expected)
def test_failing_iterator():
with pytest.raises(ZeroDivisionError):
pa.array((1 // 0 for x in range(10)))
# ARROW-17253
with pytest.raises(ZeroDivisionError):
pa.array((1 // 0 for x in range(10)), size=10)
class ObjectWithOnlyGetitem:
def __getitem__(self, key):
return 3
def test_object_with_getitem():
# https://github.com/apache/arrow/issues/34944
# considered as sequence because of __getitem__, but has no length
with pytest.raises(TypeError, match="has no len()"):
pa.array(ObjectWithOnlyGetitem())
def _as_list(xs):
return xs
def _as_tuple(xs):
return tuple(xs)
def _as_deque(xs):
# deque is a sequence while neither tuple nor list
return collections.deque(xs)
def _as_dict_values(xs):
# a dict values object is not a sequence, just a regular iterable
dct = {k: v for k, v in enumerate(xs)}
return dct.values()
def _as_numpy_array(xs):
arr = np.empty(len(xs), dtype=object)
arr[:] = xs
return arr
def _as_set(xs):
return set(xs)
SEQUENCE_TYPES = [_as_list, _as_tuple, _as_numpy_array]
ITERABLE_TYPES = [_as_set, _as_dict_values] + SEQUENCE_TYPES
COLLECTIONS_TYPES = [_as_deque] + ITERABLE_TYPES
parametrize_with_iterable_types = pytest.mark.parametrize(
"seq", ITERABLE_TYPES
)
parametrize_with_sequence_types = pytest.mark.parametrize(
"seq", SEQUENCE_TYPES
)
parametrize_with_collections_types = pytest.mark.parametrize(
"seq", COLLECTIONS_TYPES
)
@parametrize_with_collections_types
def test_sequence_types(seq):
arr1 = pa.array(seq([1, 2, 3]))
arr2 = pa.array([1, 2, 3])
assert arr1.equals(arr2)
@parametrize_with_iterable_types
def test_nested_sequence_types(seq):
arr1 = pa.array([seq([1, 2, 3])])
arr2 = pa.array([[1, 2, 3]])
assert arr1.equals(arr2)
@parametrize_with_sequence_types
def test_sequence_boolean(seq):
expected = [True, None, False, None]
arr = pa.array(seq(expected))
assert len(arr) == 4
assert arr.null_count == 2
assert arr.type == pa.bool_()
assert arr.to_pylist() == expected
@parametrize_with_sequence_types
def test_sequence_numpy_boolean(seq):
expected = [np.bool_(True), None, np.bool_(False), None]
arr = pa.array(seq(expected))
assert arr.type == pa.bool_()
assert arr.to_pylist() == [True, None, False, None]
@parametrize_with_sequence_types
def test_sequence_mixed_numpy_python_bools(seq):
values = np.array([True, False])
arr = pa.array(seq([values[0], None, values[1], True, False]))
assert arr.type == pa.bool_()
assert arr.to_pylist() == [True, None, False, True, False]
@parametrize_with_collections_types
def test_empty_list(seq):
arr = pa.array(seq([]))
assert len(arr) == 0
assert arr.null_count == 0
assert arr.type == pa.null()
assert arr.to_pylist() == []
@parametrize_with_sequence_types
def test_nested_lists(seq):
data = [[], [1, 2], None]
arr = pa.array(seq(data))
assert len(arr) == 3
assert arr.null_count == 1
assert arr.type == pa.list_(pa.int64())
assert arr.to_pylist() == data
# With explicit type
arr = pa.array(seq(data), type=pa.list_(pa.int32()))
assert len(arr) == 3
assert arr.null_count == 1
assert arr.type == pa.list_(pa.int32())
assert arr.to_pylist() == data
@parametrize_with_sequence_types
def test_nested_large_lists(seq):
data = [[], [1, 2], None]
arr = pa.array(seq(data), type=pa.large_list(pa.int16()))
assert len(arr) == 3
assert arr.null_count == 1
assert arr.type == pa.large_list(pa.int16())
assert arr.to_pylist() == data
@parametrize_with_collections_types
def test_list_with_non_list(seq):
# List types don't accept non-sequences
with pytest.raises(TypeError):
pa.array(seq([[], [1, 2], 3]), type=pa.list_(pa.int64()))
with pytest.raises(TypeError):
pa.array(seq([[], [1, 2], 3]), type=pa.large_list(pa.int64()))
@parametrize_with_sequence_types
def test_nested_arrays(seq):
arr = pa.array(seq([np.array([], dtype=np.int64),
np.array([1, 2], dtype=np.int64), None]))
assert len(arr) == 3
assert arr.null_count == 1
assert arr.type == pa.list_(pa.int64())
assert arr.to_pylist() == [[], [1, 2], None]
@parametrize_with_sequence_types
def test_nested_fixed_size_list(seq):
# sequence of lists
data = [[1, 2], [3, None], None]
arr = pa.array(seq(data), type=pa.list_(pa.int64(), 2))
assert len(arr) == 3
assert arr.null_count == 1
assert arr.type == pa.list_(pa.int64(), 2)
assert arr.to_pylist() == data
# sequence of numpy arrays
data = [np.array([1, 2], dtype='int64'), np.array([3, 4], dtype='int64'),
None]
arr = pa.array(seq(data), type=pa.list_(pa.int64(), 2))
assert len(arr) == 3
assert arr.null_count == 1
assert arr.type == pa.list_(pa.int64(), 2)
assert arr.to_pylist() == [[1, 2], [3, 4], None]
# incorrect length of the lists or arrays
data = [[1, 2, 4], [3, None], None]
for data in [[[1, 2, 3]], [np.array([1, 2, 4], dtype='int64')]]:
with pytest.raises(
ValueError, match="Length of item not correct: expected 2"):
pa.array(seq(data), type=pa.list_(pa.int64(), 2))
# with list size of 0
data = [[], [], None]
arr = pa.array(seq(data), type=pa.list_(pa.int64(), 0))
assert len(arr) == 3
assert arr.null_count == 1
assert arr.type == pa.list_(pa.int64(), 0)
assert arr.to_pylist() == [[], [], None]
@parametrize_with_sequence_types
def test_sequence_all_none(seq):
arr = pa.array(seq([None, None]))
assert len(arr) == 2
assert arr.null_count == 2
assert arr.type == pa.null()
assert arr.to_pylist() == [None, None]
@parametrize_with_sequence_types
@pytest.mark.parametrize("np_scalar_pa_type", int_type_pairs)
def test_sequence_integer(seq, np_scalar_pa_type):
np_scalar, pa_type = np_scalar_pa_type
expected = [1, None, 3, None,
np.iinfo(np_scalar).min, np.iinfo(np_scalar).max]
arr = pa.array(seq(expected), type=pa_type)
assert len(arr) == 6
assert arr.null_count == 2
assert arr.type == pa_type
assert arr.to_pylist() == expected
@parametrize_with_collections_types
@pytest.mark.parametrize("np_scalar_pa_type", int_type_pairs)
def test_sequence_integer_np_nan(seq, np_scalar_pa_type):
# ARROW-2806: numpy.nan is a double value and thus should produce
# a double array.
_, pa_type = np_scalar_pa_type
with pytest.raises(ValueError):
pa.array(seq([np.nan]), type=pa_type, from_pandas=False)
arr = pa.array(seq([np.nan]), type=pa_type, from_pandas=True)
expected = [None]
assert len(arr) == 1
assert arr.null_count == 1
assert arr.type == pa_type
assert arr.to_pylist() == expected
@parametrize_with_sequence_types
@pytest.mark.parametrize("np_scalar_pa_type", int_type_pairs)
def test_sequence_integer_nested_np_nan(seq, np_scalar_pa_type):
# ARROW-2806: numpy.nan is a double value and thus should produce
# a double array.
_, pa_type = np_scalar_pa_type
with pytest.raises(ValueError):
pa.array(seq([[np.nan]]), type=pa.list_(pa_type), from_pandas=False)
arr = pa.array(seq([[np.nan]]), type=pa.list_(pa_type), from_pandas=True)
expected = [[None]]
assert len(arr) == 1
assert arr.null_count == 0
assert arr.type == pa.list_(pa_type)
assert arr.to_pylist() == expected
@parametrize_with_sequence_types
def test_sequence_integer_inferred(seq):
expected = [1, None, 3, None]
arr = pa.array(seq(expected))
assert len(arr) == 4
assert arr.null_count == 2
assert arr.type == pa.int64()
assert arr.to_pylist() == expected
@parametrize_with_sequence_types
@pytest.mark.parametrize("np_scalar_pa_type", int_type_pairs)
def test_sequence_numpy_integer(seq, np_scalar_pa_type):
np_scalar, pa_type = np_scalar_pa_type
expected = [np_scalar(1), None, np_scalar(3), None,
np_scalar(np.iinfo(np_scalar).min),
np_scalar(np.iinfo(np_scalar).max)]
arr = pa.array(seq(expected), type=pa_type)
assert len(arr) == 6
assert arr.null_count == 2
assert arr.type == pa_type
assert arr.to_pylist() == expected
@parametrize_with_sequence_types
@pytest.mark.parametrize("np_scalar_pa_type", int_type_pairs)
def test_sequence_numpy_integer_inferred(seq, np_scalar_pa_type):
np_scalar, pa_type = np_scalar_pa_type
expected = [np_scalar(1), None, np_scalar(3), None]
expected += [np_scalar(np.iinfo(np_scalar).min),
np_scalar(np.iinfo(np_scalar).max)]
arr = pa.array(seq(expected))
assert len(arr) == 6
assert arr.null_count == 2
assert arr.type == pa_type
assert arr.to_pylist() == expected
@parametrize_with_sequence_types
def test_sequence_custom_integers(seq):
expected = [0, 42, 2**33 + 1, -2**63]
data = list(map(MyInt, expected))
arr = pa.array(seq(data), type=pa.int64())
assert arr.to_pylist() == expected
@parametrize_with_collections_types
def test_broken_integers(seq):
data = [MyBrokenInt()]
with pytest.raises(pa.ArrowInvalid, match="tried to convert to int"):
pa.array(seq(data), type=pa.int64())
def test_numpy_scalars_mixed_type():
# ARROW-4324
data = [np.int32(10), np.float32(0.5)]
arr = pa.array(data)
expected = pa.array([10, 0.5], type="float64")
assert arr.equals(expected)
# ARROW-9490
data = [np.int8(10), np.float32(0.5)]
arr = pa.array(data)
expected = pa.array([10, 0.5], type="float32")
assert arr.equals(expected)
@pytest.mark.xfail(reason="Type inference for uint64 not implemented",
raises=OverflowError)
def test_uint64_max_convert():
data = [0, np.iinfo(np.uint64).max]
arr = pa.array(data, type=pa.uint64())
expected = pa.array(np.array(data, dtype='uint64'))
assert arr.equals(expected)
arr_inferred = pa.array(data)
assert arr_inferred.equals(expected)
@pytest.mark.parametrize("bits", [8, 16, 32, 64])
def test_signed_integer_overflow(bits):
ty = getattr(pa, "int%d" % bits)()
# XXX ideally would always raise OverflowError
with pytest.raises((OverflowError, pa.ArrowInvalid)):
pa.array([2 ** (bits - 1)], ty)
with pytest.raises((OverflowError, pa.ArrowInvalid)):
pa.array([-2 ** (bits - 1) - 1], ty)
@pytest.mark.parametrize("bits", [8, 16, 32, 64])
def test_unsigned_integer_overflow(bits):
ty = getattr(pa, "uint%d" % bits)()
# XXX ideally would always raise OverflowError
with pytest.raises((OverflowError, pa.ArrowInvalid)):
pa.array([2 ** bits], ty)
with pytest.raises((OverflowError, pa.ArrowInvalid)):
pa.array([-1], ty)
@parametrize_with_collections_types
@pytest.mark.parametrize("typ", pa_int_types)
def test_integer_from_string_error(seq, typ):
# ARROW-9451: pa.array(['1'], type=pa.uint32()) should not succeed
with pytest.raises(pa.ArrowInvalid):
pa.array(seq(['1']), type=typ)
def test_convert_with_mask():
data = [1, 2, 3, 4, 5]
mask = np.array([False, True, False, False, True])
result = pa.array(data, mask=mask)
expected = pa.array([1, None, 3, 4, None])
assert result.equals(expected)
# Mask wrong length
with pytest.raises(ValueError):
pa.array(data, mask=mask[1:])
def test_garbage_collection():
import gc
# Force the cyclic garbage collector to run
gc.collect()
bytes_before = pa.total_allocated_bytes()
pa.array([1, None, 3, None])
gc.collect()
assert pa.total_allocated_bytes() == bytes_before
def test_sequence_double():
data = [1.5, 1., None, 2.5, None, None]
arr = pa.array(data)
assert len(arr) == 6
assert arr.null_count == 3
assert arr.type == pa.float64()
assert arr.to_pylist() == data
def test_double_auto_coerce_from_integer():
# Done as part of ARROW-2814
data = [1.5, 1., None, 2.5, None, None]
arr = pa.array(data)
data2 = [1.5, 1, None, 2.5, None, None]
arr2 = pa.array(data2)
assert arr.equals(arr2)
data3 = [1, 1.5, None, 2.5, None, None]
arr3 = pa.array(data3)
data4 = [1., 1.5, None, 2.5, None, None]
arr4 = pa.array(data4)
assert arr3.equals(arr4)
def test_double_integer_coerce_representable_range():
valid_values = [1.5, 1, 2, None, 1 << 53, -(1 << 53)]
invalid_values = [1.5, 1, 2, None, (1 << 53) + 1]
invalid_values2 = [1.5, 1, 2, None, -((1 << 53) + 1)]
# it works
pa.array(valid_values)
# it fails
with pytest.raises(ValueError):
pa.array(invalid_values)
with pytest.raises(ValueError):
pa.array(invalid_values2)
def test_float32_integer_coerce_representable_range():
f32 = np.float32
valid_values = [f32(1.5), 1 << 24, -(1 << 24)]
invalid_values = [f32(1.5), (1 << 24) + 1]
invalid_values2 = [f32(1.5), -((1 << 24) + 1)]
# it works
pa.array(valid_values, type=pa.float32())
# it fails
with pytest.raises(ValueError):
pa.array(invalid_values, type=pa.float32())
with pytest.raises(ValueError):
pa.array(invalid_values2, type=pa.float32())
def test_mixed_sequence_errors():
with pytest.raises(ValueError, match="tried to convert to boolean"):
pa.array([True, 'foo'], type=pa.bool_())
with pytest.raises(ValueError, match="tried to convert to float32"):
pa.array([1.5, 'foo'], type=pa.float32())
with pytest.raises(ValueError, match="tried to convert to double"):
pa.array([1.5, 'foo'])
@parametrize_with_sequence_types
@pytest.mark.parametrize("np_scalar,pa_type", [
(np.float16, pa.float16()),
(np.float32, pa.float32()),
(np.float64, pa.float64())
])
@pytest.mark.parametrize("from_pandas", [True, False])
def test_sequence_numpy_double(seq, np_scalar, pa_type, from_pandas):
data = [np_scalar(1.5), np_scalar(1), None, np_scalar(2.5), None, np.nan]
arr = pa.array(seq(data), from_pandas=from_pandas)
assert len(arr) == 6
if from_pandas:
assert arr.null_count == 3
else:
assert arr.null_count == 2
if from_pandas:
# The NaN is skipped in type inference, otherwise it forces a
# float64 promotion
assert arr.type == pa_type
else:
assert arr.type == pa.float64()
assert arr.to_pylist()[:4] == data[:4]
if from_pandas:
assert arr.to_pylist()[5] is None
else:
assert np.isnan(arr.to_pylist()[5])
@pytest.mark.parametrize("from_pandas", [True, False])
@pytest.mark.parametrize("inner_seq", [np.array, list])
def test_ndarray_nested_numpy_double(from_pandas, inner_seq):
# ARROW-2806
data = np.array([
inner_seq([1., 2.]),
inner_seq([1., 2., 3.]),
inner_seq([np.nan]),
None
], dtype=object)
arr = pa.array(data, from_pandas=from_pandas)
assert len(arr) == 4
assert arr.null_count == 1
assert arr.type == pa.list_(pa.float64())
if from_pandas:
assert arr.to_pylist() == [[1.0, 2.0], [1.0, 2.0, 3.0], [None], None]
else:
np.testing.assert_equal(arr.to_pylist(),
[[1., 2.], [1., 2., 3.], [np.nan], None])
def test_nested_ndarray_in_object_array():
# ARROW-4350
arr = np.empty(2, dtype=object)
arr[:] = [np.array([1, 2], dtype=np.int64),
np.array([2, 3], dtype=np.int64)]
arr2 = np.empty(2, dtype=object)
arr2[0] = [3, 4]
arr2[1] = [5, 6]
expected_type = pa.list_(pa.list_(pa.int64()))
assert pa.infer_type([arr]) == expected_type
result = pa.array([arr, arr2])
expected = pa.array([[[1, 2], [2, 3]], [[3, 4], [5, 6]]],
type=expected_type)
assert result.equals(expected)
# test case for len-1 arrays to ensure they are interpreted as
# sublists and not scalars
arr = np.empty(2, dtype=object)
arr[:] = [np.array([1]), np.array([2])]
result = pa.array([arr, arr])
assert result.to_pylist() == [[[1], [2]], [[1], [2]]]
@pytest.mark.xfail(reason=("Type inference for multidimensional ndarray "
"not yet implemented"),
raises=AssertionError)
def test_multidimensional_ndarray_as_nested_list():
# TODO(wesm): see ARROW-5645
arr = np.array([[1, 2], [2, 3]], dtype=np.int64)
arr2 = np.array([[3, 4], [5, 6]], dtype=np.int64)
expected_type = pa.list_(pa.list_(pa.int64()))
assert pa.infer_type([arr]) == expected_type
result = pa.array([arr, arr2])
expected = pa.array([[[1, 2], [2, 3]], [[3, 4], [5, 6]]],
type=expected_type)
assert result.equals(expected)
@pytest.mark.parametrize(('data', 'value_type'), [
([True, False], pa.bool_()),
([None, None], pa.null()),
([1, 2, None], pa.int8()),
([1, 2., 3., None], pa.float32()),
([datetime.date.today(), None], pa.date32()),
([None, datetime.date.today()], pa.date64()),
([datetime.time(1, 1, 1), None], pa.time32('s')),
([None, datetime.time(2, 2, 2)], pa.time64('us')),
([datetime.datetime.now(), None], pa.timestamp('us')),
([datetime.timedelta(seconds=10)], pa.duration('s')),
([b"a", b"b"], pa.binary()),
([b"aaa", b"bbb", b"ccc"], pa.binary(3)),
([b"a", b"b", b"c"], pa.large_binary()),
(["a", "b", "c"], pa.string()),
(["a", "b", "c"], pa.large_string()),
(
[{"a": 1, "b": 2}, None, {"a": 5, "b": None}],
pa.struct([('a', pa.int8()), ('b', pa.int16())])
)
])
def test_list_array_from_object_ndarray(data, value_type):
ty = pa.list_(value_type)
ndarray = np.array(data, dtype=object)
arr = pa.array([ndarray], type=ty)
assert arr.type.equals(ty)
assert arr.to_pylist() == [data]
@pytest.mark.parametrize(('data', 'value_type'), [
([[1, 2], [3]], pa.list_(pa.int64())),
([[1, 2], [3, 4]], pa.list_(pa.int64(), 2)),
([[1], [2, 3]], pa.large_list(pa.int64()))
])
def test_nested_list_array_from_object_ndarray(data, value_type):
ndarray = np.empty(len(data), dtype=object)
ndarray[:] = [np.array(item, dtype=object) for item in data]
ty = pa.list_(value_type)
arr = pa.array([ndarray], type=ty)
assert arr.type.equals(ty)
assert arr.to_pylist() == [data]
def test_array_ignore_nan_from_pandas():
# See ARROW-4324, this reverts logic that was introduced in
# ARROW-2240
with pytest.raises(ValueError):
pa.array([np.nan, 'str'])
arr = pa.array([np.nan, 'str'], from_pandas=True)
expected = pa.array([None, 'str'])
assert arr.equals(expected)
def test_nested_ndarray_different_dtypes():
data = [
np.array([1, 2, 3], dtype='int64'),
None,
np.array([4, 5, 6], dtype='uint32')
]
arr = pa.array(data)
expected = pa.array([[1, 2, 3], None, [4, 5, 6]],
type=pa.list_(pa.int64()))
assert arr.equals(expected)
t2 = pa.list_(pa.uint32())
arr2 = pa.array(data, type=t2)
expected2 = expected.cast(t2)
assert arr2.equals(expected2)
def test_sequence_unicode():
data = ['foo', 'bar', None, 'mañana']
arr = pa.array(data)
assert len(arr) == 4
assert arr.null_count == 1
assert arr.type == pa.string()
assert arr.to_pylist() == data
def check_array_mixed_unicode_bytes(binary_type, string_type):
values = ['qux', b'foo', bytearray(b'barz')]
b_values = [b'qux', b'foo', b'barz']
u_values = ['qux', 'foo', 'barz']
arr = pa.array(values)
expected = pa.array(b_values, type=pa.binary())
assert arr.type == pa.binary()
assert arr.equals(expected)
arr = pa.array(values, type=binary_type)
expected = pa.array(b_values, type=binary_type)
assert arr.type == binary_type
assert arr.equals(expected)
arr = pa.array(values, type=string_type)
expected = pa.array(u_values, type=string_type)
assert arr.type == string_type
assert arr.equals(expected)
def test_array_mixed_unicode_bytes():
check_array_mixed_unicode_bytes(pa.binary(), pa.string())
check_array_mixed_unicode_bytes(pa.large_binary(), pa.large_string())
@pytest.mark.large_memory
@pytest.mark.parametrize("ty", [pa.large_binary(), pa.large_string()])
def test_large_binary_array(ty):
# Construct a large binary array with more than 4GB of data
s = b"0123456789abcdefghijklmnopqrstuvwxyz" * 10
nrepeats = math.ceil((2**32 + 5) / len(s))
data = [s] * nrepeats
arr = pa.array(data, type=ty)
assert isinstance(arr, pa.Array)
assert arr.type == ty
assert len(arr) == nrepeats
@pytest.mark.slow
@pytest.mark.large_memory
@pytest.mark.parametrize("ty", [pa.large_binary(), pa.large_string()])
def test_large_binary_value(ty):
# Construct a large binary array with a single value larger than 4GB
s = b"0123456789abcdefghijklmnopqrstuvwxyz"
nrepeats = math.ceil((2**32 + 5) / len(s))
arr = pa.array([b"foo", s * nrepeats, None, b"bar"], type=ty)
assert isinstance(arr, pa.Array)
assert arr.type == ty
assert len(arr) == 4
buf = arr[1].as_buffer()
assert len(buf) == len(s) * nrepeats
@pytest.mark.large_memory
@pytest.mark.parametrize("ty", [pa.binary(), pa.string()])
def test_string_too_large(ty):
# Construct a binary array with a single value larger than 4GB
s = b"0123456789abcdefghijklmnopqrstuvwxyz"
nrepeats = math.ceil((2**32 + 5) / len(s))
with pytest.raises(pa.ArrowCapacityError):
pa.array([b"foo", s * nrepeats, None, b"bar"], type=ty)
def test_sequence_bytes():
u1 = b'ma\xc3\xb1ana'
data = [b'foo',
memoryview(b'dada'),
memoryview(b'd-a-t-a')[::2], # non-contiguous is made contiguous
u1.decode('utf-8'), # unicode gets encoded,
bytearray(b'bar'),
None]
for ty in [None, pa.binary(), pa.large_binary()]:
arr = pa.array(data, type=ty)
assert len(arr) == 6
assert arr.null_count == 1
assert arr.type == ty or pa.binary()
assert arr.to_pylist() == [b'foo', b'dada', b'data', u1, b'bar', None]
@pytest.mark.parametrize("ty", [pa.string(), pa.large_string()])
def test_sequence_utf8_to_unicode(ty):
# ARROW-1225
data = [b'foo', None, b'bar']
arr = pa.array(data, type=ty)
assert arr.type == ty
assert arr[0].as_py() == 'foo'
# test a non-utf8 unicode string
val = ('mañana').encode('utf-16-le')
with pytest.raises(pa.ArrowInvalid):
pa.array([val], type=ty)
def test_sequence_fixed_size_bytes():
data = [b'foof', None, bytearray(b'barb'), b'2346']
arr = pa.array(data, type=pa.binary(4))
assert len(arr) == 4
assert arr.null_count == 1
assert arr.type == pa.binary(4)
assert arr.to_pylist() == [b'foof', None, b'barb', b'2346']
def test_fixed_size_bytes_does_not_accept_varying_lengths():
data = [b'foo', None, b'barb', b'2346']
with pytest.raises(pa.ArrowInvalid):
pa.array(data, type=pa.binary(4))
def test_fixed_size_binary_length_check():
# ARROW-10193
data = [b'\x19h\r\x9e\x00\x00\x00\x00\x01\x9b\x9fA']
assert len(data[0]) == 12
ty = pa.binary(12)
arr = pa.array(data, type=ty)
assert arr.to_pylist() == data
def test_sequence_date():
data = [datetime.date(2000, 1, 1), None, datetime.date(1970, 1, 1),
datetime.date(2040, 2, 26)]
arr = pa.array(data)
assert len(arr) == 4
assert arr.type == pa.date32()
assert arr.null_count == 1
assert arr[0].as_py() == datetime.date(2000, 1, 1)
assert arr[1].as_py() is None
assert arr[2].as_py() == datetime.date(1970, 1, 1)
assert arr[3].as_py() == datetime.date(2040, 2, 26)
@pytest.mark.parametrize('input',
[(pa.date32(), [10957, None]),
(pa.date64(), [10957 * 86400000, None])])
def test_sequence_explicit_types(input):
t, ex_values = input
data = [datetime.date(2000, 1, 1), None]
arr = pa.array(data, type=t)
arr2 = pa.array(ex_values, type=t)
for x in [arr, arr2]:
assert len(x) == 2
assert x.type == t
assert x.null_count == 1
assert x[0].as_py() == datetime.date(2000, 1, 1)
assert x[1].as_py() is None
def test_date32_overflow():
# Overflow
data3 = [2**32, None]
with pytest.raises((OverflowError, pa.ArrowException)):
pa.array(data3, type=pa.date32())
@pytest.mark.parametrize(('time_type', 'unit', 'int_type'), [
(pa.time32, 's', 'int32'),
(pa.time32, 'ms', 'int32'),
(pa.time64, 'us', 'int64'),
(pa.time64, 'ns', 'int64'),
])
def test_sequence_time_with_timezone(time_type, unit, int_type):
def expected_integer_value(t):
# only use with utc time object because it doesn't adjust with the
# offset
units = ['s', 'ms', 'us', 'ns']
multiplier = 10**(units.index(unit) * 3)
if t is None:
return None
seconds = (
t.hour * 3600 +
t.minute * 60 +
t.second +
t.microsecond * 10**-6
)
return int(seconds * multiplier)
def expected_time_value(t):
# only use with utc time object because it doesn't adjust with the
# time objects tzdata
if unit == 's':
return t.replace(microsecond=0)
elif unit == 'ms':
return t.replace(microsecond=(t.microsecond // 1000) * 1000)
else:
return t
# only timezone naive times are supported in arrow
data = [
datetime.time(8, 23, 34, 123456),
datetime.time(5, 0, 0, 1000),
None,
datetime.time(1, 11, 56, 432539),
datetime.time(23, 10, 0, 437699)
]
ty = time_type(unit)
arr = pa.array(data, type=ty)
assert len(arr) == 5
assert arr.type == ty
assert arr.null_count == 1
# test that the underlying integers are UTC values
values = arr.cast(int_type)
expected = list(map(expected_integer_value, data))
assert values.to_pylist() == expected
# test that the scalars are datetime.time objects with UTC timezone
assert arr[0].as_py() == expected_time_value(data[0])
assert arr[1].as_py() == expected_time_value(data[1])
assert arr[2].as_py() is None
assert arr[3].as_py() == expected_time_value(data[3])
assert arr[4].as_py() == expected_time_value(data[4])
def tz(hours, minutes=0):
offset = datetime.timedelta(hours=hours, minutes=minutes)
return datetime.timezone(offset)
def test_sequence_timestamp():
data = [
datetime.datetime(2007, 7, 13, 1, 23, 34, 123456),
None,
datetime.datetime(2006, 1, 13, 12, 34, 56, 432539),
datetime.datetime(2010, 8, 13, 5, 46, 57, 437699)
]
arr = pa.array(data)
assert len(arr) == 4
assert arr.type == pa.timestamp('us')
assert arr.null_count == 1
assert arr[0].as_py() == datetime.datetime(2007, 7, 13, 1,
23, 34, 123456)
assert arr[1].as_py() is None
assert arr[2].as_py() == datetime.datetime(2006, 1, 13, 12,
34, 56, 432539)
assert arr[3].as_py() == datetime.datetime(2010, 8, 13, 5,