-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathtest_dataframe.py
More file actions
5210 lines (4531 loc) · 175 KB
/
test_dataframe.py
File metadata and controls
5210 lines (4531 loc) · 175 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
#!/usr/bin/env python3
#
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
#
import copy
import datetime
import decimal
import json
import logging
import math
import sys
from array import array
from collections import namedtuple
from decimal import Decimal
from itertools import product
from textwrap import dedent
from typing import Tuple
from unittest import mock
from snowflake.snowpark.dataframe import map
from snowflake.snowpark.session import Session
from tests.conftest import local_testing_mode
try:
import pandas as pd # noqa: F401
from pandas import DataFrame as PandasDF
from pandas.testing import assert_frame_equal
is_pandas_available = True
except ImportError:
is_pandas_available = False
import pytest
from snowflake.connector import IntegrityError, ProgrammingError
from snowflake.snowpark import Column, Row, Window
from snowflake.snowpark._internal.analyzer.analyzer_utils import result_scan_statement
from snowflake.snowpark._internal.analyzer.expression import Attribute, Star
from snowflake.snowpark._internal.utils import TempObjectType
from snowflake.snowpark.dataframe_na_functions import _SUBSET_CHECK_ERROR_MESSAGE
from snowflake.snowpark.exceptions import (
SnowparkColumnException,
SnowparkCreateDynamicTableException,
SnowparkCreateViewException,
SnowparkDataframeException,
SnowparkSQLException,
)
from snowflake.snowpark.functions import (
col,
column,
concat,
count,
explode,
get_path,
lit,
make_interval,
rank,
seq1,
seq2,
seq4,
seq8,
table_function,
udtf,
uniform,
when,
)
from snowflake.snowpark.types import (
FileType,
ArrayType,
BinaryType,
BooleanType,
ByteType,
DateType,
DecimalType,
DoubleType,
FloatType,
IntegerType,
LongType,
MapType,
NullType,
ShortType,
StringType,
StructField,
StructType,
TimestampTimeZone,
TimestampType,
TimeType,
VariantType,
)
from tests.utils import (
IS_IN_STORED_PROC,
IS_IN_STORED_PROC_LOCALFS,
TestData,
TestFiles,
Utils,
multithreaded_run,
structured_types_enabled_session,
structured_types_supported,
)
# Python 3.8 needs to use typing.Iterable because collections.abc.Iterable is not subscriptable
# Python 3.9 can use both
# Python 3.10 needs to use collections.abc.Iterable because typing.Iterable is removed
if sys.version_info <= (3, 9):
from typing import Iterable
else:
from collections.abc import Iterable
tmp_stage_name = Utils.random_stage_name()
test_file_on_stage = f"@{tmp_stage_name}/testCSV.csv"
user_schema = StructType(
[
StructField("a", IntegerType()),
StructField("b", StringType()),
StructField("c", DoubleType()),
]
)
@pytest.fixture(scope="module", autouse=True)
def setup(session, resources_path, local_testing_mode):
if not local_testing_mode:
Utils.create_stage(session, tmp_stage_name, is_temporary=True)
test_files = TestFiles(resources_path)
Utils.upload_to_stage(
session, f"@{tmp_stage_name}", test_files.test_file_csv, compress=False
)
@pytest.fixture(scope="function")
def table_name_1(session):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
session.create_dataframe(
[[1], [2], [3]], schema=StructType([StructField("num", IntegerType())])
).write.save_as_table(table_name)
yield table_name
Utils.drop_table(session, table_name)
def test_dataframe_get_item(session):
df = session.create_dataframe([[1, "a"], [2, "b"], [3, "c"], [4, "d"]]).to_df(
"id", "value"
)
df["id"]
df[0]
df[col("id")]
df[["id"]]
df[("id")]
with pytest.raises(TypeError) as exc_info:
df[11.1]
assert "Unexpected item type: " in str(exc_info)
def test_dataframe_get_attr(session):
df = session.create_dataframe([[1, "a"], [2, "b"], [3, "c"], [4, "d"]]).to_df(
"id", "value"
)
df.id
df.value
with pytest.raises(AttributeError) as exc_info:
df.non_existent
assert "object has no attribute" in str(exc_info)
@pytest.mark.skipif(IS_IN_STORED_PROC_LOCALFS, reason="need resources")
def test_read_stage_file_show(session, resources_path, local_testing_mode):
tmp_stage_name = Utils.random_stage_name()
test_files = TestFiles(resources_path)
test_file_on_stage = f"@{tmp_stage_name}/testCSV.csv"
try:
Utils.create_stage(session, tmp_stage_name, is_temporary=True)
Utils.upload_to_stage(
session, "@" + tmp_stage_name, test_files.test_file_csv, compress=False
)
user_schema = StructType(
[
StructField("a", IntegerType()),
StructField("b", StringType()),
StructField("c", DoubleType()),
]
)
result_str = (
session.read.option("purge", False)
.schema(user_schema)
.csv(test_file_on_stage)
._show_string(_emit_ast=session.ast_enabled)
)
assert (
result_str
== """
-------------------
|"A" |"B" |"C" |
-------------------
|1 |one |1.2 |
|2 |two |2.2 |
-------------------
""".lstrip()
)
finally:
if not local_testing_mode:
Utils.drop_stage(session, tmp_stage_name)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="This is a SQL test",
run=False,
)
def test_show_using_with_select_statement(session):
df = session.sql(
"with t1 as (select 1 as a union all select 2 union all select 3 "
" union all select 4 union all select 5 union all select 6 "
" union all select 7 union all select 8 union all select 9 "
" union all select 10 union all select 11 union all select 12) "
"select * from t1"
)
assert (
df._show_string(_emit_ast=session.ast_enabled)
== """
-------
|"A" |
-------
|1 |
|2 |
|3 |
|4 |
|5 |
|6 |
|7 |
|8 |
|9 |
|10 |
-------\n""".lstrip()
)
@pytest.mark.parametrize("use_simplification", [True, False])
def test_distinct(session, use_simplification, local_testing_mode):
"""Tests df.distinct()."""
session.conf.set("use_simplified_query_generation", use_simplification)
df = session.create_dataframe(
[
[1, 1],
[1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5],
[None, 1],
[1, None],
[None, None],
]
).to_df("id", "v")
res = df.distinct().sort(["id", "v"]).collect()
assert res == [
Row(None, None),
Row(None, 1),
Row(1, None),
Row(1, 1),
Row(2, 2),
Row(3, 3),
Row(4, 4),
Row(5, 5),
]
res = df.select(col("id")).distinct().sort(["id"]).collect()
assert res == [Row(None), Row(1), Row(2), Row(3), Row(4), Row(5)]
res = df.select(col("v")).distinct().sort(["v"]).collect()
assert res == [Row(None), Row(1), Row(2), Row(3), Row(4), Row(5)]
if not local_testing_mode:
queries = df.distinct().queries["queries"]
if use_simplification:
assert "SELECT DISTINCT" in queries[0]
else:
assert "GROUP BY" in queries[0]
def test_first(session):
"""Tests df.first()."""
df = session.create_dataframe([[1, "a"], [2, "b"], [3, "c"], [4, "d"]]).to_df(
"id", "v"
)
# empty first, should default to 1
res = df.first()
assert res == Row(1, "a")
res = df.first(0)
assert res == []
res = df.first(1)
assert res == [Row(1, "a")]
res = df.first(2)
res.sort(key=lambda x: x[0])
assert res == [Row(1, "a"), Row(2, "b")]
res = df.first(3)
res.sort(key=lambda x: x[0])
assert res == [Row(1, "a"), Row(2, "b"), Row(3, "c")]
res = df.first(4)
res.sort(key=lambda x: x[0])
assert res == [Row(1, "a"), Row(2, "b"), Row(3, "c"), Row(4, "d")]
# Negative value is equivalent to collect()
res = df.first(-1)
res.sort(key=lambda x: x[0])
assert res == [Row(1, "a"), Row(2, "b"), Row(3, "c"), Row(4, "d")]
# first-value larger than cardinality
res = df.first(123)
res.sort(key=lambda x: x[0])
assert res == [Row(1, "a"), Row(2, "b"), Row(3, "c"), Row(4, "d")]
# test invalid type argument passed to first
with pytest.raises(ValueError) as ex_info:
df.first("abc")
assert "Invalid type of argument passed to first()" in str(ex_info)
def test_new_df_from_range(session):
"""Tests df.range()."""
# range(start, end, step)
df = session.range(1, 10, 2)
res = df.collect()
expected = [Row(1), Row(3), Row(5), Row(7), Row(9)]
assert res == expected
# range(start, end)
df = session.range(1, 10)
res = df.collect()
expected = [
Row(1),
Row(2),
Row(3),
Row(4),
Row(5),
Row(6),
Row(7),
Row(8),
Row(9),
]
assert res == expected
# range(end)
df = session.range(10)
res = df.collect()
expected = [
Row(0),
Row(1),
Row(2),
Row(3),
Row(4),
Row(5),
Row(6),
Row(7),
Row(8),
Row(9),
]
assert res == expected
def test_select_single_column(session):
"""Tests df.select() on dataframes with a single column."""
df = session.range(1, 10, 2)
res = df.filter(col("id") > 4).select("id").collect()
expected = [Row(5), Row(7), Row(9)]
assert res == expected
df = session.range(1, 10, 2)
res = df.filter(col("id") < 4).select("id").collect()
expected = [Row(1), Row(3)]
assert res == expected
res = session.range(1, 10, 2).select("id").filter(col("id") <= 4).collect()
expected = [Row(1), Row(3)]
assert res == expected
res = session.range(1, 10, 2).select("id").filter(col("id") <= 3).collect()
expected = [Row(1), Row(3)]
assert res == expected
res = session.range(1, 10, 2).select("id").filter(col("id") <= 0).collect()
expected = []
assert res == expected
def test_select_star(session):
"""Tests df.select('*')."""
# Single column
res = session.range(3, 8).select("*").collect()
expected = [Row(3), Row(4), Row(5), Row(6), Row(7)]
result = res == expected
assert result
# Two columns
df = session.range(3, 8).select([col("id"), col("id").alias("id_prime")])
res = df.select("*").collect()
expected = [Row(3, 3), Row(4, 4), Row(5, 5), Row(6, 6), Row(7, 7)]
assert res == expected
@pytest.mark.udf
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="Table function is not supported in Local Testing",
)
def test_select_table_function(session):
df = session.create_dataframe(
[(1, "one o one", 10), (2, "twenty two", 20), (3, "thirty three", 30)]
).to_df(["a", "b", "c"])
# test single output column udtf
class TwoXUDTF:
def process(self, n: int):
yield (2 * n,)
table_func = udtf(
TwoXUDTF,
output_schema=StructType([StructField("two_x", IntegerType())]),
input_types=[IntegerType()],
)
# test single column selection
expected_result = [Row(TWO_X=2), Row(TWO_X=4), Row(TWO_X=6)]
Utils.check_answer(df.select(table_func("a")), expected_result)
Utils.check_answer(df.select(table_func(col("a"))), expected_result)
Utils.check_answer(df.select(table_func(df.a)), expected_result)
# test multiple column selection
expected_result = [Row(A=1, TWO_X=2), Row(A=2, TWO_X=4), Row(A=3, TWO_X=6)]
Utils.check_answer(df.select("a", table_func("a")), expected_result)
Utils.check_answer(df.select(col("a"), table_func(col("a"))), expected_result)
Utils.check_answer(df.select(df.a, table_func(df.a)), expected_result)
# test multiple column selection with order preservation
expected_result = [
Row(A=1, TWO_X=2, C=10),
Row(A=2, TWO_X=4, C=20),
Row(A=3, TWO_X=6, C=30),
]
Utils.check_answer(df.select("a", table_func("a"), "c"), expected_result)
Utils.check_answer(
df.select(col("a"), table_func(col("a")), col("c")), expected_result
)
Utils.check_answer(df.select(df.a, table_func(df.a), df.c), expected_result)
# test multiple output column udtf
class TwoXSixXUDTF:
def process(self, n: int):
yield (2 * n, 6 * n)
table_func = udtf(
TwoXSixXUDTF,
output_schema=StructType(
[StructField("two_x", IntegerType()), StructField("six_x", IntegerType())]
),
input_types=[IntegerType()],
)
# test single column selection
expected_result = [
Row(TWO_X=2, SIX_X=6),
Row(TWO_X=4, SIX_X=12),
Row(TWO_X=6, SIX_X=18),
]
Utils.check_answer(df.select(table_func("a")), expected_result)
Utils.check_answer(df.select(table_func(col("a"))), expected_result)
Utils.check_answer(df.select(table_func(df.a)), expected_result)
# test multiple column selection
expected_result = [
Row(A=1, TWO_X=2, SIX_X=6),
Row(A=2, TWO_X=4, SIX_X=12),
Row(A=3, TWO_X=6, SIX_X=18),
]
Utils.check_answer(df.select("a", table_func("a")), expected_result)
Utils.check_answer(df.select(col("a"), table_func(col("a"))), expected_result)
Utils.check_answer(df.select(df.a, table_func(df.a)), expected_result)
# test multiple column selection with order preservation
expected_result = [
Row(A=1, TWO_X=2, SIX_X=6, C=10),
Row(A=2, TWO_X=4, SIX_X=12, C=20),
Row(A=3, TWO_X=6, SIX_X=18, C=30),
]
Utils.check_answer(df.select("a", table_func("a"), "c"), expected_result)
Utils.check_answer(
df.select(col("a"), table_func(col("a")), col("c")), expected_result
)
Utils.check_answer(df.select(df.a, table_func(df.a), df.c), expected_result)
# test with aliases
expected_result = [
Row(A=1, DOUBLE=2, SIX_X=6, C=10),
Row(A=2, DOUBLE=4, SIX_X=12, C=20),
Row(A=3, DOUBLE=6, SIX_X=18, C=30),
]
Utils.check_answer(
df.select("a", table_func("a").alias("double", "six_x"), "c"), expected_result
)
Utils.check_answer(
df.select(col("a"), table_func(col("a")).alias("double", "six_x"), col("c")),
expected_result,
)
Utils.check_answer(
df.select(df.a, table_func(df.a).alias("double", "six_x"), df.c),
expected_result,
)
# testing in-built table functions
table_func = table_function("split_to_table")
expected_result = [
Row(A=1, SEQ=1, INDEX=1, VALUE="one"),
Row(A=1, SEQ=1, INDEX=2, VALUE="o"),
Row(A=1, SEQ=1, INDEX=3, VALUE="one"),
Row(A=2, SEQ=2, INDEX=1, VALUE="twenty"),
Row(A=2, SEQ=2, INDEX=2, VALUE="two"),
Row(A=3, SEQ=3, INDEX=1, VALUE="thirty"),
Row(A=3, SEQ=3, INDEX=2, VALUE="three"),
]
Utils.check_answer(df.select("a", table_func("b", lit(" "))), expected_result)
Utils.check_answer(
df.select(col("a"), table_func(col("b"), lit(" "))), expected_result
)
Utils.check_answer(df.select(df.a, table_func(df.b, lit(" "))), expected_result)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="Session.generator is not supported in Local Testing",
)
def test_generator_table_function(session):
# works with rowcount
expected_result = [Row(-108, 3), Row(-107, 3), Row(0, 3)]
df = (
session.generator(seq1(1), uniform(1, 10, 2), rowcount=150)
.order_by(seq1(1))
.limit(3, offset=20)
)
Utils.check_answer(df, expected_result)
# works with timelimit
expected_result = [Row(0, 3), Row(0, 3), Row(0, 3)]
df = (
session.generator(seq2(0), uniform(1, 10, 2), timelimit=1)
.order_by(seq2(0))
.limit(3)
)
Utils.check_answer(df, expected_result)
# works with combination of both
expected_result = [Row(-108, 3), Row(-107, 3), Row(0, 3)]
df = (
session.generator(seq1(1), uniform(1, 10, 2), timelimit=1, rowcount=150)
.order_by(seq1(1))
.limit(3, offset=20)
)
Utils.check_answer(df, expected_result)
# works without both
df = session.generator(seq4(1), uniform(1, 10, 2))
Utils.check_answer(df, [])
# aliasing works
df = (
session.generator(
seq1(1).as_("pixel"), uniform(1, 10, 2).as_("unicorn"), rowcount=150
)
.order_by("pixel")
.limit(3, offset=20)
)
expected_result = [
Row(pixel=-108, unicorn=3),
Row(pixel=-107, unicorn=3),
Row(pixel=0, unicorn=3),
]
Utils.check_answer(df, expected_result)
# aggregation works
df = session.generator(count(seq1(0)).as_("rows"), rowcount=150)
expected_result = [Row(rows=150)]
Utils.check_answer(df, expected_result)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="Session.generator is not supported in Local Testing",
)
def test_generator_table_function_negative(session):
# fails when no operators added
with pytest.raises(ValueError) as ex_info:
_ = session.generator(rowcount=10)
assert "Columns cannot be empty for generator table function" in str(ex_info)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="Table function is not supported in Local Testing",
)
@pytest.mark.udf
def test_select_table_function_negative(session):
df = session.create_dataframe([(1, "a", 10), (2, "b", 20), (3, "c", 30)]).to_df(
["a", "b", "c"]
)
class TwoXUDTF:
def process(self, n: int):
yield (2 * n,)
two_x_udtf = udtf(
TwoXUDTF,
output_schema=StructType([StructField("two_x", IntegerType())]),
input_types=[IntegerType()],
)
with pytest.raises(ValueError) as ex_info:
df.select(two_x_udtf("a"), "b", two_x_udtf("c"))
assert "At most one table function can be called" in str(ex_info)
@udtf(output_schema=["two_x", "three_x"])
class multiplier_udtf:
def process(self, n: int) -> Iterable[Tuple[int, int]]:
yield (2 * n, 3 * n)
with pytest.raises(ValueError) as ex_info:
df.select(multiplier_udtf(df.a).alias("double", "double"))
assert "All output column names after aliasing must be unique" in str(ex_info)
with pytest.raises(ValueError) as ex_info:
df.select(multiplier_udtf(df.a).alias("double"))
assert (
"The number of aliases should be same as the number of cols added by table function"
in str(ex_info)
)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="hash is not supported in Local Testing",
)
def test_random_split(session):
original_enabled = session.conf.get("use_simplified_query_generation")
try:
session.conf.set("use_simplified_query_generation", True)
# test the cache_result is not invoked
df = session.range(1, 50)
with session.query_history() as history:
df1, df2 = df.random_split([0.5, 0.5])
assert len(history.queries) == 0
# test the that seed is respected
df1, df2, df3 = df.random_split([0.5, 0.4, 0.1], seed=1729)
dfa, dfb, dfc = df.random_split([0.5, 0.4, 0.1], seed=1729)
Utils.check_answer(df1, dfa)
Utils.check_answer(df2, dfb)
Utils.check_answer(df3, dfc)
# assert that there in no overlap between the splits
df1, df2 = df.random_split([0.5, 0.5])
assert df1.intersect(df2).count() == 0
finally:
session.conf.set("use_simplified_query_generation", original_enabled)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="Table function is not supported in Local Testing",
)
@pytest.mark.udf
def test_select_with_table_function_column_overlap(session):
df = session.create_dataframe([[1, 2, 3], [4, 5, 6]], schema=["A", "B", "C"])
class TwoXUDTF:
def process(self, n: int):
yield (2 * n,)
two_x_udtf = udtf(
TwoXUDTF,
output_schema=StructType([StructField("A", IntegerType())]),
input_types=[IntegerType()],
)
# ensure aliasing works
Utils.check_answer(
df.select(df.a, df.b, two_x_udtf(df.a).alias("a2")),
[Row(A=1, B=2, A2=2), Row(A=4, B=5, A2=8)],
)
Utils.check_answer(
df.select(col("a").alias("a1"), df.b, two_x_udtf(df.a).alias("a2")),
[Row(A1=1, B=2, A2=2), Row(A1=4, B=5, A2=8)],
)
# join_table_function works
Utils.check_answer(
df.join_table_function(two_x_udtf(df.a)), [Row(1, 2, 3, 2), Row(4, 5, 6, 8)]
)
Utils.check_answer(
df.join_table_function(two_x_udtf(df.a).alias("a2")),
[Row(A=1, B=2, C=3, A2=2), Row(A=4, B=5, C=6, A2=8)],
)
# ensure explode works
df = session.create_dataframe([(1, [1, 2]), (2, [3, 4])], schema=["id", "value"])
Utils.check_answer(
df.select(df.id, explode(df.value).as_("VAL")),
[
Row(ID=1, VAL="1"),
Row(ID=1, VAL="2"),
Row(ID=2, VAL="3"),
Row(ID=2, VAL="4"),
],
)
# ensure overlapping columns work if a single table function is selected
Utils.check_answer(
df.select(explode(df.value)),
[Row(VALUE="1"), Row(VALUE="2"), Row(VALUE="3"), Row(VALUE="4")],
)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="functions.explode is not supported in Local Testing",
)
def test_explode(session):
df = session.create_dataframe(
[[1, [1, 2, 3], {"a": "b"}, "Kimura"]], schema=["idx", "lists", "maps", "strs"]
)
# col is str
expected_result = [
Row(value="1"),
Row(value="2"),
Row(value="3"),
]
Utils.check_answer(df.select(explode("lists")), expected_result)
expected_result = [Row(key="a", value='"b"')]
Utils.check_answer(df.select(explode("maps")), expected_result)
# col is Column
expected_result = [
Row(value="1"),
Row(value="2"),
Row(value="3"),
]
Utils.check_answer(df.select(explode(col("lists"))), expected_result)
expected_result = [Row(key="a", value='"b"')]
Utils.check_answer(df.select(explode(df.maps)), expected_result)
# with other non table cols
expected_result = [
Row(idx=1, value="1"),
Row(idx=1, value="2"),
Row(idx=1, value="3"),
]
Utils.check_answer(df.select(df.idx, explode(col("lists"))), expected_result)
expected_result = [Row(strs="Kimura", key="a", value='"b"')]
Utils.check_answer(df.select(df.strs, explode(df.maps)), expected_result)
# with alias
expected_result = [
Row(idx=1, uno="1"),
Row(idx=1, uno="2"),
Row(idx=1, uno="3"),
]
Utils.check_answer(
df.select(df.idx, explode(col("lists")).alias("uno")), expected_result
)
expected_result = [Row(strs="Kimura", primo="a", secundo='"b"')]
Utils.check_answer(
df.select(df.strs, explode(df.maps).as_("primo", "secundo")), expected_result
)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="functions.explode is not supported in Local Testing",
)
def test_explode_negative(session):
df = session.create_dataframe(
[[1, [1, 2, 3], {"a": "b"}, "Kimura"]], schema=["idx", "lists", "maps", "strs"]
)
split_to_table = table_function("split_to_table")
# mix explode and table function
with pytest.raises(
ValueError, match="At most one table function can be called inside"
):
df.select(split_to_table(df.strs, lit("")), explode(df.lists))
# mismatch in number of alias given array
with pytest.raises(
ValueError,
match="Invalid number of aliases given for explode. Expecting 1, got 2",
):
df.select(explode(df.lists).alias("key", "val"))
# mismatch in number of alias given map
with pytest.raises(
ValueError,
match="Invalid number of aliases given for explode. Expecting 2, got 1",
):
df.select(explode(df.maps).alias("val"))
# invalid column type
with pytest.raises(ValueError, match="Invalid column type for explode"):
df.select(explode(df.idx))
with pytest.raises(ValueError, match="Invalid column type for explode"):
df.select(explode(col("DOES_NOT_EXIST")))
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="UDTF is not supported in Local Testing",
)
@pytest.mark.udf
def test_with_column(session):
df = session.create_dataframe([[1, 2], [3, 4]], schema=["a", "b"])
expected = [Row(A=1, B=2, MEAN=1.5), Row(A=3, B=4, MEAN=3.5)]
Utils.check_answer(df.with_column("mean", (df["a"] + df["b"]) / 2), expected)
@udtf(output_schema=["number"])
class sum_udtf:
def process(self, a: int, b: int) -> Iterable[Tuple[int]]:
yield (a + b,)
expected = [Row(A=1, B=2, TOTAL=3), Row(A=3, B=4, TOTAL=7)]
Utils.check_answer(df.with_column("total", sum_udtf(df.a, df.b)), expected)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="UDTF is not supported in Local Testing",
)
@pytest.mark.udf
def test_with_column_negative(session):
df = session.create_dataframe([[1, 2], [3, 4]], schema=["a", "b"])
# raise error when table function returns multiple columns
@udtf(output_schema=["sum", "diff"])
class sum_diff_udtf:
def process(self, a: int, b: int) -> Iterable[Tuple[int, int]]:
yield (a + b, a - b)
with pytest.raises(ValueError) as ex_info:
df.with_column("total", sum_diff_udtf(df.a, df.b))
assert (
"The number of aliases should be same as the number of cols added by table function"
in str(ex_info)
)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="UDTF is not supported in Local Testing",
)
@pytest.mark.udf
def test_with_columns(session):
df = session.create_dataframe([[1, 2], [3, 4]], schema=["a", "b"])
@udtf(output_schema=["number"])
class sum_udtf:
def process(self, a: int, b: int) -> Iterable[Tuple[int]]:
yield (a + b,)
expected = [Row(A=1, B=2, MEAN=1.5, TOTAL=3), Row(A=3, B=4, MEAN=3.5, TOTAL=7)]
Utils.check_answer(
df.with_columns(
["mean", "total"], [(df["a"] + df["b"]) / 2, sum_udtf(df.a, df.b)]
),
expected,
)
# test with a udtf sandwiched between names
@udtf(output_schema=["sum", "diff"])
class sum_diff_udtf:
def process(self, a: int, b: int) -> Iterable[Tuple[int, int]]:
yield (a + b, a - b)
expected = [
Row(A=1, B=2, MEAN=1.5, ADD=3, SUB=-1, TWO_A=2),
Row(A=3, B=4, MEAN=3.5, ADD=7, SUB=-1, TWO_A=6),
]
Utils.check_answer(
df.with_columns(
["mean", "add", "sub", "two_a"],
[(df["a"] + df["b"]) / 2, sum_diff_udtf(df.a, df.b), df.a + df.a],
),
expected,
)
# test with built-in table function
split_to_table = table_function("split_to_table")
df = session.sql(
"select 'James' as name, 'address1 address2 address3' as addresses"
)
expected = [
Row(
NAME="James",
ADDRESSES="address1 address2 address3",
SEQ=1,
IDX=1,
VAL="address1",
),
Row(
NAME="James",
ADDRESSES="address1 address2 address3",
SEQ=1,
IDX=2,
VAL="address2",
),
Row(
NAME="James",
ADDRESSES="address1 address2 address3",
SEQ=1,
IDX=3,
VAL="address3",
),
]
Utils.check_answer(
df.with_columns(
["seq", "idx", "val"], [split_to_table(df.addresses, lit(" "))]
),
expected,
)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="UDTF is not supported in Local Testing",
)
@pytest.mark.udf
def test_with_columns_negative(session):
df = session.create_dataframe(
[[1, 2, "one o one"], [3, 4, "two o two"]], schema=["a", "b", "c"]
)
# raise error when more column names are added than cols
with pytest.raises(ValueError) as ex_info:
df.with_columns(["sum", "diff"], [(df["a"] + df["b"]) / 2])
assert (
"The size of column names (2) is not equal to the size of columns (1)"
in str(ex_info)
)
# raise when more than one table function is called
split_to_table = table_function("split_to_table")
@udtf(output_schema=["number"])
class sum_udtf:
def process(self, a: int, b: int) -> Iterable[Tuple[int]]:
yield (a + b,)
with pytest.raises(ValueError) as ex_info:
df.with_columns(
["total", "sum", "diff"], [sum_udtf(df.a, df.b), split_to_table(df.c)]
)
assert (
"Only one table function call accepted inside with_columns call, (2) provided"
in str(ex_info)
)
# raise when len(cols) < len(values)
with pytest.raises(ValueError) as ex_info:
df.with_columns(["total"], [sum_udtf(df.a, df.b), (df.a + df.b) / 2])
assert "Fewer columns provided." in str(ex_info)
# raise when col names don't match output cols
@udtf(output_schema=["sum", "diff"])
class sum_diff_udtf:
def process(self, a: int, b: int) -> Iterable[Tuple[int, int]]:
yield (a + b, a - b)
with pytest.raises(ValueError) as ex_info:
df.with_columns(
["mean", "total"], [(df["a"] + df["b"]) / 2, split_to_table(df.c, lit(" "))]
)
assert (
"The number of aliases should be same as the number of cols added by table function"
in str(ex_info)
)