-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
conftest.py
2280 lines (1995 loc) · 75.5 KB
/
conftest.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
from __future__ import annotations
import copy
import datetime
import locale
import logging
import os
import pathlib
import random
import shutil
import urllib.parse
import warnings
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, Final, Generator, List, Optional
from unittest import mock
import numpy as np
import packaging
import pandas as pd
import pytest
import great_expectations as gx
from great_expectations.analytics.config import ENV_CONFIG
from great_expectations.compatibility import pyspark
from great_expectations.compatibility.sqlalchemy_compatibility_wrappers import (
add_dataframe_to_db,
)
from great_expectations.core.batch_definition import BatchDefinition
from great_expectations.core.expectation_suite import ExpectationSuite
from great_expectations.core.expectation_validation_result import (
ExpectationValidationResult,
)
from great_expectations.core.metric_function_types import MetricPartialFunctionTypes
from great_expectations.core.validation_definition import ValidationDefinition
from great_expectations.core.yaml_handler import YAMLHandler
from great_expectations.data_context import (
AbstractDataContext,
CloudDataContext,
get_context,
)
from great_expectations.data_context._version_checker import _VersionChecker
from great_expectations.data_context.cloud_constants import (
GXCloudEnvironmentVariable,
)
from great_expectations.data_context.data_context.context_factory import (
project_manager,
set_context,
)
from great_expectations.data_context.data_context.ephemeral_data_context import (
EphemeralDataContext,
)
from great_expectations.data_context.data_context.file_data_context import (
FileDataContext,
)
from great_expectations.data_context.store.gx_cloud_store_backend import (
GXCloudStoreBackend,
)
from great_expectations.data_context.types.base import (
DataContextConfig,
GXCloudConfig,
InMemoryStoreBackendDefaults,
)
from great_expectations.data_context.types.resource_identifiers import (
ExpectationSuiteIdentifier,
)
from great_expectations.data_context.util import (
file_relative_path,
)
from great_expectations.datasource.fluent import GxDatasourceWarning, PandasDatasource
from great_expectations.execution_engine import SparkDFExecutionEngine
from great_expectations.expectations.expectation_configuration import (
ExpectationConfiguration,
)
from great_expectations.self_check.util import (
build_test_backends_list as build_test_backends_list_v3,
)
from great_expectations.self_check.util import (
expectationSuiteValidationResultSchema,
)
from great_expectations.util import (
build_in_memory_runtime_context,
is_library_loadable,
)
from great_expectations.validator.metric_configuration import MetricConfiguration
from great_expectations.validator.validator import Validator
from tests.datasource.fluent._fake_cloud_api import (
DUMMY_JWT_TOKEN,
FAKE_ORG_ID,
GX_CLOUD_MOCK_BASE_URL,
CloudDetails,
gx_cloud_api_fake_ctx,
)
if TYPE_CHECKING:
from unittest.mock import MagicMock # noqa: TID251 # type-checking only
from pytest_mock import MockerFixture
from great_expectations.compatibility.sqlalchemy import Engine
yaml = YAMLHandler()
###
#
# NOTE: THESE TESTS ARE WRITTEN WITH THE en_US.UTF-8 LOCALE AS DEFAULT FOR STRING FORMATTING
#
###
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
logger = logging.getLogger(__name__)
REQUIRED_MARKERS: Final[set[str]] = {
"all_backends",
"athena",
"aws_creds",
"aws_deps",
"big",
"bigquery",
"cli",
"clickhouse",
"cloud",
"databricks",
"docs",
"integration",
"filesystem",
"mssql",
"mysql",
"openpyxl",
"performance",
"postgresql",
"project",
"pyarrow",
"snowflake",
"spark",
"spark_connect",
"sqlite",
"trino",
"unit",
}
@pytest.fixture()
def unset_gx_env_variables(monkeypatch: pytest.MonkeyPatch) -> None:
for var in GXCloudEnvironmentVariable:
monkeypatch.delenv(var, raising=False)
@pytest.mark.order(index=2)
@pytest.fixture(scope="module")
def spark_warehouse_session(tmp_path_factory):
# Note this fixture will configure spark to use in-memory metastore
pytest.importorskip("pyspark")
spark_warehouse_path: str = str(tmp_path_factory.mktemp("spark-warehouse"))
spark: pyspark.SparkSession = SparkDFExecutionEngine.get_or_create_spark_session(
spark_config={
"spark.sql.warehouse.dir": spark_warehouse_path,
}
)
yield spark
spark.stop()
def pytest_configure(config):
config.addinivalue_line(
"markers",
"smoketest: mark test as smoketest--it does not have useful assertions but may produce side effects " # noqa: E501
"that require manual inspection.",
)
config.addinivalue_line(
"markers",
"rendered_output: produces rendered output that should be manually reviewed.",
)
config.addinivalue_line(
"markers",
"aws_integration: runs aws integration test that may be very slow and requires credentials",
)
config.addinivalue_line(
"markers",
"cloud: runs GX Cloud tests that may be slow and requires credentials",
)
def pytest_addoption(parser):
parser.addoption(
"--verify-marker-coverage-and-exit",
action="store_true",
help="If set, checks that all tests have one of the markers necessary " "for it to be run.",
)
# note: --no-spark will be deprecated in favor of --spark
parser.addoption(
"--no-spark",
action="store_true",
help="If set, suppress tests against the spark test suite",
)
parser.addoption(
"--spark",
action="store_true",
help="If set, execute tests against the spark test suite",
)
parser.addoption(
"--spark_connect",
action="store_true",
help="If set, execute tests against the spark-connect test suite",
)
parser.addoption(
"--no-sqlalchemy",
action="store_true",
help="If set, suppress all tests using sqlalchemy",
)
parser.addoption(
"--postgresql",
action="store_true",
help="If set, execute tests against postgresql",
)
# note: --no-postgresql will be deprecated in favor of --postgresql
parser.addoption(
"--no-postgresql",
action="store_true",
help="If set, supress tests against postgresql",
)
parser.addoption(
"--mysql",
action="store_true",
help="If set, execute tests against mysql",
)
parser.addoption(
"--mssql",
action="store_true",
help="If set, execute tests against mssql",
)
parser.addoption(
"--bigquery",
action="store_true",
help="If set, execute tests against bigquery",
)
parser.addoption(
"--aws",
action="store_true",
help="If set, execute tests against AWS resources like S3, RedShift and Athena",
)
parser.addoption(
"--trino",
action="store_true",
help="If set, execute tests against trino",
)
parser.addoption(
"--redshift",
action="store_true",
help="If set, execute tests against redshift",
)
parser.addoption(
"--athena",
action="store_true",
help="If set, execute tests against athena",
)
parser.addoption(
"--snowflake",
action="store_true",
help="If set, execute tests against snowflake",
)
parser.addoption(
"--clickhouse",
action="store_true",
help="If set, execute tests against clickhouse",
)
parser.addoption(
"--docs-tests",
action="store_true",
help="If set, run integration tests for docs",
)
parser.addoption("--azure", action="store_true", help="If set, execute tests against Azure")
parser.addoption(
"--cloud",
action="store_true",
help="If set, execute tests against GX Cloud API",
)
parser.addoption(
"--performance-tests",
action="store_true",
help="If set, run performance tests (which might also require additional arguments like --bigquery)", # noqa: E501
)
def build_test_backends_list_v2_api(metafunc):
test_backend_names: List[str] = build_test_backends_list_v3_api(metafunc)
return test_backend_names
def build_test_backends_list_v3_api(metafunc):
# adding deprecation warnings
if metafunc.config.getoption("--no-postgresql"):
warnings.warn(
"--no-sqlalchemy is deprecated as of v0.14 in favor of the --postgresql flag. It will be removed in v0.16. Please adjust your tests accordingly", # noqa: E501
DeprecationWarning,
)
if metafunc.config.getoption("--no-spark"):
warnings.warn(
"--no-spark is deprecated as of v0.14 in favor of the --spark flag. It will be removed in v0.16. Please adjust your tests accordingly.", # noqa: E501
DeprecationWarning,
)
include_pandas: bool = True
include_spark: bool = metafunc.config.getoption("--spark")
include_sqlalchemy: bool = not metafunc.config.getoption("--no-sqlalchemy")
include_postgresql: bool = metafunc.config.getoption("--postgresql")
include_mysql: bool = metafunc.config.getoption("--mysql")
include_mssql: bool = metafunc.config.getoption("--mssql")
include_bigquery: bool = metafunc.config.getoption("--bigquery")
include_aws: bool = metafunc.config.getoption("--aws")
include_trino: bool = metafunc.config.getoption("--trino")
include_azure: bool = metafunc.config.getoption("--azure")
include_redshift: bool = metafunc.config.getoption("--redshift")
include_athena: bool = metafunc.config.getoption("--athena")
include_snowflake: bool = metafunc.config.getoption("--snowflake")
include_clickhouse: bool = metafunc.config.getoption("--clickhouse")
test_backend_names: List[str] = build_test_backends_list_v3(
include_pandas=include_pandas,
include_spark=include_spark,
include_sqlalchemy=include_sqlalchemy,
include_postgresql=include_postgresql,
include_mysql=include_mysql,
include_mssql=include_mssql,
include_bigquery=include_bigquery,
include_aws=include_aws,
include_trino=include_trino,
include_azure=include_azure,
include_redshift=include_redshift,
include_athena=include_athena,
include_snowflake=include_snowflake,
include_clickhouse=include_clickhouse,
)
return test_backend_names
def pytest_generate_tests(metafunc):
test_backends = build_test_backends_list_v2_api(metafunc)
if "test_backend" in metafunc.fixturenames:
metafunc.parametrize("test_backend", test_backends, scope="module")
if "test_backends" in metafunc.fixturenames:
metafunc.parametrize("test_backends", [test_backends], scope="module")
@dataclass(frozen=True)
class TestMarkerCoverage:
path: str
name: str
markers: set[str]
def __str__(self): # type: ignore[explicit-override] # FIXME
return f"{self.path}, {self.name}, {self.markers}"
def _verify_marker_coverage(
session,
) -> tuple[list[TestMarkerCoverage], list[TestMarkerCoverage]]:
uncovered: list[TestMarkerCoverage] = []
multiple_markers: list[TestMarkerCoverage] = []
for test in session.items:
markers = {m.name for m in test.iter_markers()}
required_intersection = markers.intersection(REQUIRED_MARKERS)
required_intersection_size = len(required_intersection)
# required_intersection_size is a non-zero integer so there 3 cases we care about:
# 0 => no marker coverage for this test
# 1 => the marker coverage for this test is correct
# >1 => too many markers are covering this test
if required_intersection_size == 0:
uncovered.append(
TestMarkerCoverage(path=str(test.path), name=test.name, markers=markers)
)
elif required_intersection_size > 1:
multiple_markers.append(
TestMarkerCoverage(
path=str(test.path), name=test.name, markers=required_intersection
)
)
return uncovered, multiple_markers
def pytest_collection_finish(session):
if session.config.option.verify_marker_coverage_and_exit:
uncovered, multiply_covered = _verify_marker_coverage(session)
if uncovered or multiply_covered:
print("*** Every test should be covered by exactly 1 of our required markers ***")
if uncovered:
print(f"*** {len(uncovered)} tests have no marker coverage ***")
for test_info in uncovered:
print(test_info)
print()
else:
print(f"*** {len(multiply_covered)} tests have multiple marker coverage ***")
for test_info in multiply_covered:
print(test_info)
print()
print("*** The required markers follow. ***")
print(
"*** Tests marked with 'performance' are not run in the PR or release pipeline. ***"
)
print("*** All other tests are. ***")
for m in REQUIRED_MARKERS:
print(m)
pytest.exit(
reason="Marker coverage verification failed",
returncode=pytest.ExitCode.TESTS_FAILED,
)
pytest.exit(
reason="Marker coverage verification succeeded",
returncode=pytest.ExitCode.OK,
)
def pytest_collection_modifyitems(config, items):
@dataclass
class Category:
mark: str
flag: str
reason: str
categories = (
Category(
mark="docs",
flag="--docs-tests",
reason="need --docs-tests option to run",
),
Category(mark="cloud", flag="--cloud", reason="need --cloud option to run"),
)
for category in categories:
# If flag is provided, exit early so we don't add `pytest.mark.skip`
if config.getoption(category.flag):
continue
# For each test collected, check if they use a mark that matches our flag name.
# If so, add a `pytest.mark.skip` dynamically.
for item in items:
if category.mark in item.keywords:
marker = pytest.mark.skip(reason=category.reason)
item.add_marker(marker)
@pytest.fixture(autouse=True)
def no_usage_stats(monkeypatch):
# Do not generate usage stats from test runs
monkeypatch.setattr(ENV_CONFIG, "gx_analytics_enabled", False)
@pytest.fixture(scope="session", autouse=True)
def preload_latest_gx_cache():
"""
Pre-load the _VersionChecker version cache so that we don't attempt to call pypi
when creating contexts as part of normal testing.
"""
# setup
import great_expectations as gx
current_version = packaging.version.Version(gx.__version__)
logger.info(f"Seeding _VersionChecker._LATEST_GX_VERSION_CACHE with {current_version}")
_VersionChecker._LATEST_GX_VERSION_CACHE = current_version
yield current_version
# teardown
logger.info("Clearing _VersionChecker._LATEST_GX_VERSION_CACHE ")
_VersionChecker._LATEST_GX_VERSION_CACHE = None
@pytest.fixture(scope="module")
def sa(test_backends):
if not any(
dbms in test_backends
for dbms in [
"postgresql",
"sqlite",
"mysql",
"mssql",
"bigquery",
"trino",
"redshift",
"athena",
"snowflake",
]
):
pytest.skip("No recognized sqlalchemy backend selected.")
else:
try:
from great_expectations.compatibility.sqlalchemy import sqlalchemy as sa
return sa
except ImportError:
raise ValueError("SQL Database tests require sqlalchemy to be installed.")
@pytest.mark.order(index=2)
@pytest.fixture
def spark_session(test_backends) -> pyspark.SparkSession:
from great_expectations.compatibility import pyspark
if pyspark.SparkSession: # type: ignore[truthy-function]
return SparkDFExecutionEngine.get_or_create_spark_session()
raise ValueError("spark tests are requested, but pyspark is not installed")
@pytest.fixture
def spark_connect_session(test_backends):
from great_expectations.compatibility import pyspark
if pyspark.SparkConnectSession: # type: ignore[truthy-function]
spark_connect_session = pyspark.SparkSession.builder.remote(
"sc://localhost:15002"
).getOrCreate()
assert isinstance(spark_connect_session, pyspark.SparkConnectSession)
return spark_connect_session
raise ValueError("spark tests are requested, but pyspark is not installed")
@pytest.fixture
def basic_spark_df_execution_engine(spark_session):
from great_expectations.execution_engine import SparkDFExecutionEngine
conf: List[tuple] = spark_session.sparkContext.getConf().getAll()
spark_config: Dict[str, Any] = dict(conf)
execution_engine = SparkDFExecutionEngine(
spark_config=spark_config,
)
return execution_engine
@pytest.fixture
def spark_df_taxi_data_schema(spark_session):
"""
Fixture used by tests for providing schema to SparkDFExecutionEngine.
The schema returned by this fixture corresponds to taxi_tripdata
"""
# will not import unless we have a spark_session already passed in as fixture
from great_expectations.compatibility import pyspark
schema = pyspark.types.StructType(
[
pyspark.types.StructField("vendor_id", pyspark.types.IntegerType(), True, None),
pyspark.types.StructField("pickup_datetime", pyspark.types.TimestampType(), True, None),
pyspark.types.StructField(
"dropoff_datetime", pyspark.types.TimestampType(), True, None
),
pyspark.types.StructField("passenger_count", pyspark.types.IntegerType(), True, None),
pyspark.types.StructField("trip_distance", pyspark.types.DoubleType(), True, None),
pyspark.types.StructField("rate_code_id", pyspark.types.IntegerType(), True, None),
pyspark.types.StructField("store_and_fwd_flag", pyspark.types.StringType(), True, None),
pyspark.types.StructField(
"pickup_location_id", pyspark.types.IntegerType(), True, None
),
pyspark.types.StructField(
"dropoff_location_id", pyspark.types.IntegerType(), True, None
),
pyspark.types.StructField("payment_type", pyspark.types.IntegerType(), True, None),
pyspark.types.StructField("fare_amount", pyspark.types.DoubleType(), True, None),
pyspark.types.StructField("extra", pyspark.types.DoubleType(), True, None),
pyspark.types.StructField("mta_tax", pyspark.types.DoubleType(), True, None),
pyspark.types.StructField("tip_amount", pyspark.types.DoubleType(), True, None),
pyspark.types.StructField("tolls_amount", pyspark.types.DoubleType(), True, None),
pyspark.types.StructField(
"improvement_surcharge", pyspark.types.DoubleType(), True, None
),
pyspark.types.StructField("total_amount", pyspark.types.DoubleType(), True, None),
pyspark.types.StructField(
"congestion_surcharge", pyspark.types.DoubleType(), True, None
),
]
)
return schema
@pytest.mark.order(index=3)
@pytest.fixture
def spark_session_v012(test_backends):
try:
import pyspark # noqa: F401
from pyspark.sql import SparkSession # noqa: F401
return SparkDFExecutionEngine.get_or_create_spark_session()
except ImportError:
raise ValueError("spark tests are requested, but pyspark is not installed")
@pytest.fixture
def basic_expectation_suite():
expectation_suite = ExpectationSuite(
name="default",
meta={},
expectations=[
ExpectationConfiguration(
type="expect_column_to_exist",
kwargs={"column": "infinities"},
),
ExpectationConfiguration(type="expect_column_to_exist", kwargs={"column": "nulls"}),
ExpectationConfiguration(type="expect_column_to_exist", kwargs={"column": "naturals"}),
ExpectationConfiguration(
type="expect_column_values_to_be_unique",
kwargs={"column": "naturals"},
),
],
)
return expectation_suite
@pytest.fixture(scope="function")
def empty_data_context(
tmp_path,
) -> FileDataContext:
project_path = tmp_path / "empty_data_context"
project_path.mkdir()
project_path = str(project_path)
context = gx.get_context(mode="file", project_root_dir=project_path)
context_path = os.path.join(project_path, FileDataContext.GX_DIR) # noqa: PTH118
asset_config_path = os.path.join(context_path, "expectations") # noqa: PTH118
os.makedirs(asset_config_path, exist_ok=True) # noqa: PTH103
assert context.list_datasources() == []
project_manager.set_project(context)
return context
@pytest.fixture
def titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled( # noqa: E501
tmp_path_factory,
monkeypatch,
):
project_path: str = str(tmp_path_factory.mktemp("titanic_data_context_013"))
context_path: str = os.path.join( # noqa: PTH118
project_path, FileDataContext.GX_DIR
)
os.makedirs( # noqa: PTH103
os.path.join(context_path, "expectations"), # noqa: PTH118
exist_ok=True,
)
os.makedirs( # noqa: PTH103
os.path.join(context_path, "plugins"), # noqa: PTH118
exist_ok=True,
)
shutil.copy(
file_relative_path(
__file__,
str(
pathlib.Path(
"data_context",
"fixtures",
"plugins",
"extended_checkpoint.py",
)
),
),
pathlib.Path(context_path) / "plugins" / "extended_checkpoint.py",
)
data_path: str = os.path.join(context_path, "..", "data", "titanic") # noqa: PTH118
os.makedirs(os.path.join(data_path), exist_ok=True) # noqa: PTH118, PTH103
shutil.copy(
file_relative_path(
__file__,
str(
pathlib.Path(
"test_fixtures",
"great_expectations_v013_no_datasource_stats_enabled.yml",
)
),
),
str(os.path.join(context_path, FileDataContext.GX_YML)), # noqa: PTH118
)
shutil.copy(
file_relative_path(
__file__,
os.path.join("test_sets", "Titanic.csv"), # noqa: PTH118
),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_19120414_1313.csv"
)
),
)
shutil.copy(
file_relative_path(
__file__,
os.path.join("test_sets", "Titanic.csv"), # noqa: PTH118
),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_19120414_1313"
)
),
)
shutil.copy(
file_relative_path(
__file__,
os.path.join("test_sets", "Titanic.csv"), # noqa: PTH118
),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_1911.csv"
)
),
)
shutil.copy(
file_relative_path(
__file__,
os.path.join("test_sets", "Titanic.csv"), # noqa: PTH118
),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_1912.csv"
)
),
)
context = get_context(context_root_dir=context_path)
assert context.root_directory == context_path
context._save_project_config()
project_manager.set_project(context)
return context
@pytest.fixture
def titanic_v013_multi_datasource_pandas_data_context_with_checkpoints_v1_with_empty_store_stats_enabled( # noqa: E501
titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled,
tmp_path_factory,
monkeypatch,
):
context = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled # noqa: E501
project_manager.set_project(context)
return context
@pytest.fixture
def titanic_v013_multi_datasource_pandas_and_sqlalchemy_execution_engine_data_context_with_checkpoints_v1_with_empty_store_stats_enabled( # noqa: E501
sa,
titanic_v013_multi_datasource_pandas_data_context_with_checkpoints_v1_with_empty_store_stats_enabled: AbstractDataContext, # noqa: E501
tmp_path_factory,
test_backends,
monkeypatch,
):
context = titanic_v013_multi_datasource_pandas_data_context_with_checkpoints_v1_with_empty_store_stats_enabled # noqa: E501
project_dir = context.root_directory
assert isinstance(project_dir, str)
data_path: str = os.path.join(project_dir, "..", "data", "titanic") # noqa: PTH118
if (
any(dbms in test_backends for dbms in ["postgresql", "sqlite", "mysql", "mssql"])
and (sa is not None)
and is_library_loadable(library_name="sqlalchemy")
):
db_fixture_file_path: str = file_relative_path(
__file__,
os.path.join("test_sets", "titanic_sql_test_cases.db"), # noqa: PTH118
)
db_file_path: str = os.path.join( # noqa: PTH118
data_path,
"titanic_sql_test_cases.db",
)
shutil.copy(
db_fixture_file_path,
db_file_path,
)
context.data_sources.add_sqlite(
name="my_sqlite_db_datasource",
connection_string=f"sqlite:///{db_file_path}",
)
return context
@pytest.fixture
def titanic_v013_multi_datasource_multi_execution_engine_data_context_with_checkpoints_v1_with_empty_store_stats_enabled( # noqa: E501
sa,
spark_session,
titanic_v013_multi_datasource_pandas_and_sqlalchemy_execution_engine_data_context_with_checkpoints_v1_with_empty_store_stats_enabled,
tmp_path_factory,
test_backends,
monkeypatch,
):
context = titanic_v013_multi_datasource_pandas_and_sqlalchemy_execution_engine_data_context_with_checkpoints_v1_with_empty_store_stats_enabled # noqa: E501
project_manager.set_project(context)
return context
@pytest.fixture
def deterministic_asset_data_connector_context(
tmp_path_factory,
monkeypatch,
):
project_path = str(tmp_path_factory.mktemp("titanic_data_context"))
context_path = os.path.join(project_path, FileDataContext.GX_DIR) # noqa: PTH118
os.makedirs( # noqa: PTH103
os.path.join(context_path, "expectations"), # noqa: PTH118
exist_ok=True,
)
data_path = os.path.join(context_path, "..", "data", "titanic") # noqa: PTH118
os.makedirs(os.path.join(data_path), exist_ok=True) # noqa: PTH118, PTH103
shutil.copy(
file_relative_path(
__file__,
str(
pathlib.Path(
"test_fixtures",
"great_expectations_v013_no_datasource_stats_enabled.yml",
)
),
),
str(os.path.join(context_path, FileDataContext.GX_YML)), # noqa: PTH118
)
shutil.copy(
file_relative_path(__file__, "./test_sets/Titanic.csv"),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_19120414_1313.csv"
)
),
)
shutil.copy(
file_relative_path(__file__, "./test_sets/Titanic.csv"),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_1911.csv"
)
),
)
shutil.copy(
file_relative_path(__file__, "./test_sets/Titanic.csv"),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_1912.csv"
)
),
)
context = get_context(context_root_dir=context_path)
assert context.root_directory == context_path
context._save_project_config()
project_manager.set_project(context)
return context
@pytest.fixture
def titanic_data_context_with_fluent_pandas_datasources_with_checkpoints_v1_with_empty_store_stats_enabled( # noqa: E501
tmp_path_factory,
monkeypatch,
):
project_path: str = str(tmp_path_factory.mktemp("titanic_data_context_013"))
context_path: str = os.path.join( # noqa: PTH118
project_path, FileDataContext.GX_DIR
)
os.makedirs( # noqa: PTH103
os.path.join(context_path, "expectations"), # noqa: PTH118
exist_ok=True,
)
data_path: str = os.path.join(context_path, "..", "data", "titanic") # noqa: PTH118
os.makedirs(os.path.join(data_path), exist_ok=True) # noqa: PTH118, PTH103
shutil.copy(
file_relative_path(
__file__,
str(
pathlib.Path(
"test_fixtures",
"great_expectations_no_block_no_fluent_datasources_stats_enabled.yml",
)
),
),
str(os.path.join(context_path, FileDataContext.GX_YML)), # noqa: PTH118
)
os.makedirs( # noqa: PTH103
os.path.join(context_path, "plugins"), # noqa: PTH118
exist_ok=True,
)
shutil.copy(
file_relative_path(
__file__,
str(
pathlib.Path(
"data_context",
"fixtures",
"plugins",
"extended_checkpoint.py",
)
),
),
pathlib.Path(context_path) / "plugins" / "extended_checkpoint.py",
)
shutil.copy(
file_relative_path(
__file__,
os.path.join("test_sets", "Titanic.csv"), # noqa: PTH118
),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_19120414_1313.csv"
)
),
)
shutil.copy(
file_relative_path(
__file__,
os.path.join("test_sets", "Titanic.csv"), # noqa: PTH118
),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_19120414_1313"
)
),
)
shutil.copy(
file_relative_path(
__file__,
os.path.join("test_sets", "Titanic.csv"), # noqa: PTH118
),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_1911.csv"
)
),
)
shutil.copy(
file_relative_path(
__file__,
os.path.join("test_sets", "Titanic.csv"), # noqa: PTH118
),
str(
os.path.join( # noqa: PTH118
context_path, "..", "data", "titanic", "Titanic_1912.csv"
)
),
)
context = get_context(context_root_dir=context_path)
assert context.root_directory == context_path
path_to_folder_containing_csv_files = pathlib.Path(data_path)
datasource_name = "my_pandas_filesystem_datasource"
datasource = context.data_sources.add_pandas_filesystem(
name=datasource_name, base_directory=path_to_folder_containing_csv_files
)
batching_regex = r"(?P<name>.+)\.csv"
glob_directive = "*.csv"
datasource.add_csv_asset(
name="exploration", batching_regex=batching_regex, glob_directive=glob_directive
)
batching_regex = r"(.+)_(?P<timestamp>\d{8})_(?P<size>\d{4})\.csv"
glob_directive = "*.csv"
datasource.add_csv_asset(
name="users", batching_regex=batching_regex, glob_directive=glob_directive
)
datasource_name = "my_pandas_dataframes_datasource"
datasource = context.data_sources.add_pandas(name=datasource_name)
csv_source_path = pathlib.Path(
context_path,
"..",
"data",
"titanic",
"Titanic_1911.csv",
)
df = pd.read_csv(filepath_or_buffer=csv_source_path)
dataframe_asset_name = "my_dataframe_asset"
asset = datasource.add_dataframe_asset(name=dataframe_asset_name)
_ = asset.build_batch_request(options={"dataframe": df})
# noinspection PyProtectedMember
context._save_project_config()
project_manager.set_project(context)
return context
@pytest.fixture
def titanic_data_context_with_fluent_pandas_and_spark_datasources_with_checkpoints_v1_with_empty_store_stats_enabled( # noqa: E501
titanic_data_context_with_fluent_pandas_datasources_with_checkpoints_v1_with_empty_store_stats_enabled,
spark_df_from_pandas_df,
spark_session,
):
context = titanic_data_context_with_fluent_pandas_datasources_with_checkpoints_v1_with_empty_store_stats_enabled # noqa: E501
context_path: str = context.root_directory
path_to_folder_containing_csv_files = pathlib.Path(
context_path,
"..",
"data",
"titanic",
)
datasource_name = "my_spark_filesystem_datasource"
datasource = context.data_sources.add_spark_filesystem(
name=datasource_name, base_directory=path_to_folder_containing_csv_files
)
batching_regex = r"(?P<name>.+)\.csv"
glob_directive = "*.csv"
datasource.add_csv_asset(