-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathutils.py
More file actions
1826 lines (1585 loc) · 60.2 KB
/
utils.py
File metadata and controls
1826 lines (1585 loc) · 60.2 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 functools
import math
import os
import platform
import random
import string
import uuid
from contextlib import contextmanager
from datetime import date, datetime, time, timedelta, timezone
from decimal import Decimal
from typing import Dict, List, NamedTuple, Optional, Union
from threading import Thread
from unittest import mock
import re
import sys
import pytest
import pytz
from snowflake.connector.constants import FIELD_ID_TO_NAME
from snowflake.snowpark import DataFrame, Row, Session
from snowflake.snowpark._internal import utils
from snowflake.snowpark._internal.analyzer.analyzer_utils import (
quote_name_without_upper_casing,
)
from snowflake.snowpark._internal.type_utils import convert_sf_to_sp_type
from snowflake.snowpark._internal.utils import (
TempObjectType,
is_in_stored_procedure,
quote_name,
generate_random_alphanumeric,
)
from snowflake.snowpark.functions import (
array_construct,
col,
lit,
object_construct,
parse_json,
parse_xml,
to_array,
to_binary,
to_date,
to_decimal,
to_double,
to_object,
to_time,
to_timestamp,
to_timestamp_ltz,
to_timestamp_ntz,
to_timestamp_tz,
to_variant,
)
from snowflake.snowpark.mock._connection import MockServerConnection
from snowflake.snowpark.types import (
ArrayType,
BinaryType,
BooleanType,
DataType,
DateType,
DecimalType,
DoubleType,
GeographyType,
GeometryType,
IntegerType,
LongType,
MapType,
StringType,
StructField,
StructType,
TimestampTimeZone,
TimestampType,
TimeType,
VariantType,
)
IS_WINDOWS = platform.system() == "Windows"
IS_MACOS = platform.system() == "Darwin"
IS_LINUX = platform.system() == "Linux"
IS_UNIX = IS_LINUX or IS_MACOS
IS_IN_STORED_PROC = is_in_stored_procedure()
IS_NOT_ON_GITHUB = os.getenv("GITHUB_ACTIONS") != "true"
# this env variable is set in regression test
IS_IN_STORED_PROC_LOCALFS = IS_IN_STORED_PROC and os.getenv("IS_LOCAL_FS")
RUNNING_ON_GH = os.getenv("GITHUB_ACTIONS") == "true"
RUNNING_ON_JENKINS = "JENKINS_HOME" in os.environ
TEST_SCHEMA = f"GH_JOB_{(str(uuid.uuid4()).replace('-', '_'))}"
if RUNNING_ON_JENKINS:
TEST_SCHEMA = f"JENKINS_JOB_{(str(uuid.uuid4()).replace('-', '_'))}"
# SNOW-1348805: Structured types have not been rolled out to all accounts yet.
# Once rolled out this should be updated to include all accounts.
STRUCTURED_TYPE_ENVIRONMENTS = {"SFCTEST0_AWS_US_WEST_2", "SNOWPARK_PYTHON_TEST"}
ICEBERG_ENVIRONMENTS = {"SFCTEST0_AWS_US_WEST_2"}
STRUCTURED_TYPE_PARAMETERS = {
"ENABLE_STRUCTURED_TYPES_IN_FDN_TABLES",
"ENABLE_STRUCTURED_TYPES_IN_CLIENT_RESPONSE",
"ENABLE_STRUCTURED_TYPES_NATIVE_ARROW_FORMAT",
"FORCE_ENABLE_STRUCTURED_TYPES_NATIVE_ARROW_FORMAT",
"IGNORE_CLIENT_VESRION_IN_STRUCTURED_TYPES_RESPONSE",
}
def current_account(session):
return session.sql("select CURRENT_ACCOUNT_NAME()").collect()[0][0].upper()
def structured_types_supported(session, local_testing_mode):
if local_testing_mode:
return True
return current_account(session) in STRUCTURED_TYPE_ENVIRONMENTS
def iceberg_supported(session, local_testing_mode):
if local_testing_mode:
return False
return current_account(session) in ICEBERG_ENVIRONMENTS
@contextmanager
def structured_types_enabled_session(session):
for param in STRUCTURED_TYPE_PARAMETERS:
session.sql(f"alter session set {param}=true").collect()
with mock.patch("snowflake.snowpark.context._use_structured_type_semantics", True):
yield session
for param in STRUCTURED_TYPE_PARAMETERS:
session.sql(f"alter session unset {param}").collect()
def running_on_public_ci() -> bool:
"""Whether tests are currently running on one of our public CIs."""
return RUNNING_ON_GH
def running_on_jenkins() -> bool:
"""Whether tests are currently running on a Jenkins node."""
return RUNNING_ON_JENKINS
def multithreaded_run(num_threads: int = 5) -> None:
"""When multithreading_mode is enabled, run the decorated test function in multiple threads."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
all_threads = []
for _ in range(num_threads):
job = Thread(target=func, args=args, kwargs=kwargs)
all_threads.append(job)
job.start()
for thread in all_threads:
thread.join()
return wrapper
return decorator
class Utils:
@staticmethod
def escape_path(path):
if IS_WINDOWS:
return path.replace("\\", "\\\\")
else:
return path
@staticmethod
def random_name_for_temp_object(object_type: TempObjectType) -> str:
return utils.random_name_for_temp_object(object_type)
@staticmethod
def random_alphanumeric_str(n: int):
return "".join(
random.choice(
string.ascii_uppercase + string.ascii_lowercase + string.digits
)
for _ in range(n)
)
@staticmethod
def random_stage_name() -> str:
return Utils.random_name_for_temp_object(TempObjectType.STAGE)
@staticmethod
def random_function_name():
return Utils.random_name_for_temp_object(TempObjectType.FUNCTION)
@staticmethod
def random_view_name():
return Utils.random_name_for_temp_object(TempObjectType.VIEW)
@staticmethod
def random_table_name() -> str:
return Utils.random_name_for_temp_object(TempObjectType.TABLE)
@staticmethod
def create_table(
session: "Session", name: str, schema: str, is_temporary: bool = False
):
session._run_query(
f"create or replace {'temporary' if is_temporary else ''} table {name} ({schema})"
)
@staticmethod
def create_schema(session: "Session", name: str, is_temporary: bool = False):
session._run_query(
f"create or replace {'temporary' if is_temporary else ''} schema {name}"
)
@staticmethod
def create_stage(session: "Session", name: str, is_temporary: bool = True):
if isinstance(session._conn, MockServerConnection):
# no-op in local testing
return
session._run_query(
f"create or replace {'temporary' if is_temporary else ''} stage {quote_name(name)}"
)
@staticmethod
def drop_stage(session: "Session", name: str):
if isinstance(session._conn, MockServerConnection):
# no-op in local testing
return
session._run_query(f"drop stage if exists {quote_name(name)}")
@staticmethod
def drop_table(session: "Session", name: str):
if isinstance(session._conn, MockServerConnection):
session.table(name).drop_table()
else:
session._run_query(f"drop table if exists {quote_name(name)}")
@staticmethod
def drop_dynamic_table(session: "Session", name: str):
session._run_query(f"drop dynamic table if exists {quote_name(name)}")
@staticmethod
def drop_view(session: "Session", name: str):
session._run_query(f"drop view if exists {quote_name(name)}")
@staticmethod
def drop_function(session: "Session", name: str):
session._run_query(f"drop function if exists {name}")
@staticmethod
def drop_procedure(session: "Session", name: str):
session._run_query(f"drop procedure if exists {name}")
@staticmethod
def drop_schema(session: "Session", name: str):
session._run_query(f"drop schema if exists {name}")
@staticmethod
def drop_database(session: "Session", name: str):
session._run_query(f"drop database if exists {name}")
@staticmethod
def unset_query_tag(session: "Session"):
session.query_tag = None
@staticmethod
def upload_to_stage(
session: "Session", stage_name: str, filename: str, compress: bool
):
session.file.put(
local_file_name=filename, stage_location=stage_name, auto_compress=compress
)
@staticmethod
def is_schema_same(
schema_a: StructType, schema_b: StructType, case_sensitive=True
) -> None:
if case_sensitive:
assert str(schema_a) == str(schema_b), "str(schema) mismatch"
if len(schema_a.fields) != len(schema_b.fields):
raise AssertionError("field length mismatch")
for field_a, field_b in zip(schema_a, schema_b):
if field_a.name.lower() != field_b.name.lower():
raise AssertionError(f"name mismatch {field_a.name} != {field_b.name}")
if repr(field_a.datatype) != repr(field_b.datatype):
raise AssertionError(
f"datatype mismatch {field_a.datatype} != {field_b.datatype} for {field_a.name}"
)
if field_a.nullable != field_b.nullable:
raise AssertionError(
f"nullable mismatch {field_a.nullable} != {field_b.nullable} for {field_a.name}"
)
@staticmethod
def equals_ignore_case(a: str, b: str) -> bool:
return a.lower() == b.lower()
@classmethod
def random_temp_schema(cls):
return f"SCHEMA_{cls.random_alphanumeric_str(10)}"
@classmethod
def random_temp_database(cls):
return f"DATABASE_{cls.random_alphanumeric_str(10)}"
@classmethod
def get_fully_qualified_temp_schema(cls, session: Session):
return f"{session.get_current_database()}.{cls.random_temp_schema()}"
@staticmethod
def assert_rows(actual_rows, expected_rows, float_equality_threshold=0.0):
assert len(actual_rows) == len(
expected_rows
), f"row count is different. Expected {len(expected_rows)}. Actual {len(actual_rows)}"
for row_index in range(0, len(expected_rows)):
expected_row = expected_rows[row_index]
actual_row = actual_rows[row_index]
assert len(actual_row) == len(
expected_row
), f"column count for row {row_index + 1} is different. Expected {len(expected_row)}. Actual {len(actual_row)}"
for column_index in range(0, len(expected_row)):
expected_value = expected_row[column_index]
actual_value = actual_row[column_index]
if isinstance(expected_value, float):
if math.isnan(expected_value):
assert math.isnan(
actual_value
), f"Expected NaN. Actual {actual_value}"
elif float_equality_threshold > 0:
assert actual_value == pytest.approx(
expected_value, abs=float_equality_threshold
)
else:
assert math.isclose(
actual_value, expected_value
), f"Expected {expected_value}. Actual {actual_value}"
elif isinstance(expected_value, list):
if len(expected_value) > 0 and any(
[isinstance(v, float) for v in expected_value]
):
assert actual_value == pytest.approx(
expected_value
), f"Mismatch on row {row_index} at column {column_index}. Expected {expected_value}. Actual {actual_value}"
else:
assert (
actual_value == expected_value
), f"Mismatch on row {row_index} at column {column_index}. Expected {expected_value}. Actual {actual_value}"
else:
assert (
actual_value == expected_value
), f"Mismatch on row {row_index} at column {column_index}. Expected {expected_value}. Actual {actual_value}"
@staticmethod
def get_sorted_rows(rows: List[Row]) -> List[Row]:
def compare_rows(row1, row2):
assert len(row1) == len(
row2
), "rows1 and row2 have different length so they're not comparable."
for value1, value2 in zip(row1, row2):
if value1 == value2:
continue
if value1 is None:
return -1
elif value2 is None:
return 1
elif value1 > value2:
return 1
elif value1 < value2:
return -1
return 0
sort_key = functools.cmp_to_key(compare_rows)
return sorted(rows, key=sort_key)
@staticmethod
def check_answer(
actual: Union[Row, List[Row], DataFrame],
expected: Union[Row, List[Row], DataFrame],
sort=True,
statement_params: Optional[Dict[str, str]] = None,
float_equality_threshold=0.0,
) -> None:
# Check that statement_params are passed as Dict[str, str].
assert statement_params is None or (
isinstance(statement_params, dict)
and all(
isinstance(k, str) and isinstance(v, str)
for k, v in statement_params.items()
)
)
def get_rows(input_data: Union[Row, List[Row], DataFrame]):
if isinstance(input_data, list):
rows = input_data
elif isinstance(input_data, DataFrame):
rows = input_data.collect(statement_params=statement_params)
elif isinstance(input_data, Row):
rows = [input_data]
else:
raise TypeError(
"input_data must be a DataFrame, a list of Row objects or a Row object"
)
# Strip column names to make errors more concise
rows = [Row(*list(x)) for x in rows]
return rows
actual_rows = get_rows(actual)
expected_rows = get_rows(expected)
if sort:
sorted_expected_rows = Utils.get_sorted_rows(expected_rows)
sorted_actual_rows = Utils.get_sorted_rows(actual_rows)
Utils.assert_rows(
sorted_actual_rows, sorted_expected_rows, float_equality_threshold
)
else:
Utils.assert_rows(actual_rows, expected_rows, float_equality_threshold)
@staticmethod
def verify_schema(
sql: str,
expected_schema: StructType,
session: Session,
max_string_size: int = None,
) -> None:
session._run_query(sql)
result_meta = session._conn._cursor.description
assert len(result_meta) == len(expected_schema.fields)
for meta, field in zip(result_meta, expected_schema.fields):
assert (
quote_name_without_upper_casing(meta.name)
== field.column_identifier.quoted_name
)
assert meta.is_nullable == field.nullable
sp_type = convert_sf_to_sp_type(
FIELD_ID_TO_NAME[meta.type_code],
meta.precision,
meta.scale,
meta.internal_size,
max_string_size or session._conn.max_string_size,
)
assert (
sp_type == field.datatype
), f"{sp_type=} is not equal to {field.datatype=}"
@staticmethod
def is_active_transaction(session: Session) -> bool:
# `SELECT CURRENT_TRANSACTION()` returns a valid txn ID if there is active txn or NULL otherwise
return session.sql("SELECT CURRENT_TRANSACTION()").collect()[0][0] is not None
@staticmethod
def assert_table_type(session: Session, table_name: str, table_type: str) -> None:
table_info = session.sql(f"show tables like '{table_name}'").collect()
if not table_type:
expected_table_kind = "TABLE"
elif table_type == "temp":
expected_table_kind = "TEMPORARY"
else:
expected_table_kind = table_type.upper()
assert table_info[0]["kind"] == expected_table_kind
@staticmethod
def assert_rows_count(data: DataFrame, row_number: int):
row_counter = len(data.collect())
assert (
row_counter == row_number
), f"Expect {row_number} rows, Got {row_counter} instead"
@staticmethod
def assert_executed_with_query_tag(
session: Session, query_tag: str, local_testing_mode: bool = False
) -> None:
# inside the stored proc information_schema.query_history_by_session() is not accessible
# which leads to "Requested information on the current user is not accessible in stored procedure."
if local_testing_mode or IS_IN_STORED_PROC:
return
query_details = session.sql(
f"select * from table(information_schema.query_history_by_session()) where QUERY_TAG='{query_tag}'"
)
assert (
len(query_details.collect()) > 0
), f"query tag '{query_tag}' not present in query history for given session"
@staticmethod
def normalize_sql(sql_query: str) -> str:
# replace all whitespace with a single space
stripped_sql = re.sub(r"\s+", " ", sql_query).strip()
# remove space followed by parenthesis
stripped_sql = re.sub(r"\(\s+", "(", stripped_sql)
stripped_sql = re.sub(r"\s+\)", ")", stripped_sql)
return stripped_sql
@staticmethod
def write_test_msg(
write_mode: str, file_location: str, test_msg: str = None
) -> tuple[Union[str, bytes], str]:
"""
Generates a test message or uses the provided message and writes it to the specified file location.
Used to create a test message for reading in SnowflakeFile tests.
Returns a test message and the file location that the message was written to.
"""
file_location = os.path.join(
file_location, f"{generate_random_alphanumeric()}.txt"
)
if test_msg is None:
test_msg = generate_random_alphanumeric()
if write_mode == "wb":
test_msg = test_msg.encode()
encoding = "utf-8" if write_mode == "w" else None
with open(file_location, write_mode, encoding=encoding) as f:
f.write(test_msg)
return test_msg, file_location
@staticmethod
def write_test_msg_to_stage(
write_mode: str,
file_location: str,
tmp_stage: str,
session: Session,
test_msg: str = None,
) -> tuple[Union[str, bytes], str]:
"""
Generates a test message or uses the provided message and writes it to the specified file location on a stage.
Used to create a test message for reading in SnowflakeFile tests involving stages.
Returns a test message and the file location that the message was written to.
"""
test_msg, file_location = Utils.write_test_msg(
write_mode, file_location, test_msg
)
Utils.upload_to_stage(session, f"@{tmp_stage}", file_location, compress=False)
file_location = Utils.get_file_name(file_location)
return test_msg, f"@{tmp_stage}/{file_location}"
@staticmethod
def get_file_name(file_location: str) -> str:
"""
Gets the file name from the file location.
Handles both Windows and Unix-style paths.
"""
if "\\" in file_location:
file_location = file_location.split("\\")[-1]
else:
file_location = file_location.split("/")[-1]
return file_location
@staticmethod
def generate_and_write_lines(
num_lines: int,
write_mode: str,
file_location: str,
msg: Union[str, bytes] = None,
) -> tuple[list[Union[str, bytes]], str]:
"""
Generates a list of test messages and writes them to the specified file location.
Returns the list of messages and the file location that the messages were written to.
"""
file_location = os.path.join(
file_location, f"{generate_random_alphanumeric()}.txt"
)
lines = [
f"{generate_random_alphanumeric()}\n" if msg is None else f"{msg}\n"
for _ in range(num_lines)
]
if write_mode == "wb":
lines = [line.encode() for line in lines]
encoding = "utf-8" if write_mode == "w" else None
with open(file_location, write_mode, encoding=encoding) as f:
for line in lines:
f.write(line)
return lines, file_location
@staticmethod
def generate_and_write_lines_to_stage(
num_lines: int,
write_mode: str,
file_location: str,
tmp_stage: str,
session: Session,
msg: Union[str, bytes] = None,
) -> tuple[list[Union[str, bytes]], str]:
"""
Generates a list of test messages and writes them to the specified file location on a stage.
Returns the list of messages and the file location that the messages were written to.
"""
lines, file_location = Utils.generate_and_write_lines(
num_lines, write_mode, file_location, msg
)
Utils.upload_to_stage(session, f"@{tmp_stage}", file_location, compress=False)
file_location = Utils.get_file_name(file_location)
return lines, f"@{tmp_stage}/{file_location}"
@staticmethod
def get_current_line_number_sys():
"""Returns the current line number of the caller using sys._getframe()."""
return sys._getframe(1).f_lineno
class TestData:
__test__ = (
False # silence pytest warnings for trying to collect this class as a test
)
class Data(NamedTuple):
num: int
bool: bool
str: str
class Data2(NamedTuple):
a: int
b: int
class Data3(NamedTuple):
a: int
b: Optional[int]
class Data4(NamedTuple):
key: int
value: str
class LowerCaseData(NamedTuple):
n: int
l: str
class UpperCaseData(NamedTuple):
N: int
L: str
NullInt = NamedTuple("NullInts", [("a", Optional[int])])
class Number1(NamedTuple):
K: int
v1: float
v2: float
class Number2(NamedTuple):
x: int
y: int
z: int
class MonthlySales(NamedTuple):
empid: int
amount: int
month: str
@classmethod
def test_data1(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[cls.Data(1, True, "a"), cls.Data(2, False, "b")]
)
@classmethod
def test_data2(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[
cls.Data2(1, 1),
cls.Data2(1, 2),
cls.Data2(2, 1),
cls.Data2(2, 2),
cls.Data2(3, 1),
cls.Data2(3, 2),
]
)
@classmethod
def test_data3(cls, session: "Session") -> DataFrame:
return session.create_dataframe([cls.Data3(1, None), cls.Data3(2, 2)])
@classmethod
def test_data4(cls, session: "Session") -> DataFrame:
return session.create_dataframe([cls.Data4(i, str(i)) for i in range(1, 101)])
@classmethod
def lower_case_data(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[
cls.LowerCaseData(1, "a"),
cls.LowerCaseData(2, "b"),
cls.LowerCaseData(3, "c"),
cls.LowerCaseData(4, "d"),
]
)
@classmethod
def upper_case_data(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[
cls.UpperCaseData(1, "A"),
cls.UpperCaseData(2, "B"),
cls.UpperCaseData(3, "C"),
cls.UpperCaseData(4, "D"),
cls.UpperCaseData(5, "E"),
cls.UpperCaseData(6, "F"),
]
)
@classmethod
def null_ints(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[cls.NullInt(1), cls.NullInt(2), cls.NullInt(3), cls.NullInt(None)]
)
@classmethod
def all_nulls(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[cls.NullInt(None), cls.NullInt(None), cls.NullInt(None), cls.NullInt(None)]
)
@classmethod
def null_data1(cls, session: "Session") -> DataFrame:
return session.create_dataframe([[None], [2], [1], [3], [None]], schema=["a"])
@classmethod
def null_data2(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[
[1, 2, 3],
[None, 2, 3],
[None, None, 3],
[None, None, None],
[1, None, 3],
[1, None, None],
[1, 2, None],
],
schema=["a", "b", "c"],
)
@classmethod
def null_data3(cls, session: "Session", local_testing_mode=False) -> DataFrame:
return (
session.sql(
"select * from values(1.0, 1, true, 'a'),('NaN'::Double, 2, null, 'b'),"
"(null, 3, false, null), (4.0, null, null, 'd'), (null, null, null, null),"
"('NaN'::Double, null, null, null) as T(flo, int, boo, str)"
)
if not local_testing_mode
else session.create_dataframe(
[
[1.0, 1, True, "a"],
[math.nan, 2, None, "b"],
[None, 3, False, None],
[4.0, None, None, "d"],
[None, None, None, None],
[math.nan, None, None, None],
],
schema=["flo", "int", "boo", "str"],
)
)
@classmethod
def null_data4(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[
[Decimal(1), None],
[None, Decimal(2)],
]
).to_df(["a", "b"])
@classmethod
def integer1(cls, session: "Session") -> DataFrame:
return session.create_dataframe([[1], [2], [3]]).to_df(["a"])
@classmethod
def double1(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[[1.111], [2.222], [3.333]],
schema=StructType([StructField("a", DecimalType(scale=3))]),
)
@classmethod
def double2(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[[0.1, 0.5], [0.2, 0.6], [0.3, 0.7]], schema=["a", "b"]
)
@classmethod
def double3(cls, session: "Session", local_testing_mode=False) -> DataFrame:
return (
session.sql(
"select * from values(1.0, 1),('NaN'::Double, 2),(null, 3),"
"(4.0, null), (null, null), ('NaN'::Double, null) as T(a, b)"
)
if not local_testing_mode
else session.create_dataframe(
[
[1.0, 1],
[math.nan, 2],
[None, 3],
[4.0, None],
[None, None],
[math.nan, None],
],
schema=["a", "b"],
)
)
@classmethod
def nan_data1(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[(1.2,), (math.nan,), (None,), (2.3,)], schema=["a"]
)
@classmethod
def double4(cls, session: "Session") -> DataFrame:
return session.sql("select * from values(1.0, 1) as T(a, b)")
@classmethod
def duplicated_numbers(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[
(3,),
(2,),
(1,),
(3,),
(2,),
],
schema=["a"],
)
@classmethod
def approx_numbers(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [0]], schema=["a"]
)
@classmethod
def approx_numbers2(cls, session: "Session") -> DataFrame:
return session.sql(
"select * from values(1, 1),(2, 1),(3, 3),(4, 3),(5, 3),(6, 3),(7, 3),"
+ "(8, 5),(9, 5),(0, 5) as T(a, T)"
)
@classmethod
def string1(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[["test1", "a"], ["test2", "b"], ["test3", "c"]],
schema=StructType(
[StructField("a", StringType(5)), StructField("b", StringType(1))]
),
)
@classmethod
def string2(cls, session: "Session") -> DataFrame:
return session.create_dataframe([["asdFg"], ["qqq"], ["Qw"]], schema=["a"])
@classmethod
def string3(cls, session: "Session") -> DataFrame:
return session.create_dataframe([[" abcba "], [" a12321a "]], schema=["a"])
@classmethod
def string4(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[["apple"], ["banana"], ["peach"]], schema=["a"]
)
@classmethod
def string5(cls, session: "Session") -> DataFrame:
return session.create_dataframe([["1,2,3,4,5"]], schema=["a"])
@classmethod
def string6(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[["1,2,3,4,5", ","], ["1 2 3 4 5", " "]], schema=["a", "b"]
)
@classmethod
def string7(cls, session: "Session") -> DataFrame:
return session.create_dataframe([["str", 1], [None, 2]], schema=["a", "b"])
@classmethod
def string8(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[
(
"foo-bar;baz",
"qwer,dvor>azer",
"lower",
"UPPER",
"Chief Variable Officer",
"Lorem ipsum dolor sit amet",
)
],
schema=["delim1", "delim2", "lower", "upper", "title", "sentence"],
)
@classmethod
def string9(cls, session: "Session") -> DataFrame:
return session.create_dataframe(
[
("foo\nbar1"),
("foo\tbar2"),
("foo\rbar3"),
("foo\r\nbar4"),
],
schema=["a"],
)
@classmethod
def array1(cls, session: "Session") -> DataFrame:
df = session.create_dataframe(
[
(1, 2, 3, 3, 4, 5),
(6, 7, 8, 9, 0, 1),
],
schema=["a", "b", "c", "d", "e", "f"],
)
return df.select(
array_construct("a", "b", "c").alias("arr1"),
array_construct("d", "e", "f").alias("arr2"),
)
@classmethod
def array2(cls, session: "Session") -> DataFrame:
return session.sql(
"select array_construct(a,b,c) as arr1, d, e, f from"
" values(1,2,3,2,'e1','[{a:1}]'),(6,7,8,1,'e2','[{a:1},{b:2}]') as T(a,b,c,d,e,f)"
)
@classmethod
def array3(cls, session: "Session") -> DataFrame:
return session.sql(
"select array_construct(a,b,c) as arr1, d, e, f "
"from values(1,2,3,1,2,','),(4,5,6,1,-1,', '),(6,7,8,0,2,';') as T(a,b,c,d,e,f)"
)
@classmethod
def object1(cls, session: "Session") -> DataFrame:
return (
session.create_dataframe(
[
("age", 21),
("zip", 94401),
]
)
.to_df(["key", "value"])
.select("key", to_variant("value").alias("value"))
)
@classmethod
def object2(cls, session: "Session") -> DataFrame:
return (
session.create_dataframe(
[
("age", 21, "zip", 21021, "name", "Joe", "age", 0, True),
("age", 26, "zip", 94021, "name", "Jay", "key", 0, False),
]
)
.to_df(["a", "b", "c", "d", "e", "f", "k", "v", "flag"])
.select(
object_construct("a", "b", "c", "d", "e", "f").alias("obj"),
"k",
"v",
"flag",
)
)
@classmethod
def object3(cls, session: "Session") -> DataFrame:
return (
session.create_dataframe(
[
(None, 21),
("zip", None),
]
)
.to_df(["key", "value"])
.select("key", to_variant("value").alias("value"))
)
@classmethod
def null_array1(cls, session: "Session") -> DataFrame:
return session.sql(
"select array_construct(a,b,c) as arr1, array_construct(d,e,f) as arr2 "
"from values(1,null,3,3,null,5),(6,null,8,9,null,1) as T(a,b,c,d,e,f)"
)
@classmethod
def zero1(cls, session: "Session") -> DataFrame:
return session.create_dataframe([(0,)], schema=["a"])
@classmethod
def variant1(cls, session: "Session") -> DataFrame:
df = session.create_dataframe([1]).select(
to_variant(to_array(lit("Example"))).alias("arr1"),
to_variant(to_object(parse_json(lit('{"Tree": "Pine"}')))).alias("obj1"),
to_variant(to_binary(lit("snow"), "utf-8")).alias("bin1"),
to_variant(lit(True)).alias("bool1"),
to_variant(lit("X")).alias("str1"),
to_variant(to_date(lit("2017-02-24"))).alias("date1"),