-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathtest_dataframe_suite.py
More file actions
3168 lines (2737 loc) · 106 KB
/
test_dataframe_suite.py
File metadata and controls
3168 lines (2737 loc) · 106 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
#
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
#
import logging
import copy
import math
import os
import re
from datetime import date, datetime
from decimal import Decimal
from logging import getLogger
from typing import Iterator
import pytest
from snowflake.snowpark import Row, Session
from snowflake.snowpark._internal.utils import TempObjectType, parse_table_name
from snowflake.snowpark.exceptions import (
SnowparkColumnException,
SnowparkDataframeException,
SnowparkInvalidObjectNameException,
SnowparkPlanException,
SnowparkSQLException,
)
from snowflake.snowpark.functions import (
as_integer,
col,
datediff,
get,
lit,
max,
mean,
min,
parse_json,
sum as sum_,
to_timestamp,
)
from snowflake.snowpark.types import (
ArrayType,
BinaryType,
BooleanType,
ByteType,
DateType,
DecimalType,
DoubleType,
FloatType,
GeographyType,
GeometryType,
IntegerType,
LongType,
MapType,
ShortType,
StringType,
StructField,
StructType,
TimestampTimeZone,
TimestampType,
TimeType,
VariantType,
VectorType,
)
from tests.utils import (
IS_IN_STORED_PROC,
IS_IN_STORED_PROC_LOCALFS,
TestData,
TestFiles,
Utils,
multithreaded_run,
)
SAMPLING_DEVIATION = 0.4
_logger = getLogger(__name__)
def test_null_data_in_tables(session, local_testing_mode):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
try:
if not local_testing_mode:
Utils.create_table(session, table_name, "num int")
session.sql(
f"insert into {table_name} values(null),(null),(null)"
).collect()
else:
session.create_dataframe(
[[None], [None], [None]],
schema=StructType([StructField("num", IntegerType())]),
).write.save_as_table(table_name)
res = session.table(table_name).collect()
assert res == [Row(None), Row(None), Row(None)]
finally:
if not local_testing_mode:
Utils.drop_table(session, table_name)
def test_null_data_in_local_relation_with_filters(session):
df = session.create_dataframe([[1, None], [2, "NotNull"], [3, None]]).to_df(
["a", "b"]
)
assert df.collect() == [Row(1, None), Row(2, "NotNull"), Row(3, None)]
df2 = session.create_dataframe([[1, None], [2, "NotNull"], [3, None]]).to_df(
["a", "b"]
)
assert df.collect() == df2.collect()
assert df.filter(col("b").is_null()).collect() == [
Row(1, None),
Row(3, None),
]
assert df.filter(col("b").is_not_null()).collect() == [Row(2, "NotNull")]
assert df.sort(col("b").asc_nulls_last()).collect() == [
Row(2, "NotNull"),
Row(1, None),
Row(3, None),
]
def test_project_null_values(session):
"""Tests projecting null values onto different columns in a dataframe"""
df = session.create_dataframe([1, 2]).to_df("a").with_column("b", lit(None))
assert df.collect() == [Row(1, None), Row(2, None)]
df2 = session.create_dataframe([1, 2]).to_df("a").select(lit(None))
assert len(df2.schema.fields) == 1
assert df2.schema.fields[0].datatype == StringType()
assert df2.collect() == [Row(None), Row(None)]
@pytest.mark.skipif(IS_IN_STORED_PROC_LOCALFS, reason="Large result")
def test_bulk_insert_from_collected_result(session):
"""Tests columnless bulk insert into a new table from a collected result of 'SELECT *'"""
table_name_source = Utils.random_name_for_temp_object(TempObjectType.TABLE)
table_name_copied = Utils.random_name_for_temp_object(TempObjectType.TABLE)
source_df = session.create_dataframe(
[
[Utils.random_alphanumeric_str(230), Utils.random_alphanumeric_str(230)]
for _ in range(1000)
],
schema=["a", "b"],
)
try:
source_df.write.save_as_table(table_name_source)
results = session.table(table_name_source).collect()
new_df = session.create_dataframe(results)
new_df.write.save_as_table(table_name_copied)
Utils.check_answer(session.table(table_name_source), source_df, True)
Utils.check_answer(session.table(table_name_copied), source_df, True)
finally:
Utils.drop_table(session, table_name_source)
Utils.drop_table(session, table_name_copied)
def test_write_null_data_to_table(session, local_testing_mode):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
df = session.create_dataframe([(1, None), (2, None), (3, None)]).to_df("a", "b")
try:
df.write.save_as_table(table_name)
Utils.check_answer(session.table(table_name), df, True)
finally:
if not local_testing_mode:
Utils.drop_table(session, table_name)
def test_view_should_be_updated(session, local_testing_mode):
"""Assert views should reflect changes if the underlying data is updated."""
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
view_name = Utils.random_name_for_temp_object(TempObjectType.VIEW)
df = session.create_dataframe([(1, 2), (3, 4)], schema=["a", "b"])
try:
df.write.save_as_table(table_name, table_type="temporary")
session.table(table_name).select(
sum_(col("a")), sum_(col("b"))
).create_or_replace_view(view_name)
Utils.check_answer(session.table(view_name), [Row(4, 6)])
session.create_dataframe(
[(5, 6), (7, 8)], schema=["a", "b"]
).write.save_as_table(table_name, mode="append")
Utils.check_answer(session.table(view_name), [Row(16, 20)])
finally:
if not local_testing_mode:
Utils.drop_table(session, table_name)
Utils.drop_view(session, view_name)
@multithreaded_run()
def test_create_or_replace_view_with_null_data(session, local_testing_mode):
df = session.create_dataframe([[1, None], [2, "NotNull"], [3, None]]).to_df(
["a", "b"]
)
view_name = Utils.random_name_for_temp_object(TempObjectType.VIEW)
try:
df.create_or_replace_view(view_name)
res = session.table(view_name).collect()
res.sort(key=lambda x: x[0])
assert res == [Row(1, None), Row(2, "NotNull"), Row(3, None)]
finally:
if not local_testing_mode:
Utils.drop_view(session, view_name)
def test_adjust_column_width_of_show(session):
df = session.create_dataframe([[1, None], [2, "NotNull"]]).to_df("a", "b")
# run show(), make sure no error is reported
df.show(10, 4)
res = df._show_string(10, 4, _emit_ast=session.ast_enabled)
assert (
res
== """
--------------
|"A" |"B" |
--------------
|1 |NULL |
|2 |N... |
--------------\n""".lstrip()
)
def test_show_with_null_data(session):
df = session.create_dataframe([[1, None], [2, "NotNull"]]).to_df("a", "b")
# run show(), make sure no error is reported
df.show(10)
res = df._show_string(10, _emit_ast=session.ast_enabled)
assert (
res
== """
-----------------
|"A" |"B" |
-----------------
|1 |NULL |
|2 |NotNull |
-----------------\n""".lstrip()
)
def test_show_multi_lines_row(session):
df = session.create_dataframe(
[
("line1\nline2", None),
("single line", "NotNull\none more line\nlast line"),
]
).to_df("a", "b")
res = df._show_string(2, _emit_ast=session.ast_enabled)
assert (
res
== """
-------------------------------
|"A" |"B" |
-------------------------------
|line1 |NULL |
|line2 | |
|single line |NotNull |
| |one more line |
| |last line |
-------------------------------\n""".lstrip()
)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="SQL query not supported",
run=False,
)
def test_show(session):
TestData.test_data1(session).show()
res = TestData.test_data1(session)._show_string(10, _emit_ast=session.ast_enabled)
assert (
res
== """
--------------------------
|"NUM" |"BOOL" |"STR" |
--------------------------
|1 |True |a |
|2 |False |b |
--------------------------\n""".lstrip()
)
# make sure show runs with sql
session.sql("show tables").show()
session.sql("drop table if exists test_table_123").show()
# truncate result, no more than 50 characters
res = session.sql("drop table if exists test_table_123")._show_string(
1, _emit_ast=session.ast_enabled
)
assert (
res
== """
------------------------------------------------------
|"status" |
------------------------------------------------------
|Drop statement executed successfully (TEST_TABL... |
------------------------------------------------------\n""".lstrip()
)
def test_cache_result(session):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
session.create_dataframe([[1], [2]], schema=["num"]).write.save_as_table(table_name)
df = session.table(table_name)
Utils.check_answer(df, [Row(1), Row(2)])
session.create_dataframe([[3]], schema=["num"]).write.save_as_table(
table_name, mode="append"
)
Utils.check_answer(df, [Row(1), Row(2), Row(3)])
df1 = df.cache_result()
session.create_dataframe([[4]], schema=["num"]).write.save_as_table(
table_name, mode="append"
)
Utils.check_answer(df1, [Row(1), Row(2), Row(3)])
Utils.check_answer(df, [Row(1), Row(2), Row(3), Row(4)])
df2 = df1.where(col("num") > 2)
Utils.check_answer(df2, [Row(3)])
df3 = df.where(col("num") > 2)
Utils.check_answer(df3, [Row(3), Row(4)])
df4 = df1.cache_result()
Utils.check_answer(df4, [Row(1), Row(2), Row(3)])
session.table(table_name).drop_table()
Utils.check_answer(df1, [Row(1), Row(2), Row(3)])
Utils.check_answer(df2, [Row(3)])
@multithreaded_run()
@pytest.mark.xfail(
reason="SNOW-1709861 result_scan for show tables is flaky", strict=False
)
@pytest.mark.xfail(
reason="SNOW-1709861 result_scan for show tables is flaky", strict=False
)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="This is testing query generation",
run=False,
)
def test_cache_result_with_show(session):
table_name1 = Utils.random_name_for_temp_object(TempObjectType.TABLE)
try:
session._run_query(f"create temp table {table_name1} (name string)")
session._run_query(f"insert into {table_name1} values('{table_name1}')")
table = session.table(table_name1)
# SHOW TABLES
df1 = session.sql("show tables").cache_result()
table_names = [tn[1] for tn in df1.collect()]
assert table_name1 in table_names
# SHOW TABLES + SELECT
df2 = session.sql("show tables").select('"created_on"', '"name"').cache_result()
table_names = [tn[1] for tn in df2.collect()]
assert table_name1 in table_names
# SHOW TABLES + SELECT + Join
df3 = session.sql("show tables").select('"created_on"', '"name"')
df3.show()
df4 = df3.join(table, df3['"name"'] == table["name"]).cache_result()
table_names = [tn[0] for tn in df4.select("name").collect()]
assert table_name1 in table_names
finally:
session._run_query(f"drop table {table_name1}")
def test_drop_cache_result_try_finally(session):
df = session.create_dataframe([[1, 2]], schema=["a", "b"])
cached = df.cache_result()
try:
df_after_cached = cached.select("a")
df_after_cached.collect()
finally:
cached.drop_table()
database, schema, table_name = parse_table_name(cached.table_name)
assert database == session.get_current_database()
assert schema == session.get_current_schema()
with pytest.raises(
SnowparkSQLException,
match=f"'{database[1:-1]}.{schema[1:-1]}.{table_name[1:-1]}' does not exist or not authorized.",
):
cached.collect()
with pytest.raises(
SnowparkSQLException,
match=f"'{database[1:-1]}.{schema[1:-1]}.{table_name[1:-1]}' does not exist or not authorized.",
):
df_after_cached.collect()
def test_drop_cache_result_context_manager(session):
df = session.create_dataframe([[1, 2]], schema=["a", "b"])
with df.cache_result() as cached:
df_after_cached = cached.select("a")
df_after_cached.collect()
database, schema, table_name = parse_table_name(cached.table_name)
with pytest.raises(
SnowparkSQLException,
match=f"'{database[1:-1]}.{schema[1:-1]}.{table_name[1:-1]}' does not exist or not authorized.",
):
cached.collect()
with pytest.raises(
SnowparkSQLException,
match=f"'{database[1:-1]}.{schema[1:-1]}.{table_name[1:-1]}' does not exist or not authorized.",
):
df_after_cached.collect()
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="This is testing query generation",
run=False,
)
def test_non_select_query_composition(session):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
try:
session.sql(
f"create or replace temporary table {table_name} (num int)"
).collect()
df = (
session.sql("show tables")
.select('"name"')
.filter(col('"name"') == table_name)
)
assert len(df.collect()) == 1
schema = df.schema
assert len(schema.fields) == 1
assert type(schema.fields[0].datatype) is StringType
assert schema.fields[0].name == '"name"'
finally:
Utils.drop_table(session, table_name)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="This is testing query generation",
run=False,
)
def test_non_select_query_composition_union(session):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
try:
session.sql(
f"create or replace temporary table {table_name} (num int)"
).collect()
df1 = session.sql("show tables")
df2 = session.sql("show tables")
df = df1.union(df2).select('"name"').filter(col('"name"') == table_name)
res = df.collect()
assert len(res) == 1
finally:
Utils.drop_table(session, table_name)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="This is testing query generation",
run=False,
)
def test_non_select_query_composition_unionall(session):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
try:
session.sql(
f"create or replace temporary table {table_name} (num int)"
).collect()
df1 = session.sql("show tables")
df2 = session.sql("show tables")
df = df1.union_all(df2).select('"name"').filter(col('"name"') == table_name)
res = df.collect()
assert len(res) == 2
finally:
Utils.drop_table(session, table_name)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="This is testing query generation",
run=False,
)
def test_non_select_query_composition_self_union(session):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
try:
session.sql(
f"create or replace temporary table {table_name} (num int)"
).collect()
df = session.sql("show tables")
union = df.union(df).select('"name"').filter(col('"name"') == table_name)
assert len(union.collect()) == 1
if session.sql_simplifier_enabled:
assert len(union._plan.queries) == 3
else:
assert len(union._plan.queries) == 2
finally:
Utils.drop_table(session, table_name)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="This is testing query generation",
run=False,
)
def test_non_select_query_composition_self_unionall(session):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
try:
session.sql(
f"create or replace temporary table {table_name} (num int)"
).collect()
df = session.sql("show tables")
union = df.union_all(df).select('"name"').filter(col('"name"') == table_name)
assert len(union.collect()) == 2
if session.sql_simplifier_enabled:
assert len(union._plan.queries) == 3
else:
assert len(union._plan.queries) == 2
finally:
Utils.drop_table(session, table_name)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="This is testing query generation",
run=False,
)
def test_only_use_result_scan_when_composing_queries(session):
df = session.sql("show tables")
assert len(df._plan.queries) == 1
assert df._plan.queries[0].sql == "show tables"
df2 = df.select('"name"')
assert len(df2._plan.queries) == 2
assert "RESULT_SCAN" in df2._plan.queries[-1].sql
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="This is testing query generation",
run=False,
)
def test_joins_on_result_scan(session):
df1 = session.sql("show tables").select(['"name"', '"kind"'])
df2 = session.sql("show tables").select(['"name"', '"rows"'])
result = df1.join(df2, '"name"')
result.collect() # no error
assert len(result.schema.fields) == 3
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="FEAT: function corr not supported",
)
def test_df_stat_corr(session):
with pytest.raises(SnowparkSQLException) as exec_info:
TestData.string1(session).stat.corr("a", "b")
assert "Numeric value 'a' is not recognized" in str(exec_info)
assert TestData.null_data2(session).stat.corr("a", "b") is None
assert (
TestData.null_data2(session).stat.corr(
"a", "b", statement_params={"SF_PARTNER": "FAKE_PARTNER"}
)
is None
)
assert TestData.double4(session).stat.corr("a", "b") is None
assert math.isnan(TestData.double3(session).stat.corr("a", "b"))
math.isclose(TestData.double2(session).stat.corr("a", "b"), 0.9999999999999991)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="FEAT: function covar_samp not supported",
)
def test_df_stat_cov(session):
with pytest.raises(SnowparkSQLException) as exec_info:
TestData.string1(session).stat.cov("a", "b")
assert "Numeric value 'a' is not recognized" in str(exec_info)
assert TestData.null_data2(session).stat.cov("a", "b") == 0
assert (
TestData.null_data2(session).stat.cov(
"a", "b", statement_params={"SF_PARTNER": "FAKE_PARTNER"}
)
== 0
)
assert TestData.double4(session).stat.cov("a", "b") is None
assert math.isnan(TestData.double3(session).stat.cov("a", "b"))
math.isclose(TestData.double2(session).stat.cov("a", "b"), 0.010000000000000037)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="FEAT: function approx_percentile_accumulate not supported",
)
def test_df_stat_approx_quantile(session):
assert TestData.approx_numbers(session).stat.approx_quantile("a", [0.5]) == [4.5]
assert TestData.approx_numbers(session).stat.approx_quantile(
"a", [0.5], statement_params={"SF_PARTNER": "FAKE_PARTNER"}
) == [4.5]
assert TestData.approx_numbers(session).stat.approx_quantile(
"a", [0, 0.1, 0.4, 0.6, 1]
) in (
[-0.5, 0.5, 3.5, 5.5, 9.5], # old behavior of Snowflake
[0.0, 0.9, 3.6, 5.3999999999999995, 9.0],
) # new behavior of Snowflake
with pytest.raises(SnowparkSQLException) as exec_info:
TestData.approx_numbers(session).stat.approx_quantile("a", [-1])
assert "Invalid value [-1.0] for function 'APPROX_PERCENTILE_ESTIMATE'" in str(
exec_info
)
with pytest.raises(SnowparkSQLException) as exec_info:
TestData.string1(session).stat.approx_quantile("a", [0.5])
assert "Numeric value 'test1' is not recognized" in str(exec_info)
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
Utils.create_table(session, table_name, "num int")
try:
assert session.table(table_name).stat.approx_quantile("num", [0.5])[0] is None
res = TestData.double2(session).stat.approx_quantile(["a", "b"], [0, 0.1, 0.6])
try:
Utils.assert_rows(
res,
[[0.05, 0.15000000000000002, 0.25], [0.45, 0.55, 0.6499999999999999]],
) # old behavior of Snowflake
except AssertionError:
try:
Utils.assert_rows(
res, [[0.1, 0.12000000000000001, 0.22], [0.5, 0.52, 0.62]]
) # new behavior of Snowflake
except AssertionError:
Utils.assert_rows(
res,
[
[0.05, 0.08000000000000002, 0.22999999999999998],
[0.45, 0.48, 0.6299999999999999],
],
)
# ApproxNumbers2 contains a column called T, which conflicts with tmpColumnName.
# This test demos that the query still works.
assert (
TestData.approx_numbers2(session).stat.approx_quantile("a", [0.5])[0] == 4.5
)
assert (
TestData.approx_numbers2(session).stat.approx_quantile("t", [0.5])[0] == 3.0
)
assert TestData.double2(session).stat.approx_quantile("a", []) == []
assert TestData.double2(session).stat.approx_quantile([], []) == []
assert TestData.double2(session).stat.approx_quantile([], [0.5]) == []
finally:
Utils.drop_table(session, table_name)
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="FEAT: RelationalGroupedDataFrame.Pivot not supported",
)
def test_df_stat_crosstab(session):
cross_tab = (
TestData.monthly_sales(session)
.stat.crosstab("empid", "month")
.sort(col("empid"))
.collect()
)
assert (
cross_tab[0]["EMPID"] == 1
and cross_tab[0]["'JAN'"] == 2
and cross_tab[0]["'FEB'"] == 2
and cross_tab[0]["'MAR'"] == 2
and cross_tab[0]["'APR'"] == 2
)
assert (
cross_tab[1]["EMPID"] == 2
and cross_tab[1]["'JAN'"] == 2
and cross_tab[1]["'FEB'"] == 2
and cross_tab[1]["'MAR'"] == 2
and cross_tab[1]["'APR'"] == 2
)
cross_tab_2 = (
TestData.monthly_sales(session)
.stat.crosstab("month", "empid")
.sort(col("month"))
.collect()
)
assert (
cross_tab_2[0]["MONTH"] == "APR"
and cross_tab_2[0]["CAST(1 AS NUMBER(38,0))"] == 2
and cross_tab_2[0]["CAST(2 AS NUMBER(38,0))"] == 2
)
assert (
cross_tab_2[1]["MONTH"] == "FEB"
and cross_tab_2[1]["CAST(1 AS NUMBER(38,0))"] == 2
and cross_tab_2[1]["CAST(2 AS NUMBER(38,0))"] == 2
)
assert (
cross_tab_2[2]["MONTH"] == "JAN"
and cross_tab_2[2]["CAST(1 AS NUMBER(38,0))"] == 2
and cross_tab_2[2]["CAST(2 AS NUMBER(38,0))"] == 2
)
assert (
cross_tab_2[3]["MONTH"] == "MAR"
and cross_tab_2[3]["CAST(1 AS NUMBER(38,0))"] == 2
and cross_tab_2[3]["CAST(2 AS NUMBER(38,0))"] == 2
)
cross_tab_3 = (
TestData.date1(session).stat.crosstab("a", "b").sort(col("a")).collect()
)
assert (
cross_tab_3[0]["A"] == date(2010, 12, 1)
and cross_tab_3[0]["CAST(1 AS NUMBER(38,0))"] == 0
and cross_tab_3[0]["CAST(2 AS NUMBER(38,0))"] == 1
)
assert (
cross_tab_3[1]["A"] == date(2020, 8, 1)
and cross_tab_3[1]["CAST(1 AS NUMBER(38,0))"] == 1
and cross_tab_3[1]["CAST(2 AS NUMBER(38,0))"] == 0
)
cross_tab_4 = (
TestData.date1(session).stat.crosstab("b", "a").sort(col("b")).collect()
)
assert (
cross_tab_4[0]["B"] == 1
and cross_tab_4[0]["TO_DATE('2020-08-01')"] == 1
and cross_tab_4[0]["TO_DATE('2010-12-01')"] == 0
), f"Incorrect cross_tab_4 row 1: {cross_tab_4}"
assert (
cross_tab_4[1]["B"] == 2
and cross_tab_4[1]["TO_DATE('2020-08-01')"] == 0
and cross_tab_4[1]["TO_DATE('2010-12-01')"] == 1
), f"Incorrect cross_tab_4 row 2: {cross_tab_4}"
cross_tab_5 = (
TestData.string7(session).stat.crosstab("a", "b").sort(col("a")).collect()
)
assert (
cross_tab_5[0]["A"] is None
and cross_tab_5[0]["CAST(1 AS NUMBER(38,0))"] == 0
and cross_tab_5[0]["CAST(2 AS NUMBER(38,0))"] == 1
)
assert (
cross_tab_5[1]["A"] == "str"
and cross_tab_5[1]["CAST(1 AS NUMBER(38,0))"] == 1
and cross_tab_5[1]["CAST(2 AS NUMBER(38,0))"] == 0
)
cross_tab_6 = (
TestData.string7(session).stat.crosstab("b", "a").sort(col("b")).collect()
)
assert (
cross_tab_6[0]["B"] == 1
and cross_tab_6[0]["'str'"] == 1
and cross_tab_6[0]["NULL"] == 0
)
assert (
cross_tab_6[1]["B"] == 2
and cross_tab_6[1]["'str'"] == 0
and cross_tab_6[1]["NULL"] == 0
)
cross_tab_7 = (
TestData.string7(session)
.stat.crosstab("b", "a", statement_params={"SF_PARTNER": "FAKE_PARTNER"})
.sort(col("B"))
.collect()
)
assert (
cross_tab_7[0]["B"] == 1
and cross_tab_7[0]["'str'"] == 1
and cross_tab_7[0]["NULL"] == 0
)
assert (
cross_tab_7[1]["B"] == 2
and cross_tab_7[1]["'str'"] == 0
and cross_tab_7[1]["NULL"] == 0
)
def test_df_stat_sampleBy(session):
sample_by = (
TestData.monthly_sales(session)
.stat.sample_by(col("empid"), {1: 0.0, 2: 1.0})
.collect()
)
expected_data = [
[2, 4500, "JAN"],
[2, 35000, "JAN"],
[2, 200, "FEB"],
[2, 90500, "FEB"],
[2, 2500, "MAR"],
[2, 9500, "MAR"],
[2, 800, "APR"],
[2, 4500, "APR"],
]
Utils.check_answer(sample_by, expected_data)
sample_by_2 = (
TestData.monthly_sales(session)
.stat.sample_by(col("month"), {"JAN": 1.0})
.collect()
)
expected_data_2 = [
[1, 10000, "JAN"],
[1, 400, "JAN"],
[2, 4500, "JAN"],
[2, 35000, "JAN"],
]
Utils.check_answer(sample_by_2, expected_data_2)
sample_by_3 = TestData.monthly_sales(session).stat.sample_by(col("month"), {})
schema_names = sample_by_3.schema.names
assert (
schema_names[0] == "EMPID"
and schema_names[1] == "AMOUNT"
and schema_names[2] == "MONTH"
)
assert len(sample_by_3.collect()) == 0
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="session.sql is not supported in local testing",
)
def test_df_stat_sampleBy_seed(session, caplog):
temp_table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
TestData.monthly_sales(session).write.save_as_table(
temp_table_name, table_type="temp", mode="overwrite"
)
df = session.table(temp_table_name)
# with seed, the result is deterministic and should be the same
sample_by_action = (
lambda df: df.stat.sample_by(col("empid"), {1: 0.5, 2: 0.5}, seed=1)
.sort(df.columns)
.collect()
)
result = sample_by_action(df)
for _ in range(3):
Utils.check_answer(sample_by_action(df), result)
# DataFrame doesn't work with seed
caplog.clear()
with caplog.at_level(logging.WARNING):
sample_by_action(TestData.monthly_sales(session))
assert "`seed` argument is ignored on `DataFrame` object" in caplog.text
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="FEAT: RelationalGroupedDataFrame.Pivot not supported",
)
@pytest.mark.skipif(IS_IN_STORED_PROC_LOCALFS, reason="Large result")
def test_df_stat_crosstab_max_column_test(session):
df1 = session.create_dataframe(
[
[Utils.random_alphanumeric_str(230), Utils.random_alphanumeric_str(230)]
for _ in range(1000)
],
schema=["a", "b"],
)
assert df1.stat.crosstab("a", "b").count() == 1000
df2 = session.create_dataframe(
[
[Utils.random_alphanumeric_str(230), Utils.random_alphanumeric_str(230)]
for _ in range(1001)
],
schema=["a", "b"],
)
with pytest.raises(SnowparkDataframeException) as exec_info:
df2.stat.crosstab("a", "b").collect()
assert (
"The number of distinct values in the second input column (1001) exceeds the maximum number of distinct values allowed (1000)"
in str(exec_info)
)
df3 = session.create_dataframe([[1, 1] for _ in range(1000)], schema=["a", "b"])
res_3 = df3.stat.crosstab("a", "b").collect()
assert len(res_3) == 1
assert res_3[0]["A"] == 1 and res_3[0]["CAST(1 AS NUMBER(38,0))"] == 1000
df4 = session.create_dataframe([[1, 1] for _ in range(1001)], schema=["a", "b"])
res_4 = df4.stat.crosstab("a", "b").collect()
assert len(res_4) == 1
assert res_4[0]["A"] == 1 and res_4[0]["CAST(1 AS NUMBER(38,0))"] == 1001
def test_select_star(session):
double2 = TestData.double2(session)
expected = TestData.double2(session).collect()
assert double2.select("*").collect() == expected
assert double2.select(double2.col("*")).collect() == expected
def test_first(session):
assert TestData.integer1(session).first() == Row(1)
assert TestData.null_data1(session).first() == Row(None)
assert TestData.integer1(session).filter(col("a") < 0).first() is None
res = TestData.integer1(session).first(2)
assert sorted(res, key=lambda x: x[0]) == [Row(1), Row(2)]
# return all elements
res = TestData.integer1(session).first(3)
assert sorted(res, key=lambda x: x[0]) == [Row(1), Row(2), Row(3)]
res = TestData.integer1(session).first(10)
assert sorted(res, key=lambda x: x[0]) == [Row(1), Row(2), Row(3)]
res = TestData.integer1(session).first(-10)
assert sorted(res, key=lambda x: x[0]) == [Row(1), Row(2), Row(3)]
@pytest.mark.skipif(IS_IN_STORED_PROC_LOCALFS, reason="Large result")
def test_sample_with_row_count(session):
"""Tests sample using n (row count)"""
row_count = 10000
df = session.range(row_count)
assert df.sample(n=0).count() == 0
assert len(df.sample(n=0).collect()) == 0
row_count_10_percent = int(row_count / 10)
assert df.sample(n=row_count_10_percent).count() == row_count_10_percent
assert df.sample(n=row_count).count() == row_count
assert df.sample(n=row_count + 10).count() == row_count
assert len(df.sample(n=row_count_10_percent).collect()) == row_count_10_percent
assert len(df.sample(n=row_count).collect()) == row_count
assert len(df.sample(n=row_count + 10).collect()) == row_count
@pytest.mark.skipif(IS_IN_STORED_PROC_LOCALFS, reason="Large result")
def test_sample_with_frac(session):
"""Tests sample using frac"""
row_count = 10000
df = session.range(row_count)
assert df.sample(frac=0.0).count() == 0
half_row_count = row_count * 0.5
assert (
abs(df.sample(frac=0.5).count() - half_row_count)
< half_row_count * SAMPLING_DEVIATION
)
assert df.sample(frac=1.0).count() == row_count
assert len(df.sample(frac=0.0).collect()) == 0
half_row_count = row_count * 0.5
assert (
abs(len(df.sample(frac=0.5).collect()) - half_row_count)
< half_row_count * SAMPLING_DEVIATION
)
assert len(df.sample(frac=1.0).collect()) == row_count
def test_sample_with_seed(session):
row_count = 10000
temp_table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
session.range(row_count).write.save_as_table(
temp_table_name, table_type="temporary"
)
df = session.table(temp_table_name)
try:
sample1 = df.sample(frac=0.1, seed=1).collect()
sample2 = df.sample(frac=0.1, seed=1).collect()
Utils.check_answer(sample1, sample2, sort=True)
finally:
Utils.drop_table(session, temp_table_name)
def test_sample_with_sampling_method(session):
"""sampling method actually has no impact on result. It has impact on performance."""
row_count = 10000
temp_table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
session.range(row_count).write.save_as_table(
temp_table_name, table_type="temporary"
)
df = session.table(temp_table_name)
try:
assert df.sample(frac=0.0, sampling_method="BLOCK").count() == 0
half_row_count = row_count * 0.5
assert (
abs(df.sample(frac=0.5, sampling_method="BLOCK").count() - half_row_count)
< half_row_count * SAMPLING_DEVIATION