-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_infer_schema.py
145 lines (124 loc) · 4.31 KB
/
test_infer_schema.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
import json
import copy
import csv
import unittest
from typing import Dict, Any, Union, List
from unittest.mock import patch
from io import StringIO
from infer_schema import infer_schema, NULL_VALUES, _detect_type, main
import fastjsonschema
TEST_CASES = [
("tests/mtcars.csv", "tests/mtcars.schema.json", dict()),
("tests/mtcars_partial.csv", "tests/mtcars_partial.schema.json", dict()),
(
"tests/mtcars_partial.csv",
"tests/mtcars_partial_enum-fields.schema.json",
dict(enum_fields=["car_model"]),
),
(
"tests/mtcars_partial.csv",
"tests/mtcars_partial_enum-threshold.schema.json",
dict(enum_threshold=30),
),
(
"tests/mtcars_partial.csv",
"tests/mtcars_partial_bound-types.schema.json",
dict(bound_types=set()),
),
(
"tests/mtcars_partial.csv",
"tests/mtcars_partial_bound-string.schema.json",
dict(bound_types={"string"}),
),
("tests/dates.csv", "tests/dates.schema.json", dict()),
("tests/date-times.csv", "tests/date-times.schema.json", dict()),
]
def read_json(file: str) -> Dict[str, Any]:
with open(file) as fp:
return json.load(fp)
def is_numeric_jsonschema_type(t: Union[str, List[str]]) -> bool:
t = {t} if isinstance(t, str) else set(t)
return "string" not in t and (t & {"number"})
def is_integer_jsonschema_type(t: Union[str, List[str]]) -> bool:
t = {t} if isinstance(t, str) else set(t)
return t - {"null"} == {"integer"}
def casted_row(
row: Dict[str, Any],
integer_columns: List[str],
numeric_columns: List[str],
explicit_nulls: bool = False,
) -> Dict[str, Any]:
nrow = copy.deepcopy(row)
for c in row:
if row[c] in NULL_VALUES:
if explicit_nulls:
nrow[c] = None
else:
del nrow[c]
continue
if c in integer_columns:
nrow[c] = int(row[c])
if c in numeric_columns:
nrow[c] = float(row[c])
return nrow
def validate_csv(file: str, jsonschema_file: str, explicit_nulls: bool = False) -> bool:
jsonschema = read_json(jsonschema_file)
numeric_columns = [
c
for c in jsonschema["properties"]
if is_numeric_jsonschema_type(jsonschema["properties"][c].get("type", "string"))
or isinstance(jsonschema["properties"][c].get("enum", ["x"])[0], float)
]
integer_columns = [
c
for c in jsonschema["properties"]
if is_integer_jsonschema_type(jsonschema["properties"][c].get("type", "string"))
or isinstance(jsonschema["properties"][c].get("enum", ["x"])[0], int)
]
validate = fastjsonschema.compile(jsonschema)
with open(file) as fp:
reader = csv.DictReader(fp)
for row in reader:
try:
validate(
casted_row(
row,
integer_columns,
numeric_columns,
explicit_nulls=explicit_nulls,
)
)
except fastjsonschema.JsonSchemaException as e:
print(row)
print(e.message)
return False
return True
class InferSchemaTest(unittest.TestCase):
def test_infer_schema(self):
for i, case in enumerate(TEST_CASES):
with self.subTest(i=i):
self.assertEqual(infer_schema(case[0], **case[2]), read_json(case[1]))
class ValidationTest(unittest.TestCase):
def test_validation(self):
for i, case in enumerate(TEST_CASES):
with self.subTest(i=i):
self.assertEqual(validate_csv(case[0], case[1]), True)
# explicit nulls case
self.assertEqual(
validate_csv(
"tests/mtcars_partial.csv",
"tests/mtcars_partial_explicit-nulls.schema.json",
explicit_nulls=True,
),
True,
)
class TypeTest(unittest.TestCase):
def test_detect_type(self):
self.assertEqual(_detect_type("N/A"), "null")
class MainTest(unittest.TestCase):
def test_main(self):
with patch("sys.stdout", new=StringIO()) as out:
main(["tests/dates.csv"])
self.assertEqual(
json.loads(out.getvalue()), read_json("tests/dates.schema.json")
)