Repository navigation
Expand file tree
/
Copy pathtest_types.py
More file actions
1197 lines (931 loc) · 35.1 KB
/
Copy pathtest_types.py
File metadata and controls
1197 lines (931 loc) · 35.1 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.
from collections import OrderedDict
from collections.abc import Iterator
from functools import partial
import datetime
import sys
import pickle
import pytest
import hypothesis as h
import hypothesis.strategies as st
try:
import hypothesis.extra.pytz as tzst
except ImportError:
tzst = None
import weakref
import numpy as np
import pyarrow as pa
import pyarrow.types as types
import pyarrow.tests.strategies as past
def get_many_types():
# returning them from a function is required because of pa.dictionary
# type holds a pyarrow array and test_array.py::test_toal_bytes_allocated
# checks that the default memory pool has zero allocated bytes
return (
pa.null(),
pa.bool_(),
pa.int32(),
pa.time32('s'),
pa.time64('us'),
pa.date32(),
pa.timestamp('us'),
pa.timestamp('us', tz='UTC'),
pa.timestamp('us', tz='Europe/Paris'),
pa.duration('s'),
pa.float16(),
pa.float32(),
pa.float64(),
pa.decimal128(19, 4),
pa.decimal256(76, 38),
pa.string(),
pa.binary(),
pa.binary(10),
pa.large_string(),
pa.large_binary(),
pa.list_(pa.int32()),
pa.list_(pa.int32(), 2),
pa.large_list(pa.uint16()),
pa.map_(pa.string(), pa.int32()),
pa.map_(pa.field('key', pa.int32(), nullable=False),
pa.field('value', pa.int32())),
pa.struct([pa.field('a', pa.int32()),
pa.field('b', pa.int8()),
pa.field('c', pa.string())]),
pa.struct([pa.field('a', pa.int32(), nullable=False),
pa.field('b', pa.int8(), nullable=False),
pa.field('c', pa.string())]),
pa.union([pa.field('a', pa.binary(10)),
pa.field('b', pa.string())], mode=pa.lib.UnionMode_DENSE),
pa.union([pa.field('a', pa.binary(10)),
pa.field('b', pa.string())], mode=pa.lib.UnionMode_DENSE,
type_codes=[4, 8]),
pa.union([pa.field('a', pa.binary(10)),
pa.field('b', pa.string())], mode=pa.lib.UnionMode_SPARSE),
pa.union([pa.field('a', pa.binary(10), nullable=False),
pa.field('b', pa.string())], mode=pa.lib.UnionMode_SPARSE),
pa.dictionary(pa.int32(), pa.string())
)
def test_is_boolean():
assert types.is_boolean(pa.bool_())
assert not types.is_boolean(pa.int8())
def test_is_integer():
signed_ints = [pa.int8(), pa.int16(), pa.int32(), pa.int64()]
unsigned_ints = [pa.uint8(), pa.uint16(), pa.uint32(), pa.uint64()]
for t in signed_ints + unsigned_ints:
assert types.is_integer(t)
for t in signed_ints:
assert types.is_signed_integer(t)
assert not types.is_unsigned_integer(t)
for t in unsigned_ints:
assert types.is_unsigned_integer(t)
assert not types.is_signed_integer(t)
assert not types.is_integer(pa.float32())
assert not types.is_signed_integer(pa.float32())
def test_is_floating():
for t in [pa.float16(), pa.float32(), pa.float64()]:
assert types.is_floating(t)
assert not types.is_floating(pa.int32())
def test_is_null():
assert types.is_null(pa.null())
assert not types.is_null(pa.list_(pa.int32()))
def test_null_field_may_not_be_non_nullable():
# ARROW-7273
with pytest.raises(ValueError):
pa.field('f0', pa.null(), nullable=False)
def test_is_decimal():
decimal128 = pa.decimal128(19, 4)
decimal256 = pa.decimal256(76, 38)
int32 = pa.int32()
assert types.is_decimal(decimal128)
assert types.is_decimal(decimal256)
assert not types.is_decimal(int32)
assert types.is_decimal128(decimal128)
assert not types.is_decimal128(decimal256)
assert not types.is_decimal128(int32)
assert not types.is_decimal256(decimal128)
assert types.is_decimal256(decimal256)
assert not types.is_decimal256(int32)
def test_is_list():
a = pa.list_(pa.int32())
b = pa.large_list(pa.int32())
c = pa.list_(pa.int32(), 3)
assert types.is_list(a)
assert not types.is_large_list(a)
assert not types.is_fixed_size_list(a)
assert types.is_large_list(b)
assert not types.is_list(b)
assert not types.is_fixed_size_list(b)
assert types.is_fixed_size_list(c)
assert not types.is_list(c)
assert not types.is_large_list(c)
assert not types.is_list(pa.int32())
def test_is_map():
m = pa.map_(pa.utf8(), pa.int32())
assert types.is_map(m)
assert not types.is_map(pa.int32())
fields = pa.map_(pa.field('key_name', pa.utf8(), nullable=False),
pa.field('value_name', pa.int32()))
assert types.is_map(fields)
entries_type = pa.struct([pa.field('key', pa.int8()),
pa.field('value', pa.int8())])
list_type = pa.list_(entries_type)
assert not types.is_map(list_type)
def test_is_dictionary():
assert types.is_dictionary(pa.dictionary(pa.int32(), pa.string()))
assert not types.is_dictionary(pa.int32())
def test_is_nested_or_struct():
struct_ex = pa.struct([pa.field('a', pa.int32()),
pa.field('b', pa.int8()),
pa.field('c', pa.string())])
assert types.is_struct(struct_ex)
assert not types.is_struct(pa.list_(pa.int32()))
assert types.is_nested(struct_ex)
assert types.is_nested(pa.list_(pa.int32()))
assert types.is_nested(pa.large_list(pa.int32()))
assert not types.is_nested(pa.int32())
def test_is_union():
for mode in [pa.lib.UnionMode_SPARSE, pa.lib.UnionMode_DENSE]:
assert types.is_union(pa.union([pa.field('a', pa.int32()),
pa.field('b', pa.int8()),
pa.field('c', pa.string())],
mode=mode))
assert not types.is_union(pa.list_(pa.int32()))
# TODO(wesm): is_map, once implemented
def test_is_binary_string():
assert types.is_binary(pa.binary())
assert not types.is_binary(pa.string())
assert not types.is_binary(pa.large_binary())
assert not types.is_binary(pa.large_string())
assert types.is_string(pa.string())
assert types.is_unicode(pa.string())
assert not types.is_string(pa.binary())
assert not types.is_string(pa.large_string())
assert not types.is_string(pa.large_binary())
assert types.is_large_binary(pa.large_binary())
assert not types.is_large_binary(pa.large_string())
assert not types.is_large_binary(pa.binary())
assert not types.is_large_binary(pa.string())
assert types.is_large_string(pa.large_string())
assert not types.is_large_string(pa.large_binary())
assert not types.is_large_string(pa.string())
assert not types.is_large_string(pa.binary())
assert types.is_fixed_size_binary(pa.binary(5))
assert not types.is_fixed_size_binary(pa.binary())
def test_is_temporal_date_time_timestamp():
date_types = [pa.date32(), pa.date64()]
time_types = [pa.time32('s'), pa.time64('ns')]
timestamp_types = [pa.timestamp('ms')]
duration_types = [pa.duration('ms')]
interval_types = [pa.month_day_nano_interval()]
for case in (date_types + time_types + timestamp_types + duration_types +
interval_types):
assert types.is_temporal(case)
for case in date_types:
assert types.is_date(case)
assert not types.is_time(case)
assert not types.is_timestamp(case)
assert not types.is_duration(case)
assert not types.is_interval(case)
for case in time_types:
assert types.is_time(case)
assert not types.is_date(case)
assert not types.is_timestamp(case)
assert not types.is_duration(case)
assert not types.is_interval(case)
for case in timestamp_types:
assert types.is_timestamp(case)
assert not types.is_date(case)
assert not types.is_time(case)
assert not types.is_duration(case)
assert not types.is_interval(case)
for case in duration_types:
assert types.is_duration(case)
assert not types.is_date(case)
assert not types.is_time(case)
assert not types.is_timestamp(case)
assert not types.is_interval(case)
for case in interval_types:
assert types.is_interval(case)
assert not types.is_date(case)
assert not types.is_time(case)
assert not types.is_timestamp(case)
assert not types.is_temporal(pa.int32())
def test_is_primitive():
assert types.is_primitive(pa.int32())
assert not types.is_primitive(pa.list_(pa.int32()))
@pytest.mark.parametrize(('tz', 'expected'), [
(datetime.timezone.utc, 'UTC'),
(datetime.timezone(datetime.timedelta(hours=1, minutes=30)), '+01:30')
])
def test_tzinfo_to_string(tz, expected):
assert pa.lib.tzinfo_to_string(tz) == expected
def test_pytz_tzinfo_to_string():
pytz = pytest.importorskip("pytz")
tz = [pytz.utc, pytz.timezone('Europe/Paris')]
expected = ['UTC', 'Europe/Paris']
assert [pa.lib.tzinfo_to_string(i) for i in tz] == expected
# StaticTzInfo.tzname returns with '-09' so we need to infer the timezone's
# name from the tzinfo.zone attribute
tz = [pytz.timezone('Etc/GMT-9'), pytz.FixedOffset(180)]
expected = ['Etc/GMT-9', '+03:00']
assert [pa.lib.tzinfo_to_string(i) for i in tz] == expected
def test_dateutil_tzinfo_to_string():
pytest.importorskip("dateutil")
import dateutil.tz
tz = dateutil.tz.UTC
assert pa.lib.tzinfo_to_string(tz) == 'UTC'
tz = dateutil.tz.gettz('Europe/Paris')
assert pa.lib.tzinfo_to_string(tz) == 'Europe/Paris'
def test_zoneinfo_tzinfo_to_string():
zoneinfo = pytest.importorskip('zoneinfo')
if sys.platform == 'win32':
# zoneinfo requires an additional dependency On Windows
# tzdata provides IANA time zone data
pytest.importorskip('tzdata')
tz = zoneinfo.ZoneInfo('UTC')
assert pa.lib.tzinfo_to_string(tz) == 'UTC'
tz = zoneinfo.ZoneInfo('Europe/Paris')
assert pa.lib.tzinfo_to_string(tz) == 'Europe/Paris'
def test_tzinfo_to_string_errors():
msg = "Not an instance of datetime.tzinfo"
with pytest.raises(TypeError):
pa.lib.tzinfo_to_string("Europe/Budapest")
if sys.version_info >= (3, 8):
# before 3.8 it was only possible to create timezone objects with whole
# number of minutes
tz = datetime.timezone(datetime.timedelta(hours=1, seconds=30))
msg = "Offset must represent whole number of minutes"
with pytest.raises(ValueError, match=msg):
pa.lib.tzinfo_to_string(tz)
if tzst:
timezones = tzst.timezones()
else:
timezones = st.none()
@h.given(timezones)
def test_pytz_timezone_roundtrip(tz):
if tz is None:
pytest.skip('requires timezone not None')
timezone_string = pa.lib.tzinfo_to_string(tz)
timezone_tzinfo = pa.lib.string_to_tzinfo(timezone_string)
assert timezone_tzinfo == tz
def test_convert_custom_tzinfo_objects_to_string():
class CorrectTimezone1(datetime.tzinfo):
"""
Conversion is using utcoffset()
"""
def tzname(self, dt):
return None
def utcoffset(self, dt):
return datetime.timedelta(hours=-3, minutes=30)
class CorrectTimezone2(datetime.tzinfo):
"""
Conversion is using tzname()
"""
def tzname(self, dt):
return "+03:00"
def utcoffset(self, dt):
return datetime.timedelta(hours=3)
class BuggyTimezone1(datetime.tzinfo):
"""
Unable to infer name or offset
"""
def tzname(self, dt):
return None
def utcoffset(self, dt):
return None
class BuggyTimezone2(datetime.tzinfo):
"""
Wrong offset type
"""
def tzname(self, dt):
return None
def utcoffset(self, dt):
return "one hour"
class BuggyTimezone3(datetime.tzinfo):
"""
Wrong timezone name type
"""
def tzname(self, dt):
return 240
def utcoffset(self, dt):
return None
assert pa.lib.tzinfo_to_string(CorrectTimezone1()) == "-02:30"
assert pa.lib.tzinfo_to_string(CorrectTimezone2()) == "+03:00"
msg = (r"Object returned by tzinfo.utcoffset\(None\) is not an instance "
r"of datetime.timedelta")
for wrong in [BuggyTimezone1(), BuggyTimezone2(), BuggyTimezone3()]:
with pytest.raises(ValueError, match=msg):
pa.lib.tzinfo_to_string(wrong)
def test_string_to_tzinfo():
string = ['UTC', 'Europe/Paris', '+03:00', '+01:30', '-02:00']
try:
import pytz
expected = [pytz.utc, pytz.timezone('Europe/Paris'),
pytz.FixedOffset(180), pytz.FixedOffset(90),
pytz.FixedOffset(-120)]
result = [pa.lib.string_to_tzinfo(i) for i in string]
assert result == expected
except ImportError:
try:
import zoneinfo
expected = [zoneinfo.ZoneInfo(key='UTC'),
zoneinfo.ZoneInfo(key='Europe/Paris'),
datetime.timezone(datetime.timedelta(hours=3)),
datetime.timezone(
datetime.timedelta(hours=1, minutes=30)),
datetime.timezone(-datetime.timedelta(hours=2))]
result = [pa.lib.string_to_tzinfo(i) for i in string]
assert result == expected
except ImportError:
pytest.skip('requires pytz or zoneinfo to be installed')
def test_timezone_string_roundtrip_pytz():
pytz = pytest.importorskip("pytz")
tz = [pytz.FixedOffset(90), pytz.FixedOffset(-90),
pytz.utc, pytz.timezone('America/New_York')]
name = ['+01:30', '-01:30', 'UTC', 'America/New_York']
assert [pa.lib.tzinfo_to_string(i) for i in tz] == name
assert [pa.lib.string_to_tzinfo(i)for i in name] == tz
def test_timestamp():
for unit in ('s', 'ms', 'us', 'ns'):
for tz in (None, 'UTC', 'Europe/Paris'):
ty = pa.timestamp(unit, tz=tz)
assert ty.unit == unit
assert ty.tz == tz
for invalid_unit in ('m', 'arbit', 'rary'):
with pytest.raises(ValueError, match='Invalid time unit'):
pa.timestamp(invalid_unit)
def test_time32_units():
for valid_unit in ('s', 'ms'):
ty = pa.time32(valid_unit)
assert ty.unit == valid_unit
for invalid_unit in ('m', 'us', 'ns'):
error_msg = 'Invalid time unit for time32: {!r}'.format(invalid_unit)
with pytest.raises(ValueError, match=error_msg):
pa.time32(invalid_unit)
def test_time64_units():
for valid_unit in ('us', 'ns'):
ty = pa.time64(valid_unit)
assert ty.unit == valid_unit
for invalid_unit in ('m', 's', 'ms'):
error_msg = 'Invalid time unit for time64: {!r}'.format(invalid_unit)
with pytest.raises(ValueError, match=error_msg):
pa.time64(invalid_unit)
def test_duration():
for unit in ('s', 'ms', 'us', 'ns'):
ty = pa.duration(unit)
assert ty.unit == unit
for invalid_unit in ('m', 'arbit', 'rary'):
with pytest.raises(ValueError, match='Invalid time unit'):
pa.duration(invalid_unit)
def test_list_type():
ty = pa.list_(pa.int64())
assert isinstance(ty, pa.ListType)
assert ty.value_type == pa.int64()
assert ty.value_field == pa.field("item", pa.int64(), nullable=True)
# nullability matters in comparison
ty_non_nullable = pa.list_(pa.field("item", pa.int64(), nullable=False))
assert ty != ty_non_nullable
# field names don't matter by default
ty_named = pa.list_(pa.field("element", pa.int64()))
assert ty == ty_named
assert not ty.equals(ty_named, check_metadata=True)
# metadata doesn't matter by default
ty_metadata = pa.list_(
pa.field("item", pa.int64(), metadata={"hello": "world"}))
assert ty == ty_metadata
assert not ty.equals(ty_metadata, check_metadata=True)
with pytest.raises(TypeError):
pa.list_(None)
def test_large_list_type():
ty = pa.large_list(pa.utf8())
assert isinstance(ty, pa.LargeListType)
assert ty.value_type == pa.utf8()
assert ty.value_field == pa.field("item", pa.utf8(), nullable=True)
with pytest.raises(TypeError):
pa.large_list(None)
def test_map_type():
ty = pa.map_(pa.utf8(), pa.int32())
assert isinstance(ty, pa.MapType)
assert ty.key_type == pa.utf8()
assert ty.key_field == pa.field("key", pa.utf8(), nullable=False)
assert ty.item_type == pa.int32()
assert ty.item_field == pa.field("value", pa.int32(), nullable=True)
# nullability matters in comparison
ty_non_nullable = pa.map_(pa.utf8(), pa.field(
"value", pa.int32(), nullable=False))
assert ty != ty_non_nullable
# field names don't matter by default
ty_named = pa.map_(pa.field("x", pa.utf8(), nullable=False),
pa.field("y", pa.int32()))
assert ty == ty_named
assert not ty.equals(ty_named, check_metadata=True)
# metadata doesn't matter by default
ty_metadata = pa.map_(pa.utf8(), pa.field(
"value", pa.int32(), metadata={"hello": "world"}))
assert ty == ty_metadata
assert not ty.equals(ty_metadata, check_metadata=True)
with pytest.raises(TypeError):
pa.map_(None)
with pytest.raises(TypeError):
pa.map_(pa.int32(), None)
with pytest.raises(TypeError):
pa.map_(pa.field("name", pa.string(), nullable=True), pa.int64())
def test_fixed_size_list_type():
ty = pa.list_(pa.float64(), 2)
assert isinstance(ty, pa.FixedSizeListType)
assert ty.value_type == pa.float64()
assert ty.value_field == pa.field("item", pa.float64(), nullable=True)
assert ty.list_size == 2
with pytest.raises(ValueError):
pa.list_(pa.float64(), -2)
def test_struct_type():
fields = [
# Duplicate field name on purpose
pa.field('a', pa.int64()),
pa.field('a', pa.int32()),
pa.field('b', pa.int32())
]
ty = pa.struct(fields)
assert len(ty) == ty.num_fields == 3
assert list(ty) == fields
assert ty[0].name == 'a'
assert ty[2].type == pa.int32()
with pytest.raises(IndexError):
assert ty[3]
assert ty['b'] == ty[2]
assert ty['b'] == ty.field('b')
assert ty[2] == ty.field(2)
# Not found
with pytest.raises(KeyError):
ty['c']
with pytest.raises(KeyError):
ty.field('c')
# Neither integer nor string
with pytest.raises(TypeError):
ty[None]
with pytest.raises(TypeError):
ty.field(None)
for a, b in zip(ty, fields):
a == b
# Construct from list of tuples
ty = pa.struct([('a', pa.int64()),
('a', pa.int32()),
('b', pa.int32())])
assert list(ty) == fields
for a, b in zip(ty, fields):
a == b
# Construct from mapping
fields = [pa.field('a', pa.int64()),
pa.field('b', pa.int32())]
ty = pa.struct(OrderedDict([('a', pa.int64()),
('b', pa.int32())]))
assert list(ty) == fields
for a, b in zip(ty, fields):
a == b
# Invalid args
with pytest.raises(TypeError):
pa.struct([('a', None)])
def test_struct_duplicate_field_names():
fields = [
pa.field('a', pa.int64()),
pa.field('b', pa.int32()),
pa.field('a', pa.int32())
]
ty = pa.struct(fields)
# Duplicate
with pytest.warns(UserWarning):
with pytest.raises(KeyError):
ty['a']
# StructType::GetFieldIndex
assert ty.get_field_index('a') == -1
# StructType::GetAllFieldIndices
assert ty.get_all_field_indices('a') == [0, 2]
def test_union_type():
def check_fields(ty, fields):
assert ty.num_fields == len(fields)
assert [ty[i] for i in range(ty.num_fields)] == fields
assert [ty.field(i) for i in range(ty.num_fields)] == fields
fields = [pa.field('x', pa.list_(pa.int32())),
pa.field('y', pa.binary())]
type_codes = [5, 9]
sparse_factories = [
partial(pa.union, mode='sparse'),
partial(pa.union, mode=pa.lib.UnionMode_SPARSE),
pa.sparse_union,
]
dense_factories = [
partial(pa.union, mode='dense'),
partial(pa.union, mode=pa.lib.UnionMode_DENSE),
pa.dense_union,
]
for factory in sparse_factories:
ty = factory(fields)
assert isinstance(ty, pa.SparseUnionType)
assert ty.mode == 'sparse'
check_fields(ty, fields)
assert ty.type_codes == [0, 1]
ty = factory(fields, type_codes=type_codes)
assert ty.mode == 'sparse'
check_fields(ty, fields)
assert ty.type_codes == type_codes
# Invalid number of type codes
with pytest.raises(ValueError):
factory(fields, type_codes=type_codes[1:])
for factory in dense_factories:
ty = factory(fields)
assert isinstance(ty, pa.DenseUnionType)
assert ty.mode == 'dense'
check_fields(ty, fields)
assert ty.type_codes == [0, 1]
ty = factory(fields, type_codes=type_codes)
assert ty.mode == 'dense'
check_fields(ty, fields)
assert ty.type_codes == type_codes
# Invalid number of type codes
with pytest.raises(ValueError):
factory(fields, type_codes=type_codes[1:])
for mode in ('unknown', 2):
with pytest.raises(ValueError, match='Invalid union mode'):
pa.union(fields, mode=mode)
def test_dictionary_type():
ty0 = pa.dictionary(pa.int32(), pa.string())
assert ty0.index_type == pa.int32()
assert ty0.value_type == pa.string()
assert ty0.ordered is False
ty1 = pa.dictionary(pa.int8(), pa.float64(), ordered=True)
assert ty1.index_type == pa.int8()
assert ty1.value_type == pa.float64()
assert ty1.ordered is True
# construct from non-arrow objects
ty2 = pa.dictionary('int8', 'string')
assert ty2.index_type == pa.int8()
assert ty2.value_type == pa.string()
assert ty2.ordered is False
# allow unsigned integers for index type
ty3 = pa.dictionary(pa.uint32(), pa.string())
assert ty3.index_type == pa.uint32()
assert ty3.value_type == pa.string()
assert ty3.ordered is False
# invalid index type raises
with pytest.raises(TypeError):
pa.dictionary(pa.string(), pa.int64())
def test_dictionary_ordered_equals():
# Python side checking of ARROW-6345
d1 = pa.dictionary('int32', 'binary', ordered=True)
d2 = pa.dictionary('int32', 'binary', ordered=False)
d3 = pa.dictionary('int8', 'binary', ordered=True)
d4 = pa.dictionary('int32', 'binary', ordered=True)
assert not d1.equals(d2)
assert not d1.equals(d3)
assert d1.equals(d4)
def test_types_hashable():
many_types = get_many_types()
in_dict = {}
for i, type_ in enumerate(many_types):
assert hash(type_) == hash(type_)
in_dict[type_] = i
assert len(in_dict) == len(many_types)
for i, type_ in enumerate(many_types):
assert in_dict[type_] == i
def test_types_picklable():
for ty in get_many_types():
data = pickle.dumps(ty)
assert pickle.loads(data) == ty
def test_types_weakref():
for ty in get_many_types():
wr = weakref.ref(ty)
assert wr() is not None
# Note that ty may be a singleton and therefore outlive this loop
wr = weakref.ref(pa.int32())
assert wr() is not None # singleton
wr = weakref.ref(pa.list_(pa.int32()))
assert wr() is None # not a singleton
def test_fields_hashable():
in_dict = {}
fields = [pa.field('a', pa.int32()),
pa.field('a', pa.int64()),
pa.field('a', pa.int64(), nullable=False),
pa.field('b', pa.int32()),
pa.field('b', pa.int32(), nullable=False)]
for i, field in enumerate(fields):
in_dict[field] = i
assert len(in_dict) == len(fields)
for i, field in enumerate(fields):
assert in_dict[field] == i
def test_fields_weakrefable():
field = pa.field('a', pa.int32())
wr = weakref.ref(field)
assert wr() is not None
del field
assert wr() is None
@pytest.mark.parametrize('t,check_func', [
(pa.date32(), types.is_date32),
(pa.date64(), types.is_date64),
(pa.time32('s'), types.is_time32),
(pa.time64('ns'), types.is_time64),
(pa.int8(), types.is_int8),
(pa.int16(), types.is_int16),
(pa.int32(), types.is_int32),
(pa.int64(), types.is_int64),
(pa.uint8(), types.is_uint8),
(pa.uint16(), types.is_uint16),
(pa.uint32(), types.is_uint32),
(pa.uint64(), types.is_uint64),
(pa.float16(), types.is_float16),
(pa.float32(), types.is_float32),
(pa.float64(), types.is_float64)
])
def test_exact_primitive_types(t, check_func):
assert check_func(t)
def test_type_id():
# enum values are not exposed publicly
for ty in get_many_types():
assert isinstance(ty.id, int)
def test_bit_width():
for ty, expected in [(pa.bool_(), 1),
(pa.int8(), 8),
(pa.uint32(), 32),
(pa.float16(), 16),
(pa.decimal128(19, 4), 128),
(pa.decimal256(76, 38), 256),
(pa.binary(42), 42 * 8)]:
assert ty.bit_width == expected
for ty in [pa.binary(), pa.string(), pa.list_(pa.int16())]:
with pytest.raises(ValueError, match="fixed width"):
ty.bit_width
def test_fixed_size_binary_byte_width():
ty = pa.binary(5)
assert ty.byte_width == 5
def test_decimal_properties():
ty = pa.decimal128(19, 4)
assert ty.byte_width == 16
assert ty.precision == 19
assert ty.scale == 4
ty = pa.decimal256(76, 38)
assert ty.byte_width == 32
assert ty.precision == 76
assert ty.scale == 38
def test_decimal_overflow():
pa.decimal128(1, 0)
pa.decimal128(38, 0)
for i in (0, -1, 39):
with pytest.raises(ValueError):
pa.decimal128(i, 0)
pa.decimal256(1, 0)
pa.decimal256(76, 0)
for i in (0, -1, 77):
with pytest.raises(ValueError):
pa.decimal256(i, 0)
def test_timedelta_overflow():
# microsecond resolution, overflow
d = datetime.timedelta(days=-106751992, seconds=71945, microseconds=224192)
with pytest.raises(pa.ArrowInvalid):
pa.scalar(d)
# microsecond resolution, overflow
d = datetime.timedelta(days=106751991, seconds=14454, microseconds=775808)
with pytest.raises(pa.ArrowInvalid):
pa.scalar(d)
# nanosecond resolution, overflow
d = datetime.timedelta(days=-106752, seconds=763, microseconds=145224)
with pytest.raises(pa.ArrowInvalid):
pa.scalar(d, type=pa.duration('ns'))
# microsecond resolution, not overflow
pa.scalar(d, type=pa.duration('us')).as_py() == d
# second/millisecond resolution, not overflow
for d in [datetime.timedelta.min, datetime.timedelta.max]:
pa.scalar(d, type=pa.duration('ms')).as_py() == d
pa.scalar(d, type=pa.duration('s')).as_py() == d
def test_type_equality_operators():
many_types = get_many_types()
non_pyarrow = ('foo', 16, {'s', 'e', 't'})
for index, ty in enumerate(many_types):
# could use two parametrization levels,
# but that'd bloat pytest's output
for i, other in enumerate(many_types + non_pyarrow):
if i == index:
assert ty == other
else:
assert ty != other
def test_key_value_metadata():
m = pa.KeyValueMetadata({'a': 'A', 'b': 'B'})
assert len(m) == 2
assert m['a'] == b'A'
assert m[b'a'] == b'A'
assert m['b'] == b'B'
assert 'a' in m
assert b'a' in m
assert 'c' not in m
m1 = pa.KeyValueMetadata({'a': 'A', 'b': 'B'})
m2 = pa.KeyValueMetadata(a='A', b='B')
m3 = pa.KeyValueMetadata([('a', 'A'), ('b', 'B')])
assert m1 != 2
assert m1 == m2
assert m2 == m3
assert m1 == {'a': 'A', 'b': 'B'}
assert m1 != {'a': 'A', 'b': 'C'}
with pytest.raises(TypeError):
pa.KeyValueMetadata({'a': 1})
with pytest.raises(TypeError):
pa.KeyValueMetadata({1: 'a'})
with pytest.raises(TypeError):
pa.KeyValueMetadata(a=1)
expected = [(b'a', b'A'), (b'b', b'B')]
result = [(k, v) for k, v in m3.items()]
assert result == expected
assert list(m3.items()) == expected
assert list(m3.keys()) == [b'a', b'b']
assert list(m3.values()) == [b'A', b'B']
assert len(m3) == 2
# test duplicate key support
md = pa.KeyValueMetadata([
('a', 'alpha'),
('b', 'beta'),
('a', 'Alpha'),
('a', 'ALPHA'),
])
expected = [
(b'a', b'alpha'),
(b'b', b'beta'),
(b'a', b'Alpha'),
(b'a', b'ALPHA')
]
assert len(md) == 4
assert isinstance(md.keys(), Iterator)
assert isinstance(md.values(), Iterator)
assert isinstance(md.items(), Iterator)
assert list(md.items()) == expected
assert list(md.keys()) == [k for k, _ in expected]
assert list(md.values()) == [v for _, v in expected]
# first occurrence
assert md['a'] == b'alpha'
assert md['b'] == b'beta'
assert md.get_all('a') == [b'alpha', b'Alpha', b'ALPHA']
assert md.get_all('b') == [b'beta']
assert md.get_all('unkown') == []
with pytest.raises(KeyError):
md = pa.KeyValueMetadata([
('a', 'alpha'),
('b', 'beta'),
('a', 'Alpha'),
('a', 'ALPHA'),