-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16_data_validation.py
More file actions
219 lines (176 loc) · 6.23 KB
/
Copy path16_data_validation.py
File metadata and controls
219 lines (176 loc) · 6.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""Data Contract Validation — Ensuring Data Quality.
Real-world scenario: You generate synthetic data for testing or seeding,
but you need to verify that the data conforms to expected patterns
(valid emails, proper UUIDs, non-null required fields). DataForge's
validation module lets you define and enforce data contracts.
This example demonstrates:
- validate_records(): validating dicts against a field mapping
- schema.validate(): validating data against a schema's contract
- validate_csv(): validating CSV files
- Understanding Violation objects and ValidationReport
- Handling null fields and semantic pattern checks
- Validating external (non-DataForge) data
"""
from dataforge import DataForge
from dataforge.validation import validate_records
forge = DataForge(seed=42)
# --- Example 1: Validating generated data (should pass) -------------------
print("=== Validating Generated Data ===\n")
schema = forge.schema(
{
"name": "person.full_name",
"email": "internet.email",
"phone": "phone_number",
"ssn": "government.ssn",
}
)
# Generate some data and validate it
data = schema.generate(count=20)
report = schema.validate(data)
print(f" Records validated: {report.total_rows}")
print(f" Columns checked: {report.total_columns}")
print(f" Is valid: {report.is_valid}")
print(f" Violations: {report.violation_count}")
print()
# --- Example 2: Validating bad data (should fail) ------------------------
print("=== Validating Bad Data ===\n")
# Intentionally bad records
bad_data = [
{
"name": "Alice Johnson",
"email": "alice@example.com",
"phone": "+1-555-0100",
"ssn": "123-45-6789",
},
{
"name": "", # empty name — violation
"email": "not-an-email", # invalid format — violation
"phone": "+1-555-0101",
"ssn": "12345", # wrong SSN format — violation
},
{
"name": "Bob Smith",
"email": "bob@test.com",
"phone": "abc", # too short for phone — violation
"ssn": "987-65-4321",
},
{
"name": "Charlie Brown",
# missing "email" key — violation
"phone": "+1-555-0102",
"ssn": "111-22-3333",
},
]
field_map = {
"name": "full_name",
"email": "email",
"phone": "phone_number",
"ssn": "ssn",
}
report = validate_records(bad_data, field_map)
print(f" Records validated: {report.total_rows}")
print(f" Is valid: {report.is_valid}")
print(f" Violations found: {report.violation_count}")
print()
# Print the full summary
print(report.summary())
print()
# --- Example 3: Inspecting individual violations -------------------------
print("=== Inspecting Violations ===\n")
for v in report.violations:
print(f" Row {v.row}, Column '{v.column}': {v.reason}")
print(f" Value: {v.value!r}")
print()
# --- Example 4: Violations grouped by column -----------------------------
print("=== Violations by Column ===\n")
by_col = report.violations_by_column()
for col, viols in sorted(by_col.items()):
print(f" {col}: {len(viols)} violation(s)")
for v in viols:
print(f" Row {v.row}: {v.reason} (value={v.value!r})")
print()
# --- Example 5: Schema-based validation ----------------------------------
print("=== Schema-Based Validation ===\n")
# Create a schema and validate external data against it
schema = forge.schema(["email", "uuid4", "date", "ipv4"])
external_data = [
{
"email": "user@domain.com",
"uuid4": "550e8400-e29b-41d4-a716-446655440000",
"date": "2024-01-15",
"ipv4": "192.168.1.1",
},
{
"email": "bad-email",
"uuid4": "not-a-uuid",
"date": "January 15",
"ipv4": "999.999.999.999",
},
{
"email": "good@test.org",
"uuid4": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"date": "2024-12-31",
"ipv4": "10.0.0.1",
},
]
report = schema.validate(external_data)
print(f" Is valid: {report.is_valid}")
print(f" Violations: {report.violation_count}")
print()
print(report.summary())
print()
# --- Example 6: Null field allowances ------------------------------------
print("=== Null Field Allowances ===\n")
# Some columns are allowed to be null
data_with_nulls = [
{"name": "Alice", "email": "alice@test.com", "phone": None},
{"name": "Bob", "email": "bob@test.com", "phone": "+1-555-0100"},
{"name": "", "email": "charlie@test.com", "phone": None},
]
# Without null allowance — phone nulls will be fine (no non-empty check),
# but empty name will trigger violation
report_strict = validate_records(
data_with_nulls,
{"name": "full_name", "email": "email", "phone": "phone_number"},
)
print(f" Strict validation: {report_strict.violation_count} violation(s)")
# With null allowance for phone
report_lenient = validate_records(
data_with_nulls,
{"name": "full_name", "email": "email", "phone": "phone_number"},
null_fields={"phone": 0.5},
)
print(f" Lenient validation: {report_lenient.violation_count} violation(s)")
print()
# --- Example 7: CSV validation -------------------------------------------
print("=== CSV Validation ===\n")
import os # noqa: E402
import tempfile # noqa: E402
csv_content = schema.to_csv(count=50)
csv_path = os.path.join(tempfile.gettempdir(), "dataforge_validation_test.csv")
with open(csv_path, "w", encoding="utf-8") as f:
f.write(csv_content)
# Validate it using schema.validate(path)
report = schema.validate(csv_path)
print(f" CSV file: {csv_path}")
print(f" Rows validated: {report.total_rows}")
print(f" Is valid: {report.is_valid}")
print(f" Violations: {report.violation_count}")
# Clean up
os.unlink(csv_path)
print()
# --- Example 8: Validation report as a testing assertion ------------------
print("=== Using Validation in Tests ===\n")
schema = forge.schema(["first_name", "email", "city"])
data = schema.generate(count=100)
report = schema.validate(data)
# In a real test you would: assert report.is_valid, report.summary()
if report.is_valid:
print(" PASS: All 100 generated records pass validation.")
else:
print(f" FAIL: {report.violation_count} violation(s) found.")
print(report.summary())
print()
print("Typical test assertion:")
print(" report = schema.validate(data)")
print(" assert report.is_valid, report.summary()")