/
expectation.py
2430 lines (2139 loc) · 92 KB
/
expectation.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 glob
import json
import logging
import os
import traceback
import warnings
from abc import ABC, ABCMeta, abstractmethod
from collections import Counter
from copy import deepcopy
from inspect import isabstract
from typing import Dict, List, Optional, Tuple, Union
from dateutil.parser import parse
from great_expectations import __version__ as ge_version
from great_expectations.core.expectation_configuration import (
ExpectationConfiguration,
parse_result_format,
)
from great_expectations.core.expectation_diagnostics.expectation_diagnostics import (
ExpectationDiagnostics,
)
from great_expectations.core.expectation_diagnostics.expectation_test_data_cases import (
ExpectationLegacyTestCaseAdapter,
ExpectationTestCase,
ExpectationTestDataCases,
TestBackend,
TestData,
)
from great_expectations.core.expectation_diagnostics.supporting_types import (
AugmentedLibraryMetadata,
ExpectationBackendTestResultCounts,
ExpectationDescriptionDiagnostics,
ExpectationDiagnosticMaturityMessages,
ExpectationErrorDiagnostics,
ExpectationExecutionEngineDiagnostics,
ExpectationMetricDiagnostics,
ExpectationRendererDiagnostics,
ExpectationTestDiagnostics,
RendererTestDiagnostics,
)
from great_expectations.core.expectation_validation_result import (
ExpectationValidationResult,
)
from great_expectations.core.util import nested_update
from great_expectations.exceptions import (
GreatExpectationsError,
InvalidExpectationConfigurationError,
InvalidExpectationKwargsError,
)
from great_expectations.execution_engine import ExecutionEngine, PandasExecutionEngine
from great_expectations.execution_engine.execution_engine import MetricDomainTypes
from great_expectations.expectations.registry import (
_registered_metrics,
_registered_renderers,
get_expectation_impl,
get_metric_kwargs,
register_expectation,
register_renderer,
)
from great_expectations.expectations.util import render_evaluation_parameter_string
from great_expectations.render.renderer.renderer import renderer
from great_expectations.render.types import (
CollapseContent,
RenderedAtomicContent,
RenderedContentBlockContainer,
RenderedGraphContent,
RenderedStringTemplateContent,
RenderedTableContent,
ValueListContent,
renderedAtomicValueSchema,
)
from great_expectations.render.util import num_to_str
from great_expectations.rule_based_profiler.config.base import RuleBasedProfilerConfig
from great_expectations.self_check.util import (
evaluate_json_test_cfe,
generate_expectation_tests,
)
from great_expectations.util import camel_to_snake, is_parseable_date
from great_expectations.validator.metric_configuration import MetricConfiguration
from great_expectations.validator.validator import Validator
logger = logging.getLogger(__name__)
_TEST_DEFS_DIR = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"tests",
"test_definitions",
)
# noinspection PyMethodParameters
class MetaExpectation(ABCMeta):
"""MetaExpectation registers Expectations as they are defined, adding them to the Expectation registry.
Any class inheriting from Expectation will be registered based on the value of the "expectation_type" class
attribute, or, if that is not set, by snake-casing the name of the class.
"""
def __new__(cls, clsname, bases, attrs):
newclass = super().__new__(cls, clsname, bases, attrs)
# noinspection PyUnresolvedReferences
if not newclass.is_abstract():
newclass.expectation_type = camel_to_snake(clsname)
register_expectation(newclass)
# noinspection PyUnresolvedReferences
newclass._register_renderer_functions()
default_kwarg_values = {}
for base in reversed(bases):
default_kwargs = getattr(base, "default_kwarg_values", {})
default_kwarg_values = nested_update(default_kwarg_values, default_kwargs)
newclass.default_kwarg_values = nested_update(
default_kwarg_values, attrs.get("default_kwarg_values", {})
)
return newclass
class Expectation(metaclass=MetaExpectation):
"""Base class for all Expectations.
Expectation classes *must* have the following attributes set:
1. `domain_keys`: a tuple of the *keys* used to determine the domain of the
expectation
2. `success_keys`: a tuple of the *keys* used to determine the success of
the expectation.
In some cases, subclasses of Expectation (such as TableExpectation) can
inherit these properties from their parent class.
They *may* optionally override `runtime_keys` and `default_kwarg_values`, and
may optionally set an explicit value for expectation_type.
1. runtime_keys lists the keys that can be used to control output but will
not affect the actual success value of the expectation (such as result_format).
2. default_kwarg_values is a dictionary that will be used to fill unspecified
kwargs from the Expectation Configuration.
Expectation classes *must* implement the following:
1. `_validate`
2. `get_validation_dependencies`
In some cases, subclasses of Expectation, such as ColumnMapExpectation will already
have correct implementations that may simply be inherited.
Additionally, they *may* provide implementations of:
1. `validate_configuration`, which should raise an error if the configuration
will not be usable for the Expectation
2. Data Docs rendering methods decorated with the @renderer decorator. See the
"""
version = ge_version
domain_keys = tuple()
success_keys = tuple()
runtime_keys = (
"include_config",
"catch_exceptions",
"result_format",
)
default_kwarg_values = {
"include_config": True,
"catch_exceptions": False,
"result_format": "BASIC",
}
args_keys = None
def __init__(self, configuration: Optional[ExpectationConfiguration] = None):
if configuration is not None:
self.validate_configuration(configuration)
self._configuration = configuration
@classmethod
def is_abstract(cls):
return isabstract(cls)
@classmethod
def _register_renderer_functions(cls):
expectation_type = camel_to_snake(cls.__name__)
for candidate_renderer_fn_name in dir(cls):
attr_obj = getattr(cls, candidate_renderer_fn_name)
if not hasattr(attr_obj, "_renderer_type"):
continue
register_renderer(
object_name=expectation_type, parent_class=cls, renderer_fn=attr_obj
)
@abstractmethod
def _validate(
self,
configuration: ExpectationConfiguration,
metrics: dict,
runtime_configuration: dict = None,
execution_engine: ExecutionEngine = None,
):
raise NotImplementedError
@classmethod
def _atomic_prescriptive_template(
cls,
configuration=None,
result=None,
language=None,
runtime_configuration=None,
**kwargs,
):
"""
Template function that contains the logic that is shared by atomic.prescriptive.summary (GE Cloud) and
renderer.prescriptive (OSS GE)
"""
if runtime_configuration is None:
runtime_configuration = {}
styling = runtime_configuration.get("styling")
template_str = "$expectation_type(**$kwargs)"
params = {
"expectation_type": configuration.expectation_type,
"kwargs": configuration.kwargs,
}
params_with_json_schema = {
"expectation_type": {
"schema": {"type": "string"},
"value": configuration.expectation_type,
},
"kwargs": {"schema": {"type": "string"}, "value": configuration.kwargs},
}
return (template_str, params_with_json_schema, styling)
@classmethod
@renderer(renderer_type="atomic.prescriptive.summary")
@render_evaluation_parameter_string
def _prescriptive_summary(
cls,
configuration=None,
result=None,
language=None,
runtime_configuration=None,
**kwargs,
):
"""
Rendering function that is utilized by GE Cloud Front-end
"""
(
template_str,
params_with_json_schema,
styling,
) = cls._atomic_prescriptive_template(
configuration, result, language, runtime_configuration, **kwargs
)
value_obj = renderedAtomicValueSchema.load(
{
"template": template_str,
"params": params_with_json_schema,
"schema": {"type": "com.superconductive.rendered.string"},
}
)
rendered = RenderedAtomicContent(
name="atomic.prescriptive.summary",
value=value_obj,
value_type="StringValueType",
)
return rendered
@classmethod
@renderer(renderer_type="renderer.prescriptive")
def _prescriptive_renderer(
cls,
configuration=None,
result=None,
language=None,
runtime_configuration=None,
**kwargs,
):
return [
RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"styling": {"parent": {"classes": ["alert", "alert-warning"]}},
"string_template": {
"template": "$expectation_type(**$kwargs)",
"params": {
"expectation_type": configuration.expectation_type,
"kwargs": configuration.kwargs,
},
"styling": {
"params": {
"expectation_type": {
"classes": ["badge", "badge-warning"],
}
}
},
},
}
)
]
@classmethod
@renderer(renderer_type="renderer.diagnostic.meta_properties")
def _diagnostic_meta_properties_renderer(cls, result=None, **kwargs):
"""
Render function used to add custom meta to Data Docs
It gets a column set in the `properties_to_render` dictionary within `meta` and adds columns in Data Docs with the values that were set.
example:
meta = {
"properties_to_render": {
"Custom Column Header": "custom.value"
},
"custom": {
"value": "1"
}
}
data docs:
----------------------------------------------------------------
| status| Expectation | Observed value | Custom Column Header |
----------------------------------------------------------------
| | must be exactly 4 columns | 4 | 1 |
Here the custom column will be added in data docs.
"""
if result is None:
return []
custom_property_values = []
meta_properties_to_render = result.expectation_config.kwargs.get(
"meta_properties_to_render", None
)
if meta_properties_to_render is not None:
for key in sorted(meta_properties_to_render.keys()):
meta_property = meta_properties_to_render[key]
if meta_property is not None:
try:
# Allow complex structure with . usage
obj = result.expectation_config.meta["attributes"]
keys = meta_property.split(".")
for i in range(0, len(keys)):
# Allow for keys with a . in the string like {"item.key": "1"}
remaining_key = "".join(keys[i:])
if remaining_key in obj:
obj = obj[remaining_key]
break
else:
obj = obj[keys[i]]
custom_property_values.append([obj])
except KeyError:
custom_property_values.append(["N/A"])
else:
custom_property_values.append(["N/A"])
return custom_property_values
@classmethod
@renderer(renderer_type="renderer.diagnostic.status_icon")
def _diagnostic_status_icon_renderer(
cls,
configuration=None,
result=None,
language=None,
runtime_configuration=None,
**kwargs,
):
assert result, "Must provide a result object."
if result.exception_info["raised_exception"]:
return RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": "$icon",
"params": {"icon": "", "markdown_status_icon": "❗"},
"styling": {
"params": {
"icon": {
"classes": [
"fas",
"fa-exclamation-triangle",
"text-warning",
],
"tag": "i",
}
}
},
},
}
)
if result.success:
return RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": "$icon",
"params": {"icon": "", "markdown_status_icon": "✅"},
"styling": {
"params": {
"icon": {
"classes": [
"fas",
"fa-check-circle",
"text-success",
],
"tag": "i",
}
}
},
},
"styling": {
"parent": {
"classes": ["hide-succeeded-validation-target-child"]
}
},
}
)
else:
return RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": "$icon",
"params": {"icon": "", "markdown_status_icon": "❌"},
"styling": {
"params": {
"icon": {
"tag": "i",
"classes": ["fas", "fa-times", "text-danger"],
}
}
},
},
}
)
@classmethod
@renderer(renderer_type="renderer.diagnostic.unexpected_statement")
def _diagnostic_unexpected_statement_renderer(
cls,
configuration=None,
result=None,
language=None,
runtime_configuration=None,
**kwargs,
):
assert result, "Must provide a result object."
success = result.success
result_dict = result.result
if result.exception_info["raised_exception"]:
exception_message_template_str = (
"\n\n$expectation_type raised an exception:\n$exception_message"
)
exception_message = RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": exception_message_template_str,
"params": {
"expectation_type": result.expectation_config.expectation_type,
"exception_message": result.exception_info[
"exception_message"
],
},
"tag": "strong",
"styling": {
"classes": ["text-danger"],
"params": {
"exception_message": {"tag": "code"},
"expectation_type": {
"classes": ["badge", "badge-danger", "mb-2"]
},
},
},
},
}
)
exception_traceback_collapse = CollapseContent(
**{
"collapse_toggle_link": "Show exception traceback...",
"collapse": [
RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": result.exception_info[
"exception_traceback"
],
"tag": "code",
},
}
)
],
}
)
return [exception_message, exception_traceback_collapse]
if success or not result_dict.get("unexpected_count"):
return []
else:
unexpected_count = num_to_str(
result_dict["unexpected_count"], use_locale=True, precision=20
)
unexpected_percent = (
f"{num_to_str(result_dict['unexpected_percent'], precision=4)}%"
)
element_count = num_to_str(
result_dict["element_count"], use_locale=True, precision=20
)
template_str = (
"\n\n$unexpected_count unexpected values found. "
"$unexpected_percent of $element_count total rows."
)
return [
RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": template_str,
"params": {
"unexpected_count": unexpected_count,
"unexpected_percent": unexpected_percent,
"element_count": element_count,
},
"tag": "strong",
"styling": {"classes": ["text-danger"]},
},
}
)
]
@classmethod
@renderer(renderer_type="renderer.diagnostic.unexpected_table")
def _diagnostic_unexpected_table_renderer(
cls,
configuration=None,
result=None,
language=None,
runtime_configuration=None,
**kwargs,
):
try:
result_dict = result.result
except KeyError:
return None
if result_dict is None:
return None
if not result_dict.get("partial_unexpected_list") and not result_dict.get(
"partial_unexpected_counts"
):
return None
table_rows = []
if result_dict.get("partial_unexpected_counts"):
# We will check to see whether we have *all* of the unexpected values
# accounted for in our count, and include counts if we do. If we do not,
# we will use this as simply a better (non-repeating) source of
# "sampled" unexpected values
total_count = 0
for unexpected_count_dict in result_dict.get("partial_unexpected_counts"):
value = unexpected_count_dict.get("value")
count = unexpected_count_dict.get("count")
total_count += count
if value is not None and value != "":
table_rows.append([value, count])
elif value == "":
table_rows.append(["EMPTY", count])
else:
table_rows.append(["null", count])
# Check to see if we have *all* of the unexpected values accounted for. If so,
# we show counts. If not, we only show "sampled" unexpected values.
if total_count == result_dict.get("unexpected_count"):
header_row = ["Unexpected Value", "Count"]
else:
header_row = ["Sampled Unexpected Values"]
table_rows = [[row[0]] for row in table_rows]
else:
header_row = ["Sampled Unexpected Values"]
sampled_values_set = set()
for unexpected_value in result_dict.get("partial_unexpected_list"):
if unexpected_value:
string_unexpected_value = str(unexpected_value)
elif unexpected_value == "":
string_unexpected_value = "EMPTY"
else:
string_unexpected_value = "null"
if string_unexpected_value not in sampled_values_set:
table_rows.append([unexpected_value])
sampled_values_set.add(string_unexpected_value)
unexpected_table_content_block = RenderedTableContent(
**{
"content_block_type": "table",
"table": table_rows,
"header_row": header_row,
"styling": {
"body": {"classes": ["table-bordered", "table-sm", "mt-3"]}
},
}
)
return unexpected_table_content_block
@classmethod
def _get_observed_value_from_evr(self, result: ExpectationValidationResult) -> str:
result_dict = result.result
if result_dict is None:
return "--"
if result_dict.get("observed_value") is not None:
observed_value = result_dict.get("observed_value")
if isinstance(observed_value, (int, float)) and not isinstance(
observed_value, bool
):
return num_to_str(observed_value, precision=10, use_locale=True)
return str(observed_value)
elif result_dict.get("unexpected_percent") is not None:
return (
num_to_str(result_dict.get("unexpected_percent"), precision=5)
+ "% unexpected"
)
else:
return "--"
@classmethod
@renderer(renderer_type="atomic.diagnostic.observed_value")
def _atomic_diagnostic_observed_value(
cls,
configuration=None,
result=None,
language=None,
runtime_configuration=None,
**kwargs,
):
"""
Rendering function that is utilized by GE Cloud Front-end
"""
observed_value = cls._get_observed_value_from_evr(result=result)
value_obj = renderedAtomicValueSchema.load(
{
"template": observed_value,
"params": {},
"schema": {"type": "com.superconductive.rendered.string"},
}
)
rendered = RenderedAtomicContent(
name="atomic.diagnostic.observed_value",
value=value_obj,
value_type="StringValueType",
)
return rendered
@classmethod
@renderer(renderer_type="renderer.diagnostic.observed_value")
def _diagnostic_observed_value_renderer(
cls,
configuration=None,
result=None,
language=None,
runtime_configuration=None,
**kwargs,
):
return cls._get_observed_value_from_evr(result=result)
@classmethod
def get_allowed_config_keys(cls):
return cls.domain_keys + cls.success_keys + cls.runtime_keys
def metrics_validate(
self,
metrics: Dict,
configuration: Optional[ExpectationConfiguration] = None,
runtime_configuration: dict = None,
execution_engine: ExecutionEngine = None,
) -> ExpectationValidationResult:
if configuration is None:
configuration = self.configuration
validation_dependencies: dict = self.get_validation_dependencies(
configuration,
execution_engine=execution_engine,
runtime_configuration=runtime_configuration,
)
runtime_configuration["result_format"] = validation_dependencies[
"result_format"
]
requested_metrics = validation_dependencies["metrics"]
provided_metrics = {}
for name, metric_edge_key in requested_metrics.items():
provided_metrics[name] = metrics[metric_edge_key.id]
expectation_validation_result: Union[
ExpectationValidationResult, dict
] = self._validate(
configuration=configuration,
metrics=provided_metrics,
runtime_configuration=runtime_configuration,
execution_engine=execution_engine,
)
evr: ExpectationValidationResult = self._build_evr(
raw_response=expectation_validation_result, configuration=configuration
)
return evr
@staticmethod
def _build_evr(raw_response, configuration) -> ExpectationValidationResult:
"""_build_evr is a lightweight convenience wrapper handling cases where an Expectation implementor
fails to return an EVR but returns the necessary components in a dictionary."""
if not isinstance(raw_response, ExpectationValidationResult):
if isinstance(raw_response, dict):
evr = ExpectationValidationResult(**raw_response)
evr.expectation_config = configuration
else:
raise GreatExpectationsError("Unable to build EVR")
else:
evr = raw_response
evr.expectation_config = configuration
return evr
def get_validation_dependencies(
self,
configuration: Optional[ExpectationConfiguration] = None,
execution_engine: Optional[ExecutionEngine] = None,
runtime_configuration: Optional[dict] = None,
) -> dict:
"""Returns the result format and metrics required to validate this Expectation using the provided result format."""
runtime_configuration = self.get_runtime_kwargs(
configuration=configuration,
runtime_configuration=runtime_configuration,
)
result_format: dict = runtime_configuration["result_format"]
result_format = parse_result_format(result_format=result_format)
return {
"result_format": result_format,
"metrics": {},
}
def get_domain_kwargs(
self, configuration: Optional[ExpectationConfiguration] = None
):
if not configuration:
configuration = self.configuration
domain_kwargs = {
key: configuration.kwargs.get(key, self.default_kwarg_values.get(key))
for key in self.domain_keys
}
# Process evaluation parameter dependencies
missing_kwargs = set(self.domain_keys) - set(domain_kwargs.keys())
if missing_kwargs:
raise InvalidExpectationKwargsError(
f"Missing domain kwargs: {list(missing_kwargs)}"
)
return domain_kwargs
def get_success_kwargs(
self, configuration: Optional[ExpectationConfiguration] = None
):
if not configuration:
configuration = self.configuration
domain_kwargs = self.get_domain_kwargs(configuration)
success_kwargs = {
key: configuration.kwargs.get(key, self.default_kwarg_values.get(key))
for key in self.success_keys
}
success_kwargs.update(domain_kwargs)
return success_kwargs
def get_runtime_kwargs(
self,
configuration: Optional[ExpectationConfiguration] = None,
runtime_configuration: dict = None,
) -> dict:
if not configuration:
configuration = self.configuration
configuration = deepcopy(configuration)
if runtime_configuration:
configuration.kwargs.update(runtime_configuration)
success_kwargs = self.get_success_kwargs(configuration)
runtime_kwargs = {
key: configuration.kwargs.get(key, self.default_kwarg_values.get(key))
for key in self.runtime_keys
}
runtime_kwargs.update(success_kwargs)
runtime_kwargs["result_format"] = parse_result_format(
runtime_kwargs["result_format"]
)
return runtime_kwargs
def get_result_format(
self,
configuration: ExpectationConfiguration,
runtime_configuration: dict = None,
) -> dict:
default_result_format: Optional[
Union[bool, str]
] = self.default_kwarg_values.get("result_format")
configuration_result_format: dict = configuration.kwargs.get(
"result_format", default_result_format
)
result_format: dict
if runtime_configuration:
result_format = runtime_configuration.get(
"result_format",
configuration_result_format,
)
else:
result_format = configuration_result_format
return result_format
def validate_configuration(self, configuration: Optional[ExpectationConfiguration]):
if configuration is None:
configuration = self.configuration
try:
assert (
configuration.expectation_type == self.expectation_type
), f"expectation configuration type {configuration.expectation_type} does not match expectation type {self.expectation_type}"
except AssertionError as e:
raise InvalidExpectationConfigurationError(str(e))
def validate(
self,
validator: Validator,
configuration: Optional[ExpectationConfiguration] = None,
evaluation_parameters=None,
interactive_evaluation=True,
data_context=None,
runtime_configuration=None,
):
if configuration is None:
configuration = deepcopy(self.configuration)
configuration.process_evaluation_parameters(
evaluation_parameters, interactive_evaluation, data_context
)
evr = validator.graph_validate(
configurations=[configuration],
runtime_configuration=runtime_configuration,
)[0]
return evr
@property
def configuration(self):
if self._configuration is None:
raise InvalidExpectationConfigurationError(
"cannot access configuration: expectation has not yet been configured"
)
return self._configuration
@classmethod
def build_configuration(cls, *args, **kwargs):
# Combine all arguments into a single new "all_args" dictionary to name positional parameters
all_args = dict(zip(cls.validation_kwargs, args))
all_args.update(kwargs)
# Unpack display parameters; remove them from all_args if appropriate
if "include_config" in kwargs:
include_config = kwargs["include_config"]
del all_args["include_config"]
else:
include_config = cls.default_expectation_args["include_config"]
if "catch_exceptions" in kwargs:
catch_exceptions = kwargs["catch_exceptions"]
del all_args["catch_exceptions"]
else:
catch_exceptions = cls.default_expectation_args["catch_exceptions"]
if "result_format" in kwargs:
result_format = kwargs["result_format"]
else:
result_format = cls.default_expectation_args["result_format"]
# Extract the meta object for use as a top-level expectation_config holder
if "meta" in kwargs:
meta = kwargs["meta"]
del all_args["meta"]
else:
meta = None
# Construct the expectation_config object
return ExpectationConfiguration(
expectation_type=cls.expectation_type,
kwargs=convert_to_json_serializable(deepcopy(all_args)),
meta=meta,
)
def run_diagnostics(
self,
raise_exceptions_for_backends: bool = False,
) -> ExpectationDiagnostics:
"""Produce a diagnostic report about this Expectation.
The current uses for this method's output are
using the JSON structure to populate the Public Expectation Gallery
and enabling a fast dev loop for developing new Expectations where the
contributors can quickly check the completeness of their expectations.
The contents of the report are captured in the ExpectationDiagnostics dataclass.
You can see some examples in test_expectation_diagnostics.py
Some components (e.g. description, examples, library_metadata) of the diagnostic report can be introspected directly from the Exepctation class.
Other components (e.g. metrics, renderers, executions) are at least partly dependent on instantiating, validating, and/or executing the Expectation class.
For these kinds of components, at least one test case with include_in_gallery=True must be present in the examples to
produce the metrics, renderers and execution engines parts of the report. This is due to
a get_validation_dependencies requiring expectation_config as an argument.
If errors are encountered in the process of running the diagnostics, they are assumed to be due to
incompleteness of the Expectation's implementation (e.g., declaring a dependency on Metrics
that do not exist). These errors are added under "errors" key in the report.
"""
errors: List[ExpectationErrorDiagnostics] = []
library_metadata: ExpectationDescriptionDiagnostics = (
self._get_augmented_library_metadata()
)
examples: List[ExpectationTestDataCases] = self._get_examples(
return_only_gallery_examples=False
)
gallery_examples: List[ExpectationTestDataCases] = []
for example in examples:
_tests_to_include = [
test for test in example.tests if test.include_in_gallery
]
example = deepcopy(example)
if _tests_to_include:
example.tests = _tests_to_include
gallery_examples.append(example)
description_diagnostics: ExpectationDescriptionDiagnostics = (
self._get_description_diagnostics()
)
_expectation_config: ExpectationConfiguration = (
self._get_expectation_configuration_from_examples(examples)
)
metric_diagnostics_list: List[
ExpectationMetricDiagnostics
] = self._get_metric_diagnostics_list(
expectation_config=_expectation_config,
)
introspected_execution_engines: ExpectationExecutionEngineDiagnostics = (
self._get_execution_engine_diagnostics(
metric_diagnostics_list=metric_diagnostics_list,
registered_metrics=_registered_metrics,
)
)
test_results: List[ExpectationTestDiagnostics] = self._get_test_results(
expectation_type=description_diagnostics.snake_name,
test_data_cases=examples,
execution_engine_diagnostics=introspected_execution_engines,
raise_exceptions_for_backends=raise_exceptions_for_backends,
)
backend_test_result_counts: List[
ExpectationBackendTestResultCounts
] = ExpectationDiagnostics._get_backends_from_test_results(test_results)
renderers: List[
ExpectationRendererDiagnostics
] = self._get_renderer_diagnostics(
expectation_type=description_diagnostics.snake_name,
test_diagnostics=test_results,
registered_renderers=_registered_renderers,
)
maturity_checklist: ExpectationDiagnosticMaturityMessages = (
self._get_maturity_checklist(
library_metadata=library_metadata,
description=description_diagnostics,
examples=examples,
tests=test_results,
backend_test_result_counts=backend_test_result_counts,
execution_engines=introspected_execution_engines,
)
)
# Set final maturity level based on status of all checks
all_experimental = all(