-
Notifications
You must be signed in to change notification settings - Fork 9
/
test_dataframe_api.py
2882 lines (2297 loc) · 98.9 KB
/
test_dataframe_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: Apache-2.0
"""Tests for the Spark to Substrait Gateway server."""
from decimal import Decimal
import pyarrow as pa
import pyarrow.parquet as pq
import pyspark
import pytest
from hamcrest import assert_that, equal_to
from pyspark import Row
from pyspark.errors.exceptions.connect import SparkConnectGrpcException
from pyspark.sql.functions import (
bit_length,
broadcast,
btrim,
char_length,
character_length,
coalesce,
col,
concat,
concat_ws,
contains,
endswith,
equal_null,
expr,
greatest,
ifnull,
instr,
isnan,
isnotnull,
isnull,
lcase,
least,
left,
length,
lit,
locate,
lower,
lpad,
ltrim,
named_struct,
nanvl,
nullif,
nvl,
nvl2,
octet_length,
position,
regexp,
regexp_like,
repeat,
replace,
right,
rlike,
row_number,
rpad,
rtrim,
sqrt,
startswith,
struct,
substr,
substring,
trim,
try_sum,
ucase,
upper,
)
from pyspark.sql.types import DoubleType, IntegerType, StringType, StructField, StructType
from pyspark.sql.window import Window
from pyspark.testing import assertDataFrameEqual
from gateway.tests.conftest import find_tpch
from gateway.tests.plan_validator import utilizes_valid_plans
def create_parquet_table(spark_session, table_name: str, table: pa.Table):
"""Creates a parquet table from a PyArrow table and registers it to the session."""
pq.write_table(table, f"{table_name}.parquet")
table_df = spark_session.read.parquet(f"{table_name}.parquet")
table_df.createOrReplaceTempView(table_name)
return spark_session.table(table_name)
@pytest.fixture(autouse=True)
def mark_dataframe_tests_as_xfail(request):
"""Marks a subset of tests as expected to be fail."""
source = request.getfixturevalue("source")
originalname = request.keywords.node.originalname
if source == "gateway-over-datafusion":
if originalname in ["test_column_getfield", "test_column_getitem"]:
pytest.skip(reason="structs not handled")
elif originalname == "test_column_getitem":
pytest.skip(reason="maps and lists not handled")
elif source == "spark" and originalname == "test_subquery_alias":
pytest.xfail("Spark supports subquery_alias but everyone else does not")
if source != "spark" and originalname.startswith("test_unionbyname"):
pytest.skip(reason="unionByName not supported in Substrait")
if source != "spark" and originalname.startswith("test_exceptall"):
pytest.skip(reason="exceptAll not supported in Substrait")
if source == "gateway-over-datafusion" and originalname == "test_subtract":
pytest.skip(reason="subtract not supported")
if source == "gateway-over-datafusion" and originalname == "test_intersect":
pytest.skip(reason="intersect not supported")
if source == "gateway-over-datafusion" and originalname == "test_offset":
pytest.skip(reason="offset not supported")
if source == "gateway-over-datafusion" and originalname == "test_broadcast":
pytest.skip(reason="duplicate name problem with joins")
if source == "gateway-over-duckdb" and originalname == "test_coalesce":
pytest.skip(reason="missing Substrait mapping")
if source == "gateway-over-datafusion" and originalname == "test_coalesce":
pytest.skip(reason="datafusion cast error")
if source == "spark" and originalname == "test_isnan":
pytest.skip(reason="None not preserved")
if source == "gateway-over-datafusion" and originalname in [
"test_isnan",
"test_nanvl",
"test_least",
"test_greatest",
]:
pytest.skip(reason="missing Substrait mapping")
if source != "spark" and originalname == "test_expr":
pytest.skip(reason="SQL support needed in gateway")
if source != "spark" and originalname == "test_named_struct":
pytest.skip(reason="needs better type tracking in gateway")
if source == "spark" and originalname == "test_nullif":
pytest.skip(reason="internal Spark type error")
if source == "gateway-over-duckdb" and originalname == "test_nullif":
pytest.skip(reason="argument count issue in DuckDB mapping")
if source != "spark" and originalname in ["test_locate", "test_position"]:
pytest.skip(reason="no direct Substrait analog")
if source != "spark" and originalname in ["test_rint", "test_bround"]:
pytest.skip(reason="behavior option ignored")
if source != "spark" and originalname in ["test_negative", "test_negate", "test_positive"]:
pytest.skip(reason="custom implementation required")
if source == "gateway-over-datafusion" and originalname in ["test_sign", "test_signum"]:
pytest.skip(reason="missing implementation")
if source != "spark" and originalname in [
"test_cot",
"test_sec",
"test_ln",
"test_log",
"test_log10",
"test_log2",
"test_log1p",
]:
pytest.skip(reason="missing in Substrait")
if source == "gateway-over-datafusion" and originalname == "test_try_divide":
pytest.skip(reason="returns infinity instead of null")
if source == "gateway-over-duckdb" and originalname == "test_row_number":
pytest.skip(reason="window functions not yet implemented in DuckDB")
if source == "gateway-over-duckdb" and originalname == "test_atanh":
pytest.skip(reason="inf vs -inf difference")
if source == "gateway-over-duckdb" and originalname in ["test_union", "test_unionall"]:
pytest.skip(reason="distinct not handled properly")
if source == "gateway-over-duckdb" and originalname == "test_rollup":
pytest.skip(reason="rollup aggregation not yet implemented in gateway")
if source == "gateway-over-duckdb" and originalname == "test_cube":
pytest.skip(reason="cube aggregation not yet implemented in DuckDB")
if source == "gateway-over-duckdb" and originalname in ["test_column_getfield",
"test_struct_and_getfield"]:
pytest.skip(reason="fully named structs not yet tracked in gateway")
if source == "gateway-over-datafusion" and originalname in ["test_struct",
"test_struct_and_getfield"]:
pytest.skip(reason="nested expressions not supported")
# ruff: noqa: E712
class TestDataFrameAPI:
"""Tests of the dataframe side of SparkConnect."""
def test_collect(self, users_dataframe):
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.collect()
assert len(outcome) == 100
# pylint: disable=singleton-comparison
def test_filter(self, users_dataframe):
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.filter(col("paid_for_service") == True).collect()
assert len(outcome) == 29
def test_create_dataframe(self, spark_session, caplog):
expected = [
Row(age=1, name="Alice"),
Row(age=2, name="Bob"),
]
with utilizes_valid_plans(spark_session, caplog):
test_df = spark_session.createDataFrame([(1, "Alice"), (2, "Bob")], ["age", "name"])
assertDataFrameEqual(test_df.collect(), expected)
def test_create_dataframe_and_temp_view(self, spark_session, caplog):
expected = [
Row(age=1, name="Alice"),
Row(age=2, name="Bob"),
]
with utilizes_valid_plans(spark_session, caplog):
test_df = spark_session.createDataFrame([(1, "Alice"), (2, "Bob")], ["age", "name"])
test_df.createOrReplaceTempView("mytempview_from_df")
view_df = spark_session.table("mytempview_from_df")
assertDataFrameEqual(view_df.collect(), expected)
def test_create_dataframe_then_join(self, register_tpch_dataset, spark_session, caplog):
expected = [
Row(c_custkey=131074, name="Alice", c_name="Customer#000131074"),
Row(c_custkey=131075, name="Bob", c_name="Customer#000131075"),
]
with utilizes_valid_plans(spark_session, caplog):
customer_df = spark_session.table("customer")
test_df = spark_session.createDataFrame(
[(131074, "Alice"), (131075, "Bob")], ["c_custkey", "name"]
)
outcome = test_df.join(customer_df, on="c_custkey").collect()
assertDataFrameEqual(outcome, expected)
def test_dropna(self, spark_session, caplog):
schema = pa.schema({"name": pa.string(), "age": pa.int32()})
table = pa.Table.from_pydict(
{"name": [None, "Joe", "Sarah", None], "age": [99, None, 42, None]}, schema=schema
)
test_df = create_parquet_table(spark_session, "mytesttable", table)
with utilizes_valid_plans(test_df, caplog):
outcome = test_df.dropna().collect()
assert len(outcome) == 1
def test_dropna_by_name(self, spark_session, caplog):
schema = pa.schema({"name": pa.string(), "age": pa.int32()})
table = pa.Table.from_pydict(
{"name": [None, "Joe", "Sarah", None], "age": [99, None, 42, None]}, schema=schema
)
test_df = create_parquet_table(spark_session, "mytesttable", table)
with utilizes_valid_plans(test_df, caplog):
outcome = test_df.dropna(subset="name").collect()
assert len(outcome) == 2
def test_dropna_by_count(self, spark_session, caplog):
schema = pa.schema({"name": pa.string(), "age": pa.int32()})
table = pa.Table.from_pydict(
{"name": [None, "Joe", "Sarah", None], "age": [99, None, 42, None]}, schema=schema
)
test_df = create_parquet_table(spark_session, "mytesttable", table)
with utilizes_valid_plans(test_df, caplog):
outcome = test_df.dropna(thresh=1).collect()
assert len(outcome) == 3
# pylint: disable=singleton-comparison
def test_filter_with_show(self, users_dataframe, capsys):
expected = """+-------------+---------------+----------------+
| user_id| name|paid_for_service|
+-------------+---------------+----------------+
|user669344115| Joshua Brown| true|
|user282427709|Michele Carroll| true|
+-------------+---------------+----------------+
"""
with utilizes_valid_plans(users_dataframe):
users_dataframe.filter(col("paid_for_service") == True).limit(2).show()
outcome = capsys.readouterr().out
assert_that(outcome, equal_to(expected))
# pylint: disable=singleton-comparison
def test_filter_with_show_with_limit(self, users_dataframe, capsys):
expected = """+-------------+------------+----------------+
| user_id| name|paid_for_service|
+-------------+------------+----------------+
|user669344115|Joshua Brown| true|
+-------------+------------+----------------+
only showing top 1 row
"""
with utilizes_valid_plans(users_dataframe):
users_dataframe.filter(col("paid_for_service") == True).show(1)
outcome = capsys.readouterr().out
assert_that(outcome, equal_to(expected))
# pylint: disable=singleton-comparison
def test_filter_with_show_and_truncate(self, users_dataframe, capsys):
expected = """+----------+----------+----------------+
| user_id| name|paid_for_service|
+----------+----------+----------------+
|user669...|Joshua ...| true|
+----------+----------+----------------+
"""
users_dataframe.filter(col("paid_for_service") == True).limit(1).show(truncate=10)
outcome = capsys.readouterr().out
assert_that(outcome, equal_to(expected))
def test_count(self, users_dataframe):
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.count()
assert outcome == 100
def test_limit(self, users_dataframe):
expected = [
Row(user_id="user849118289", name="Brooke Jones", paid_for_service=False),
Row(user_id="user954079192", name="Collin Frank", paid_for_service=False),
]
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.limit(2).collect()
assertDataFrameEqual(outcome, expected)
def test_with_column(self, users_dataframe):
expected = [
Row(user_id="user849118289", name="Brooke Jones", paid_for_service=False),
]
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.withColumn("user_id", col("user_id")).limit(1).collect()
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == list(expected[0].asDict().keys())
def test_with_column_changed(self, users_dataframe):
expected = [
Row(user_id="user849118289", name="Brooke", paid_for_service=False),
]
with utilizes_valid_plans(users_dataframe):
outcome = (
users_dataframe.withColumn("name", substring(col("name"), 1, 6)).limit(1).collect()
)
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == list(expected[0].asDict().keys())
def test_with_column_added(self, users_dataframe):
expected = [
Row(
user_id="user849118289",
name="Brooke Jones",
paid_for_service=False,
not_paid_for_service=True,
),
]
with utilizes_valid_plans(users_dataframe):
outcome = (
users_dataframe.withColumn(
"not_paid_for_service", ~users_dataframe.paid_for_service
)
.limit(1)
.collect()
)
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == list(expected[0].asDict().keys())
def test_with_column_renamed(self, users_dataframe):
expected = [
Row(old_user_id="user849118289", name="Brooke Jones", paid_for_service=False),
]
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.withColumnRenamed("user_id", "old_user_id").limit(1).collect()
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == list(expected[0].asDict().keys())
def test_with_columns(self, users_dataframe):
expected = [
Row(
user_id="user849118289",
name="Brooke",
paid_for_service=False,
not_paid_for_service=True,
),
]
with utilizes_valid_plans(users_dataframe):
outcome = (
users_dataframe.withColumns(
{
"user_id": col("user_id"),
"name": substring(col("name"), 1, 6),
"not_paid_for_service": ~users_dataframe.paid_for_service,
}
)
.limit(1)
.collect()
)
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == list(expected[0].asDict().keys())
def test_with_columns_renamed(self, users_dataframe):
expected = [
Row(old_user_id="user849118289", old_name="Brooke Jones", paid_for_service=False),
]
with utilizes_valid_plans(users_dataframe):
outcome = (
users_dataframe.withColumnsRenamed({"user_id": "old_user_id", "name": "old_name"})
.limit(1)
.collect()
)
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == list(expected[0].asDict().keys())
def test_drop(self, users_dataframe):
expected = [
Row(name="Brooke Jones", paid_for_service=False),
]
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.drop(users_dataframe.user_id).limit(1).collect()
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == list(expected[0].asDict().keys())
def test_drop_by_name(self, users_dataframe):
expected = [
Row(name="Brooke Jones", paid_for_service=False),
]
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.drop("user_id").limit(1).collect()
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == list(expected[0].asDict().keys())
def test_drop_all(self, users_dataframe, source):
if source == "spark":
outcome = (
users_dataframe.drop("user_id")
.drop("name")
.drop("paid_for_service")
.limit(1)
.collect()
)
assert not outcome[0].asDict().keys()
else:
with pytest.raises(SparkConnectGrpcException):
users_dataframe.drop("user_id").drop("name").drop("paid_for_service").limit(
1
).collect()
def test_alias(self, users_dataframe):
expected = [
Row(foo="user849118289"),
]
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.select(col("user_id").alias("foo")).limit(1).collect()
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == ["foo"]
def test_subquery_alias(self, users_dataframe):
with pytest.raises(Exception) as exc_info:
users_dataframe.select(col("user_id")).alias("foo").limit(1).collect()
assert exc_info.match("Subquery alias relations are not yet implemented")
def test_name(self, users_dataframe):
expected = [
Row(foo="user849118289"),
]
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.select(col("user_id").name("foo")).limit(1).collect()
assertDataFrameEqual(outcome, expected)
assert list(outcome[0].asDict().keys()) == ["foo"]
def test_cast(self, users_dataframe):
expected = [
Row(user_id=849, name="Brooke Jones", paid_for_service=False),
]
with utilizes_valid_plans(users_dataframe):
outcome = (
users_dataframe.withColumn(
"user_id", substring(col("user_id"), 5, 3).cast("integer")
)
.limit(1)
.collect()
)
assertDataFrameEqual(outcome, expected)
def test_getattr(self, users_dataframe):
expected = [
Row(user_id="user669344115"),
Row(user_id="user849118289"),
Row(user_id="user954079192"),
]
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.select(users_dataframe.user_id).limit(3).collect()
assertDataFrameEqual(outcome, expected)
def test_getitem(self, users_dataframe):
expected = [
Row(user_id="user669344115"),
Row(user_id="user849118289"),
Row(user_id="user954079192"),
]
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.select(users_dataframe["user_id"]).limit(3).collect()
assertDataFrameEqual(outcome, expected)
def test_column_getfield(self, spark_session, caplog):
expected = [
Row(answer="b", answer2=1),
]
struct_type = pa.struct([("a", pa.int64()), ("b", pa.string())])
data = [{"a": 1, "b": "b"}]
struct_array = pa.array(data, type=struct_type)
table = pa.Table.from_arrays([struct_array], names=["r"])
df = create_parquet_table(spark_session, "mytesttable", table)
with utilizes_valid_plans(df):
outcome = df.select(df.r.getField("b"), df.r.a).collect()
assertDataFrameEqual(outcome, expected)
def test_column_getitem(self, spark_session):
expected = [
Row(answer=1, answer2="value"),
]
list_array = pa.array([[1, 2]], type=pa.list_(pa.int64()))
map_array = pa.array([{"key": "value"}], type=pa.map_(pa.string(), pa.string(), False))
table = pa.Table.from_arrays([list_array, map_array], names=["l", "d"])
df = create_parquet_table(spark_session, "mytesttable", table)
with utilizes_valid_plans(df):
outcome = df.select(df.l.getItem(0), df.d.getItem("key")).collect()
assertDataFrameEqual(outcome, expected)
def test_astype(self, users_dataframe):
expected = [
Row(user_id=849, name="Brooke Jones", paid_for_service=False),
]
with utilizes_valid_plans(users_dataframe):
outcome = (
users_dataframe.withColumn(
"user_id", substring(col("user_id"), 5, 3).astype("integer")
)
.limit(1)
.collect()
)
assertDataFrameEqual(outcome, expected)
def test_join(self, register_tpch_dataset, spark_session):
expected = [
Row(
n_nationkey=5,
n_name="ETHIOPIA",
n_regionkey=0,
n_comment="regular requests sleep carefull",
s_suppkey=2,
s_name="Supplier#000000002",
s_address="TRMhVHz3XiFuhapxucPo1",
s_nationkey=5,
s_phone="15-679-861-2259",
s_acctbal=Decimal("4032.68"),
s_comment=" the pending packages. furiously expres",
),
]
with utilizes_valid_plans(spark_session):
nation = spark_session.table("nation")
supplier = spark_session.table("supplier")
nat = nation.join(supplier, col("n_nationkey") == col("s_nationkey"))
outcome = nat.filter(col("s_suppkey") == 2).limit(1).collect()
assertDataFrameEqual(outcome, expected)
def test_crossjoin(self, register_tpch_dataset, spark_session):
expected = [
Row(n_nationkey=0, n_name="ALGERIA", s_name="Supplier#000000002"),
Row(n_nationkey=1, n_name="ARGENTINA", s_name="Supplier#000000002"),
Row(n_nationkey=2, n_name="BRAZIL", s_name="Supplier#000000002"),
Row(n_nationkey=3, n_name="CANADA", s_name="Supplier#000000002"),
Row(n_nationkey=4, n_name="EGYPT", s_name="Supplier#000000002"),
]
with utilizes_valid_plans(spark_session):
nation = spark_session.table("nation")
supplier = spark_session.table("supplier")
nat = nation.crossJoin(supplier).filter(col("s_suppkey") == 2)
outcome = nat.select("n_nationkey", "n_name", "s_name").limit(5).collect()
assertDataFrameEqual(outcome, expected)
def test_union(self, register_tpch_dataset, spark_session):
expected = [
Row(
n_nationkey=23,
n_name="UNITED KINGDOM",
n_regionkey=3,
n_comment="carefully pending courts sleep above the ironic, regular theo",
),
Row(
n_nationkey=23,
n_name="UNITED KINGDOM",
n_regionkey=3,
n_comment="carefully pending courts sleep above the ironic, regular theo",
),
]
with utilizes_valid_plans(spark_session):
nation = spark_session.table("nation")
outcome = nation.union(nation).filter(col("n_nationkey") == 23).collect()
assertDataFrameEqual(outcome, expected)
def test_union_distinct(self, register_tpch_dataset, spark_session):
expected = [
Row(
n_nationkey=23,
n_name="UNITED KINGDOM",
n_regionkey=3,
n_comment="carefully pending courts sleep above the ironic, regular theo",
),
]
with utilizes_valid_plans(spark_session):
nation = spark_session.table("nation")
outcome = nation.union(nation).distinct().filter(col("n_nationkey") == 23).collect()
assertDataFrameEqual(outcome, expected)
def test_unionall(self, register_tpch_dataset, spark_session):
expected = [
Row(
n_nationkey=23,
n_name="UNITED KINGDOM",
n_regionkey=3,
n_comment="carefully pending courts sleep above the ironic, regular theo",
),
Row(
n_nationkey=23,
n_name="UNITED KINGDOM",
n_regionkey=3,
n_comment="carefully pending courts sleep above the ironic, regular theo",
),
]
with utilizes_valid_plans(spark_session):
nation = spark_session.table("nation")
outcome = nation.unionAll(nation).filter(col("n_nationkey") == 23).collect()
assertDataFrameEqual(outcome, expected)
def test_exceptall(self, register_tpch_dataset, spark_session, caplog):
expected = [
Row(
n_nationkey=21,
n_name="VIETNAM",
n_regionkey=2,
n_comment="lly across the quickly even pinto beans. caref",
),
Row(
n_nationkey=21,
n_name="VIETNAM",
n_regionkey=2,
n_comment="lly across the quickly even pinto beans. caref",
),
Row(
n_nationkey=22,
n_name="RUSSIA",
n_regionkey=3,
n_comment="uctions. furiously unusual instructions sleep furiously ironic "
"packages. slyly ",
),
Row(
n_nationkey=22,
n_name="RUSSIA",
n_regionkey=3,
n_comment="uctions. furiously unusual instructions sleep furiously ironic "
"packages. slyly ",
),
Row(
n_nationkey=23,
n_name="UNITED KINGDOM",
n_regionkey=3,
n_comment="carefully pending courts sleep above the ironic, regular theo",
),
Row(
n_nationkey=24,
n_name="UNITED STATES",
n_regionkey=1,
n_comment="ly ironic requests along the slyly bold ideas hang after the "
"blithely special notornis; blithely even accounts",
),
Row(
n_nationkey=24,
n_name="UNITED STATES",
n_regionkey=1,
n_comment="ly ironic requests along the slyly bold ideas hang after the "
"blithely special notornis; blithely even accounts",
),
]
with utilizes_valid_plans(spark_session, caplog):
nation = spark_session.table("nation").filter(col("n_nationkey") > 20)
nation1 = nation.union(nation)
nation2 = nation.filter(col("n_nationkey") == 23)
outcome = nation1.exceptAll(nation2).collect()
assertDataFrameEqual(outcome, expected)
def test_distinct(self, spark_session):
expected = [
Row(a=1, b=10, c="a"),
Row(a=2, b=11, c="a"),
Row(a=3, b=12, c="a"),
Row(a=4, b=13, c="a"),
]
int1_array = pa.array([1, 2, 3, 3, 4], type=pa.int32())
int2_array = pa.array([10, 11, 12, 12, 13], type=pa.int32())
string_array = pa.array(["a", "a", "a", "a", "a"], type=pa.string())
table = pa.Table.from_arrays([int1_array, int2_array, string_array], names=["a", "b", "c"])
df = create_parquet_table(spark_session, "mytesttable1", table)
with utilizes_valid_plans(df):
outcome = df.distinct().collect()
assertDataFrameEqual(outcome, expected)
def test_drop_duplicates(self, spark_session):
expected = [
Row(a=1, b=10, c="a"),
Row(a=2, b=11, c="a"),
Row(a=3, b=12, c="a"),
Row(a=4, b=13, c="a"),
]
int1_array = pa.array([1, 2, 3, 3, 4], type=pa.int32())
int2_array = pa.array([10, 11, 12, 12, 13], type=pa.int32())
string_array = pa.array(["a", "a", "a", "a", "a"], type=pa.string())
table = pa.Table.from_arrays([int1_array, int2_array, string_array], names=["a", "b", "c"])
df = create_parquet_table(spark_session, "mytesttable2", table)
with utilizes_valid_plans(df):
outcome = df.dropDuplicates().collect()
assertDataFrameEqual(outcome, expected)
def test_colregex(self, spark_session, caplog):
expected = [
Row(a1=1, col2="a"),
Row(a1=2, col2="b"),
Row(a1=3, col2="c"),
]
int_array = pa.array([1, 2, 3], type=pa.int32())
string_array = pa.array(["a", "b", "c"], type=pa.string())
table = pa.Table.from_arrays(
[int_array, int_array, string_array, string_array], names=["a1", "c", "col", "col2"]
)
df = create_parquet_table(spark_session, "mytesttable3", table)
with utilizes_valid_plans(df, caplog):
outcome = df.select(df.colRegex("`(c.l|a)?[0-9]`")).collect()
assertDataFrameEqual(outcome, expected)
def test_subtract(self, register_tpch_dataset, spark_session):
expected = [
Row(
n_nationkey=21,
n_name="VIETNAM",
n_regionkey=2,
n_comment="lly across the quickly even pinto beans. caref",
),
Row(
n_nationkey=22,
n_name="RUSSIA",
n_regionkey=3,
n_comment="uctions. furiously unusual instructions sleep furiously "
"ironic packages. slyly ",
),
Row(
n_nationkey=24,
n_name="UNITED STATES",
n_regionkey=1,
n_comment="ly ironic requests along the slyly bold ideas hang after "
"the blithely special notornis; blithely even accounts",
),
]
with utilizes_valid_plans(spark_session):
nation = spark_session.table("nation").filter(col("n_nationkey") > 20)
nation1 = nation.union(nation)
nation2 = nation.filter(col("n_nationkey") == 23)
outcome = nation1.subtract(nation2).collect()
assertDataFrameEqual(outcome, expected)
def test_intersect(self, register_tpch_dataset, spark_session):
expected = [
Row(
n_nationkey=23,
n_name="UNITED KINGDOM",
n_regionkey=3,
n_comment="carefully pending courts sleep above the ironic, regular theo",
),
]
with utilizes_valid_plans(spark_session):
nation = spark_session.table("nation")
nation1 = nation.union(nation).filter(col("n_nationkey") >= 23)
nation2 = nation.filter(col("n_nationkey") <= 23)
outcome = nation1.intersect(nation2).collect()
assertDataFrameEqual(outcome, expected)
def test_unionbyname(self, spark_session):
expected = [
Row(a=1, b=2, c=3),
Row(a=4, b=5, c=6),
]
int1_array = pa.array([1], type=pa.int32())
int2_array = pa.array([2], type=pa.int32())
int3_array = pa.array([3], type=pa.int32())
table = pa.Table.from_arrays([int1_array, int2_array, int3_array], names=["a", "b", "c"])
int4_array = pa.array([4], type=pa.int32())
int5_array = pa.array([5], type=pa.int32())
int6_array = pa.array([6], type=pa.int32())
table2 = pa.Table.from_arrays([int4_array, int5_array, int6_array], names=["a", "b", "c"])
df = create_parquet_table(spark_session, "mytesttable1", table)
df2 = create_parquet_table(spark_session, "mytesttable2", table2)
with utilizes_valid_plans(df):
outcome = df.unionByName(df2).collect()
assertDataFrameEqual(outcome, expected)
def test_unionbyname_with_mismatched_columns(self, spark_session):
int1_array = pa.array([1], type=pa.int32())
int2_array = pa.array([2], type=pa.int32())
int3_array = pa.array([3], type=pa.int32())
table = pa.Table.from_arrays([int1_array, int2_array, int3_array], names=["a", "b", "c"])
int4_array = pa.array([4], type=pa.int32())
int5_array = pa.array([5], type=pa.int32())
int6_array = pa.array([6], type=pa.int32())
table2 = pa.Table.from_arrays([int4_array, int5_array, int6_array], names=["b", "c", "d"])
df = create_parquet_table(spark_session, "mytesttable1", table)
df2 = create_parquet_table(spark_session, "mytesttable2", table2)
with pytest.raises(pyspark.errors.exceptions.captured.AnalysisException):
df.unionByName(df2).collect()
def test_unionbyname_with_missing_columns(self, spark_session):
expected = [
Row(a=1, b=2, c=3, d=None),
Row(a=None, b=4, c=5, d=6),
]
int1_array = pa.array([1], type=pa.int32())
int2_array = pa.array([2], type=pa.int32())
int3_array = pa.array([3], type=pa.int32())
table = pa.Table.from_arrays([int1_array, int2_array, int3_array], names=["a", "b", "c"])
int4_array = pa.array([4], type=pa.int32())
int5_array = pa.array([5], type=pa.int32())
int6_array = pa.array([6], type=pa.int32())
table2 = pa.Table.from_arrays([int4_array, int5_array, int6_array], names=["b", "c", "d"])
df = create_parquet_table(spark_session, "mytesttable1", table)
df2 = create_parquet_table(spark_session, "mytesttable2", table2)
with utilizes_valid_plans(df):
outcome = df.unionByName(df2, allowMissingColumns=True).collect()
assertDataFrameEqual(outcome, expected)
def test_between(self, register_tpch_dataset, spark_session):
expected = [
Row(n_name="ALGERIA", is_between=False),
Row(n_name="ARGENTINA", is_between=False),
Row(n_name="BRAZIL", is_between=False),
Row(n_name="CANADA", is_between=False),
Row(n_name="EGYPT", is_between=True),
]
with utilizes_valid_plans(spark_session):
nation = spark_session.table("nation")
outcome = (
nation.select(nation.n_name, nation.n_regionkey.between(2, 4).name("is_between"))
.limit(5)
.collect()
)
assertDataFrameEqual(outcome, expected)
def test_eqnullsafe(self, spark_session):
expected = [
Row(a=None, b=False, c=True),
Row(a=True, b=True, c=False),
]
expected2 = [
Row(a=False, b=False, c=True),
Row(a=False, b=True, c=False),
Row(a=True, b=False, c=False),
]
string_array = pa.array(["foo", None, None], type=pa.string())
float_array = pa.array([float("NaN"), 42.0, None], type=pa.float64())
table = pa.Table.from_arrays([string_array, float_array], names=["s", "f"])
df = create_parquet_table(spark_session, "mytesttable", table)
with utilizes_valid_plans(df):
outcome = (
df.select(df.s == "foo", df.s.eqNullSafe("foo"), df.s.eqNullSafe(None))
.limit(2)
.collect()
)
assertDataFrameEqual(outcome, expected)
outcome = df.select(
df.f.eqNullSafe(None), df.f.eqNullSafe(float("NaN")), df.f.eqNullSafe(42.0)
).collect()
assertDataFrameEqual(outcome, expected2)
def test_bitwise(self, spark_session):
expected = [
Row(a=0, b=42, c=42),
Row(a=42, b=42, c=0),
Row(a=8, b=255, c=247),
Row(a=None, b=None, c=None),
]
int_array = pa.array([221, 0, 42, None], type=pa.int64())
table = pa.Table.from_arrays([int_array], names=["i"])
df = create_parquet_table(spark_session, "mytesttable", table)
with utilizes_valid_plans(df):
outcome = df.select(
df.i.bitwiseAND(42), df.i.bitwiseOR(42), df.i.bitwiseXOR(42)
).collect()
assertDataFrameEqual(outcome, expected)
def test_first(self, users_dataframe):
expected = Row(user_id="user012015386", name="Kelly Mcdonald", paid_for_service=False)
with utilizes_valid_plans(users_dataframe):
outcome = users_dataframe.sort("user_id").first()
assert outcome == expected
def test_head(self, users_dataframe):
expected = [
Row(user_id="user012015386", name="Kelly Mcdonald", paid_for_service=False),
Row(user_id="user041132632", name="Tina Atkinson", paid_for_service=False),
Row(user_id="user056872864", name="Kenneth Castro", paid_for_service=False),
]