-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
test_sqlalchemy_execution_engine.py
1259 lines (1079 loc) · 46.1 KB
/
test_sqlalchemy_execution_engine.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
import logging
import os
from typing import Dict, Tuple, cast
import pandas as pd
import pytest
import great_expectations.exceptions as gx_exceptions
from great_expectations.compatibility.sqlalchemy import Connection
from great_expectations.compatibility.sqlalchemy_compatibility_wrappers import (
add_dataframe_to_db,
)
from great_expectations.core.batch_spec import (
RuntimeQueryBatchSpec,
SqlAlchemyDatasourceBatchSpec,
)
from great_expectations.core.metric_domain_types import MetricDomainTypes
from great_expectations.core.metric_function_types import (
MetricPartialFunctionTypes,
MetricPartialFunctionTypeSuffixes,
SummarizationMetricNameSuffixes,
)
from great_expectations.data_context.util import file_relative_path
from great_expectations.execution_engine.sqlalchemy_batch_data import (
SqlAlchemyBatchData,
)
from great_expectations.execution_engine.sqlalchemy_dialect import GXSqlDialect
from great_expectations.execution_engine.sqlalchemy_execution_engine import (
SqlAlchemyExecutionEngine,
_dialect_requires_persisted_connection,
)
# Function to test for spark dataframe equality
from great_expectations.expectations.row_conditions import (
RowCondition,
RowConditionParserType,
)
from great_expectations.self_check.util import build_sa_execution_engine
from great_expectations.util import get_sqlalchemy_domain_data
from great_expectations.validator.computed_metric import MetricValue
from great_expectations.validator.metric_configuration import MetricConfiguration
from great_expectations.validator.validator import Validator
from tests.expectations.test_util import get_table_columns_metric
from tests.test_utils import (
get_sqlite_table_names,
get_sqlite_temp_table_names,
get_sqlite_temp_table_names_from_engine,
)
try:
sqlalchemy = pytest.importorskip("sqlalchemy")
except ImportError:
sqlalchemy = None
pytestmark = [
pytest.mark.sqlalchemy_version_compatibility,
pytest.mark.external_sqldialect,
]
@pytest.mark.sqlite
def test_instantiation_via_connection_string(sa, test_db_connection_string):
my_execution_engine = SqlAlchemyExecutionEngine(connection_string=test_db_connection_string)
assert my_execution_engine.connection_string == test_db_connection_string
assert my_execution_engine.credentials is None
assert my_execution_engine.url is None
my_execution_engine.get_batch_data_and_markers(
batch_spec=SqlAlchemyDatasourceBatchSpec(
table_name="table_1",
schema_name="main",
sampling_method="_sample_using_limit",
sampling_kwargs={"n": 5},
)
)
@pytest.mark.sqlite
def test_instantiation_via_url(sa):
db_file = file_relative_path(
__file__,
os.path.join( # noqa: PTH118
"..", "test_sets", "test_cases_for_sql_data_connector.db"
),
)
my_execution_engine = SqlAlchemyExecutionEngine(url="sqlite:///" + db_file)
assert my_execution_engine.connection_string is None
assert my_execution_engine.credentials is None
assert my_execution_engine.url[-36:] == "test_cases_for_sql_data_connector.db"
my_execution_engine.get_batch_data_and_markers(
batch_spec=SqlAlchemyDatasourceBatchSpec(
table_name="table_partitioned_by_date_column__A",
sampling_method="_sample_using_limit",
sampling_kwargs={"n": 5},
)
)
@pytest.mark.sqlite
def test_instantiation_via_url_with_invalid_kwargs(sa):
db_file = file_relative_path(
__file__,
os.path.join( # noqa: PTH118
"..", "test_sets", "test_cases_for_sql_data_connector.db"
),
)
with pytest.raises(TypeError):
_ = SqlAlchemyExecutionEngine(
url="sqlite:///" + db_file,
connect_args={"invalid_keyword_argument": ""},
)
@pytest.mark.sqlite
def test_instantiation_via_url_with_kwargs(sa):
db_file = file_relative_path(
__file__,
os.path.join( # noqa: PTH118
"..", "test_sets", "test_cases_for_sql_data_connector.db"
),
)
my_execution_engine = SqlAlchemyExecutionEngine(
url="sqlite:///" + db_file, connect_args={"timeout": 10}
)
assert my_execution_engine.connection_string is None
assert my_execution_engine.credentials is None
assert my_execution_engine.url[-36:] == "test_cases_for_sql_data_connector.db"
my_execution_engine.get_batch_data_and_markers(
batch_spec=SqlAlchemyDatasourceBatchSpec(
table_name="table_partitioned_by_date_column__A",
sampling_method="_sample_using_limit",
sampling_kwargs={"n": 5},
)
)
@pytest.mark.sqlite
def test_instantiation_via_fluent_data_sources_with_kwargs(
sa,
empty_data_context,
filter_gx_datasource_warnings: None,
):
db_file = file_relative_path(
__file__,
os.path.join( # noqa: PTH118
"..", "test_sets", "test_cases_for_sql_data_connector.db"
),
)
connection_string = "sqlite:///" + db_file
context = empty_data_context
datasource = context.data_sources.add_sql(
name="test_datasource",
connection_string=connection_string,
kwargs={"connect_args": {"check_same_thread": False}},
)
engine = datasource.get_engine()
assert engine
assert engine.dialect.name == "sqlite"
execution_engine = datasource.get_execution_engine()
assert execution_engine.connection_string == connection_string
# kwargs should be passed through as keyword arguments to create_engine
assert execution_engine.config["connect_args"] == {"check_same_thread": False}
assert execution_engine.config["class_name"] == "SqlAlchemyExecutionEngine"
assert execution_engine.config["connection_string"] == connection_string
assert execution_engine.engine
@pytest.mark.sqlite
def test_instantiation_via_url_and_retrieve_data_with_other_dialect(sa):
"""Ensure that we can still retrieve data when the dialect is not recognized."""
# 1. Create engine with sqlite db
db_file = file_relative_path(
__file__,
os.path.join( # noqa: PTH118
"..", "test_sets", "test_cases_for_sql_data_connector.db"
),
)
my_execution_engine = SqlAlchemyExecutionEngine(url="sqlite:///" + db_file)
assert my_execution_engine.connection_string is None
assert my_execution_engine.credentials is None
assert my_execution_engine.url[-36:] == "test_cases_for_sql_data_connector.db"
# 2. Change dialect to one not listed in GXSqlDialect
my_execution_engine.engine.dialect.name = "other_dialect"
# 3. Get data
num_rows_in_sample: int = 10
batch_data, _ = my_execution_engine.get_batch_data_and_markers(
batch_spec=SqlAlchemyDatasourceBatchSpec(
table_name="table_partitioned_by_date_column__A",
sampling_method="_sample_using_limit",
sampling_kwargs={"n": num_rows_in_sample},
)
)
# 4. Assert dialect and data are as expected
assert batch_data.dialect == GXSqlDialect.OTHER
my_execution_engine.load_batch_data("__", batch_data)
validator = Validator(my_execution_engine)
assert len(validator.head(fetch_all=True)) == num_rows_in_sample
@pytest.mark.postgresql
def test_instantiation_via_credentials(sa, test_backends, test_df):
if "postgresql" not in test_backends:
pytest.skip("test_database_store_backend_get_url_for_key requires postgresql")
my_execution_engine = SqlAlchemyExecutionEngine(
credentials={
"drivername": "postgresql",
"username": "postgres",
"password": "",
"host": os.getenv("GE_TEST_LOCAL_DB_HOSTNAME", "localhost"),
"port": "5432",
"database": "test_ci",
}
)
assert my_execution_engine.connection_string is None
assert my_execution_engine.credentials == {
"username": "postgres",
"password": "",
"host": os.getenv("GE_TEST_LOCAL_DB_HOSTNAME", "localhost"),
"port": "5432",
"database": "test_ci",
}
assert my_execution_engine.url is None
# Note Abe 20201116: Let's add an actual test of get_batch_data_and_markers, which will require setting up test # noqa: E501
# fixtures
# my_execution_engine.get_batch_data_and_markers(batch_spec=BatchSpec(
# table_name="main.table_1",
# sampling_method="_sample_using_limit",
# sampling_kwargs={
# "n": 5
# }
# ))
@pytest.mark.sqlite
def test_instantiation_error_states(sa, test_db_connection_string):
with pytest.raises(gx_exceptions.InvalidConfigError):
SqlAlchemyExecutionEngine()
# Testing batching of aggregate metrics
@pytest.mark.sqlite
def test_sa_batch_aggregate_metrics(caplog, sa):
import datetime
execution_engine = build_sa_execution_engine(
pd.DataFrame({"a": [1, 2, 1, 2, 3, 3], "b": [4, 4, 4, 4, 4, 4]}), sa
)
metrics: Dict[Tuple[str, str, str], MetricValue] = {}
table_columns_metric: MetricConfiguration
results: Dict[Tuple[str, str, str], MetricValue]
table_columns_metric, results = get_table_columns_metric(execution_engine=execution_engine)
metrics.update(results)
aggregate_fn_metric_1 = MetricConfiguration(
metric_name=f"column.max.{MetricPartialFunctionTypes.AGGREGATE_FN.metric_suffix}",
metric_domain_kwargs={"column": "a"},
metric_value_kwargs=None,
)
aggregate_fn_metric_1.metric_dependencies = {
"table.columns": table_columns_metric,
}
aggregate_fn_metric_2 = MetricConfiguration(
metric_name=f"column.min.{MetricPartialFunctionTypes.AGGREGATE_FN.metric_suffix}",
metric_domain_kwargs={"column": "a"},
metric_value_kwargs=None,
)
aggregate_fn_metric_2.metric_dependencies = {
"table.columns": table_columns_metric,
}
aggregate_fn_metric_3 = MetricConfiguration(
metric_name=f"column.max.{MetricPartialFunctionTypes.AGGREGATE_FN.metric_suffix}",
metric_domain_kwargs={"column": "b"},
metric_value_kwargs=None,
)
aggregate_fn_metric_3.metric_dependencies = {
"table.columns": table_columns_metric,
}
aggregate_fn_metric_4 = MetricConfiguration(
metric_name=f"column.min.{MetricPartialFunctionTypes.AGGREGATE_FN.metric_suffix}",
metric_domain_kwargs={"column": "b"},
metric_value_kwargs=None,
)
aggregate_fn_metric_4.metric_dependencies = {
"table.columns": table_columns_metric,
}
results = execution_engine.resolve_metrics(
metrics_to_resolve=(
aggregate_fn_metric_1,
aggregate_fn_metric_2,
aggregate_fn_metric_3,
aggregate_fn_metric_4,
),
metrics=metrics,
)
metrics.update(results)
desired_metric_1 = MetricConfiguration(
metric_name="column.max",
metric_domain_kwargs={"column": "a"},
metric_value_kwargs=None,
)
desired_metric_1.metric_dependencies = {
"metric_partial_fn": aggregate_fn_metric_1,
"table.columns": table_columns_metric,
}
desired_metric_2 = MetricConfiguration(
metric_name="column.min",
metric_domain_kwargs={"column": "a"},
metric_value_kwargs=None,
)
desired_metric_2.metric_dependencies = {
"metric_partial_fn": aggregate_fn_metric_2,
"table.columns": table_columns_metric,
}
desired_metric_3 = MetricConfiguration(
metric_name="column.max",
metric_domain_kwargs={"column": "b"},
metric_value_kwargs=None,
)
desired_metric_3.metric_dependencies = {
"metric_partial_fn": aggregate_fn_metric_3,
"table.columns": table_columns_metric,
}
desired_metric_4 = MetricConfiguration(
metric_name="column.min",
metric_domain_kwargs={"column": "b"},
metric_value_kwargs=None,
)
desired_metric_4.metric_dependencies = {
"metric_partial_fn": aggregate_fn_metric_4,
"table.columns": table_columns_metric,
}
caplog.clear()
caplog.set_level(logging.DEBUG, logger="great_expectations")
start = datetime.datetime.now() # noqa: DTZ005
results = execution_engine.resolve_metrics(
metrics_to_resolve=(
desired_metric_1,
desired_metric_2,
desired_metric_3,
desired_metric_4,
),
metrics=metrics,
)
metrics.update(results)
end = datetime.datetime.now() # noqa: DTZ005
print("t1")
print(end - start)
assert results[desired_metric_1.id] == 3
assert results[desired_metric_2.id] == 1
assert results[desired_metric_3.id] == 4
assert results[desired_metric_4.id] == 4
# Check that all four of these metrics were computed on a single domain
found_message = False
for record in caplog.records:
if record.message == "SqlAlchemyExecutionEngine computed 4 metrics on domain_id ()":
found_message = True
assert found_message
@pytest.mark.sqlite
def test_get_domain_records_with_column_domain(sa):
df = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [2, 3, 4, 5, None], "c": [1, 2, 3, 4, None]})
execution_engine = build_sa_execution_engine(df, sa)
data = execution_engine.get_domain_records(
domain_kwargs={
"column": "a",
"row_condition": 'col("b")<5',
"condition_parser": "great_expectations__experimental__",
}
)
domain_data = execution_engine.execute_query(get_sqlalchemy_domain_data(data)).fetchall()
expected_column_df = df.iloc[:3]
execution_engine = build_sa_execution_engine(expected_column_df, sa)
expected_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
assert (
domain_data == expected_data
), "Data does not match after getting full access compute domain"
@pytest.mark.sqlite
def test_get_domain_records_with_column_domain_and_filter_conditions(sa):
df = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [2, 3, 4, 5, None], "c": [1, 2, 3, 4, None]})
execution_engine = build_sa_execution_engine(df, sa)
data = execution_engine.get_domain_records(
domain_kwargs={
"column": "a",
"row_condition": 'col("b")<5',
"condition_parser": "great_expectations__experimental__",
"filter_conditions": [
RowCondition(
condition='col("b").notnull()',
condition_type=RowConditionParserType.GE,
)
],
}
)
domain_data = execution_engine.execute_query(get_sqlalchemy_domain_data(data)).fetchall()
expected_column_df = df.iloc[:3]
execution_engine = build_sa_execution_engine(expected_column_df, sa)
expected_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
assert (
domain_data == expected_data
), "Data does not match after getting full access compute domain"
@pytest.mark.sqlite
def test_get_domain_records_with_different_column_domain_and_filter_conditions(sa):
df = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [2, 3, 4, 5, None], "c": [1, 2, 3, 4, None]})
execution_engine = build_sa_execution_engine(df, sa)
data = execution_engine.get_domain_records(
domain_kwargs={
"column": "a",
"row_condition": 'col("a")<2',
"condition_parser": "great_expectations__experimental__",
"filter_conditions": [
RowCondition(
condition='col("b").notnull()',
condition_type=RowConditionParserType.GE,
)
],
}
)
domain_data = execution_engine.execute_query(get_sqlalchemy_domain_data(data)).fetchall()
expected_column_df = df.iloc[:1]
execution_engine = build_sa_execution_engine(expected_column_df, sa)
expected_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
assert (
domain_data == expected_data
), "Data does not match after getting full access compute domain"
@pytest.mark.sqlite
def test_get_domain_records_with_column_domain_and_filter_conditions_raises_error_on_multiple_conditions( # noqa: E501
sa,
):
df = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [2, 3, 4, 5, None], "c": [1, 2, 3, 4, None]})
execution_engine = build_sa_execution_engine(df, sa)
with pytest.raises(gx_exceptions.GreatExpectationsError):
execution_engine.get_domain_records(
domain_kwargs={
"column": "a",
"row_condition": 'col("a")<2',
"condition_parser": "great_expectations__experimental__",
"filter_conditions": [
RowCondition(
condition='col("b").notnull()',
condition_type=RowConditionParserType.GE,
),
RowCondition(
condition='col("c").notnull()',
condition_type=RowConditionParserType.GE,
),
],
}
)
@pytest.mark.sqlite
def test_get_domain_records_with_column_pair_domain(sa):
df = pd.DataFrame(
{
"a": [1, 2, 3, 4, 5, 6],
"b": [2, 3, 4, 5, None, 6],
"c": [1, 2, 3, 4, 5, None],
}
)
execution_engine = build_sa_execution_engine(df, sa)
data = execution_engine.get_domain_records(
domain_kwargs={
"column_A": "a",
"column_B": "b",
"row_condition": 'col("b")>2',
"condition_parser": "great_expectations__experimental__",
"ignore_row_if": "both_values_are_missing",
}
)
domain_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(data)
).fetchall()
expected_column_pair_df = pd.DataFrame(
{"a": [2, 3, 4, 6], "b": [3.0, 4.0, 5.0, 6.0], "c": [2.0, 3.0, 4.0, None]}
)
execution_engine = build_sa_execution_engine(expected_column_pair_df, sa)
expected_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
assert (
domain_data == expected_data
), "Data does not match after getting full access compute domain"
execution_engine = build_sa_execution_engine(df, sa)
data = execution_engine.get_domain_records(
domain_kwargs={
"column_A": "b",
"column_B": "c",
"row_condition": 'col("b")>2',
"condition_parser": "great_expectations__experimental__",
"ignore_row_if": "either_value_is_missing",
}
)
domain_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(data)
).fetchall()
expected_column_pair_df = pd.DataFrame({"a": [2, 3, 4], "b": [3, 4, 5], "c": [2, 3, 4]})
execution_engine = build_sa_execution_engine(expected_column_pair_df, sa)
expected_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
assert (
domain_data == expected_data
), "Data does not match after getting full access compute domain"
execution_engine = build_sa_execution_engine(df, sa)
data = execution_engine.get_domain_records(
domain_kwargs={
"column_A": "b",
"column_B": "c",
"row_condition": 'col("a")<6',
"condition_parser": "great_expectations__experimental__",
"ignore_row_if": "neither",
}
)
domain_data = execution_engine.execute_query(get_sqlalchemy_domain_data(data)).fetchall()
expected_column_pair_df = pd.DataFrame(
{
"a": [1, 2, 3, 4, 5],
"b": [2.0, 3.0, 4.0, 5.0, None],
"c": [1.0, 2.0, 3.0, 4.0, 5.0],
}
)
execution_engine = build_sa_execution_engine(expected_column_pair_df, sa)
expected_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
assert (
domain_data == expected_data
), "Data does not match after getting full access compute domain"
@pytest.mark.sqlite
def test_get_domain_records_with_multicolumn_domain(sa):
df = pd.DataFrame(
{
"a": [1, 2, 3, 4, None, 5],
"b": [2, 3, 4, 5, 6, 7],
"c": [1, 2, 3, 4, None, 6],
}
)
execution_engine = build_sa_execution_engine(df, sa)
data = execution_engine.get_domain_records(
domain_kwargs={
"column_list": ["a", "c"],
"row_condition": 'col("b")>2',
"condition_parser": "great_expectations__experimental__",
"ignore_row_if": "all_values_are_missing",
}
)
domain_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(data)
).fetchall()
expected_multicolumn_df = pd.DataFrame(
{"a": [2, 3, 4, 5], "b": [3, 4, 5, 7], "c": [2, 3, 4, 6]}, index=[0, 1, 2, 4]
)
execution_engine = build_sa_execution_engine(expected_multicolumn_df, sa)
expected_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
assert (
domain_data == expected_data
), "Data does not match after getting full access compute domain"
df = pd.DataFrame(
{
"a": [1, 2, 3, 4, 5, 6],
"b": [2, 3, 4, 5, None, 6],
"c": [1, 2, 3, 4, 5, None],
}
)
execution_engine = build_sa_execution_engine(df, sa)
data = execution_engine.get_domain_records(
domain_kwargs={
"column_list": ["b", "c"],
"row_condition": 'col("a")<5',
"condition_parser": "great_expectations__experimental__",
"ignore_row_if": "any_value_is_missing",
}
)
domain_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(data)
).fetchall()
expected_multicolumn_df = pd.DataFrame(
{"a": [1, 2, 3, 4], "b": [2, 3, 4, 5], "c": [1, 2, 3, 4]}, index=[0, 1, 2, 3]
)
execution_engine = build_sa_execution_engine(expected_multicolumn_df, sa)
expected_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
assert (
domain_data == expected_data
), "Data does not match after getting full access compute domain"
df = pd.DataFrame(
{
"a": [1, 2, 3, 4, None, 5],
"b": [2, 3, 4, 5, 6, 7],
"c": [1, 2, 3, 4, None, 6],
}
)
execution_engine = build_sa_execution_engine(df, sa)
data = execution_engine.get_domain_records(
domain_kwargs={
"column_list": ["b", "c"],
"ignore_row_if": "never",
}
)
domain_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(data)
).fetchall()
expected_multicolumn_df = pd.DataFrame(
{
"a": [1, 2, 3, 4, None, 5],
"b": [2, 3, 4, 5, 6, 7],
"c": [1, 2, 3, 4, None, 6],
},
index=[0, 1, 2, 3, 4, 5],
)
execution_engine = build_sa_execution_engine(expected_multicolumn_df, sa)
expected_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
assert (
domain_data == expected_data
), "Data does not match after getting full access compute domain"
# Ensuring functionality of compute_domain when no domain kwargs are given
@pytest.mark.sqlite
def test_get_compute_domain_with_no_domain_kwargs(sa):
execution_engine = build_sa_execution_engine(
pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]}), sa
)
data, compute_kwargs, accessor_kwargs = execution_engine.get_compute_domain(
domain_kwargs={}, domain_type="table"
)
# Seeing if raw data is the same as the data after condition has been applied - checking post computation data # noqa: E501
raw_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
domain_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(data)
).fetchall()
# Ensuring that with no domain nothing happens to the data itself
assert raw_data == domain_data, "Data does not match after getting compute domain"
assert compute_kwargs == {}, "Compute domain kwargs should be existent"
assert accessor_kwargs == {}, "Accessor kwargs have been modified"
# Testing for only untested use case - column_pair
@pytest.mark.sqlite
def test_get_compute_domain_with_column_pair(sa):
execution_engine = build_sa_execution_engine(
pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]}), sa
)
# Fetching data, compute_domain_kwargs, accessor_kwargs
data, compute_kwargs, accessor_kwargs = execution_engine.get_compute_domain(
domain_kwargs={"column_A": "a", "column_B": "b"}, domain_type="column_pair"
)
# Seeing if raw data is the same as the data after condition has been applied - checking post computation data # noqa: E501
raw_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
domain_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(data)
).fetchall()
# Ensuring that with no domain nothing happens to the data itself
assert raw_data == domain_data, "Data does not match after getting compute domain"
assert (
"column_A" not in compute_kwargs and "column_B" not in compute_kwargs
), "domain kwargs should be existent"
assert accessor_kwargs == {
"column_A": "a",
"column_B": "b",
}, "Accessor kwargs have been modified"
# Testing for only untested use case - multicolumn
@pytest.mark.sqlite
def test_get_compute_domain_with_multicolumn(sa):
execution_engine = build_sa_execution_engine(
pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None], "c": [1, 2, 3, None]}),
sa,
)
# Obtaining compute domain
data, compute_kwargs, accessor_kwargs = execution_engine.get_compute_domain(
domain_kwargs={"column_list": ["a", "b", "c"]}, domain_type="multicolumn"
)
# Seeing if raw data is the same as the data after condition has been applied - checking post computation data # noqa: E501
raw_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
domain_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(data)
).fetchall()
# Ensuring that with no domain nothing happens to the data itself
assert raw_data == domain_data, "Data does not match after getting compute domain"
assert compute_kwargs is not None, "Compute domain kwargs should be existent"
assert accessor_kwargs == {"column_list": ["a", "b", "c"]}, "Accessor kwargs have been modified"
# Testing whether compute domain is properly calculated, but this time obtaining a column
@pytest.mark.sqlite
def test_get_compute_domain_with_column_domain(sa):
execution_engine = build_sa_execution_engine(
pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]}), sa
)
# Loading batch data
data, compute_kwargs, accessor_kwargs = execution_engine.get_compute_domain(
domain_kwargs={"column": "a"}, domain_type=MetricDomainTypes.COLUMN
)
# Seeing if raw data is the same as the data after condition has been applied - checking post computation data # noqa: E501
raw_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
).fetchall()
domain_data = execution_engine.execute_query(
sa.select(sa.text("*")).select_from(data)
).fetchall()
# Ensuring that column domain is now an accessor kwarg, and data remains unmodified
assert raw_data == domain_data, "Data does not match after getting compute domain"
assert compute_kwargs == {}, "Compute domain kwargs should be existent"
assert accessor_kwargs == {"column": "a"}, "Accessor kwargs have been modified"
# What happens when we filter such that no value meets the condition?
@pytest.mark.sqlite
def test_get_compute_domain_with_unmeetable_row_condition(sa):
execution_engine = build_sa_execution_engine(
pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]}), sa
)
data, compute_kwargs, accessor_kwargs = execution_engine.get_compute_domain(
domain_kwargs={
"column": "a",
"row_condition": 'col("b") > 24',
"condition_parser": "great_expectations__experimental__",
},
domain_type="column",
)
# Seeing if raw data is the same as the data after condition has been applied - checking post computation data # noqa: E501
raw_data = execution_engine.execute_query(
sa.select(sa.text("*"))
.select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
.where(sa.column("b") > 24)
).fetchall()
domain_data = execution_engine.execute_query(get_sqlalchemy_domain_data(data)).fetchall()
# Ensuring that column domain is now an accessor kwarg, and data remains unmodified
assert raw_data == domain_data, "Data does not match after getting compute domain"
# Ensuring compute kwargs have not been modified
assert (
"row_condition" in compute_kwargs
), "Row condition should be located within compute kwargs"
assert accessor_kwargs == {"column": "a"}, "Accessor kwargs have been modified"
# Testing to ensure that great expectation experimental parser also works in terms of defining a compute domain # noqa: E501
@pytest.mark.sqlite
def test_get_compute_domain_with_ge_experimental_condition_parser(sa):
execution_engine = build_sa_execution_engine(
pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]}), sa
)
# Obtaining data from computation
data, compute_kwargs, accessor_kwargs = execution_engine.get_compute_domain(
domain_kwargs={
"column": "b",
"row_condition": 'col("b") == 2',
"condition_parser": "great_expectations__experimental__",
},
domain_type="column",
)
# Seeing if raw data is the same as the data after condition has been applied - checking post computation data # noqa: E501
raw_data = execution_engine.execute_query(
sa.select(sa.text("*"))
.select_from(
cast(SqlAlchemyBatchData, execution_engine.batch_manager.active_batch_data).selectable
)
.where(sa.column("b") == 2)
).fetchall()
domain_data = execution_engine.execute_query(get_sqlalchemy_domain_data(data)).fetchall()
# Ensuring that column domain is now an accessor kwarg, and data remains unmodified
assert raw_data == domain_data, "Data does not match after getting compute domain"
# Ensuring compute kwargs have not been modified
assert (
"row_condition" in compute_kwargs
), "Row condition should be located within compute kwargs"
assert accessor_kwargs == {"column": "b"}, "Accessor kwargs have been modified"
@pytest.mark.sqlite
def test_get_compute_domain_with_nonexistent_condition_parser(sa):
execution_engine = build_sa_execution_engine(
pd.DataFrame({"a": [1, 2, 3, 4], "b": [2, 3, 4, None]}), sa
)
# Expect GreatExpectationsError because parser doesn't exist
with pytest.raises(gx_exceptions.GreatExpectationsError):
_data, _compute_kwargs, _accessor_kwargs = execution_engine.get_compute_domain(
domain_kwargs={
"row_condition": "b > 24",
"condition_parser": "nonexistent",
},
domain_type=MetricDomainTypes.TABLE,
)
# Ensuring that we can properly inform user when metric doesn't exist - should get a metric provider error # noqa: E501
@pytest.mark.sqlite
def test_resolve_metric_bundle_with_nonexistent_metric(sa):
execution_engine = build_sa_execution_engine(
pd.DataFrame({"a": [1, 2, 1, 2, 3, 3], "b": [4, 4, 4, 4, 4, 4]}), sa
)
desired_metric_1 = MetricConfiguration(
metric_name="column_values.unique",
metric_domain_kwargs={"column": "a"},
metric_value_kwargs=None,
)
desired_metric_2 = MetricConfiguration(
metric_name="column.min",
metric_domain_kwargs={"column": "a"},
metric_value_kwargs=None,
)
desired_metric_3 = MetricConfiguration(
metric_name="column.max",
metric_domain_kwargs={"column": "b"},
metric_value_kwargs=None,
)
desired_metric_4 = MetricConfiguration(
metric_name="column.does_not_exist",
metric_domain_kwargs={"column": "b"},
metric_value_kwargs=None,
)
# Ensuring a metric provider error is raised if metric does not exist
with pytest.raises(gx_exceptions.MetricProviderError) as e:
# noinspection PyUnusedLocal
execution_engine.resolve_metrics(
metrics_to_resolve=(
desired_metric_1,
desired_metric_2,
desired_metric_3,
desired_metric_4,
)
)
print(e)
@pytest.mark.sqlite
def test_resolve_metric_bundle_with_compute_domain_kwargs_json_serialization(sa):
"""
Insures that even when "compute_domain_kwargs" has multiple keys, it will be JSON-serialized for "IDDict.to_id()".
""" # noqa: E501
execution_engine = build_sa_execution_engine(
pd.DataFrame(
{
"names": [
"Ada Lovelace",
"Alan Kay",
"Donald Knuth",
"Edsger Dijkstra",
"Guido van Rossum",
"John McCarthy",
"Marvin Minsky",
"Ray Ozzie",
]
}
),
sa,
batch_id="1234",
)
metrics: Dict[Tuple[str, str, str], MetricValue] = {}
table_columns_metric: MetricConfiguration
results: Dict[Tuple[str, str, str], MetricValue]
table_columns_metric, results = get_table_columns_metric(execution_engine=execution_engine)
metrics.update(results)
aggregate_fn_metric = MetricConfiguration(
metric_name=f"column_values.length.max.{MetricPartialFunctionTypes.AGGREGATE_FN.metric_suffix}",
metric_domain_kwargs={
"column": "names",
"batch_id": "1234",
},
metric_value_kwargs=None,
)
aggregate_fn_metric.metric_dependencies = {
"table.columns": table_columns_metric,
}
try:
results = execution_engine.resolve_metrics(metrics_to_resolve=(aggregate_fn_metric,))
except gx_exceptions.MetricProviderError as e:
assert False, str(e)
desired_metric = MetricConfiguration(
metric_name="column_values.length.max",
metric_domain_kwargs={
"batch_id": "1234",
},
metric_value_kwargs=None,
)