forked from ghandic/jsf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.py
169 lines (146 loc) · 6.74 KB
/
parser.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
import json
import logging
import random
from copy import deepcopy
from datetime import datetime
from itertools import count
from typing import Any, Dict, List, Optional, Tuple, Union
from json2xml import json2xml
from faker import Faker
from jsonschema import validate as val
from pydantic import conlist
from smart_open import open as s_open
from .schema_types import AllTypes, Array, JSFEnum, JSFTuple, Object, PrimativeTypes, Primitives
logger = logging.getLogger()
faker = Faker()
class JSF:
def __init__(
self,
schema: Dict[str, Any],
context: Dict[str, Any] = {
"faker": faker,
"random": random,
"datetime": datetime,
"__internal__": {"List": List, "Union": Union, "conlist": conlist},
},
initial_state: Dict[str, Any] = {},
):
self.root_schema = schema
self.definitions = {}
self.base_state = {
"__counter__": count(start=1),
"__all_json_paths__": [],
**initial_state,
}
self.base_context = context
self.root = None
self._parse(schema)
def __parse_primitive(self, name: str, path: str, schema: Dict[str, Any]) -> PrimativeTypes:
item_type, is_nullable = self.__is_field_nullable(schema)
cls = Primitives.get(item_type)
return cls.from_dict({"name": name, "path": path, "is_nullable": is_nullable, **schema})
def __parse_object(self, name: str, path: str, schema: Dict[str, Any]) -> Object:
_, is_nullable = self.__is_field_nullable(schema)
model = Object.from_dict({"name": name, "path": path, "is_nullable": is_nullable, **schema})
props = []
for _name, definition in schema.get("properties", {}).items():
props.append(self.__parse_definition(_name, path=f"{path}/{_name}", schema=definition))
model.properties = props
return model
def __parse_array(self, name: str, path: str, schema: Dict[str, Any]) -> Array:
_, is_nullable = self.__is_field_nullable(schema)
arr = Array.from_dict({"name": name, "path": path, "is_nullable": is_nullable, **schema})
arr.items = self.__parse_definition(name, name, schema["items"])
return arr
def __parse_tuple(self, name: str, path: str, schema: Dict[str, Any]) -> JSFTuple:
_, is_nullable = self.__is_field_nullable(schema)
arr = JSFTuple.from_dict({"name": name, "path": path, "is_nullable": is_nullable, **schema})
arr.items = []
for i, item in enumerate(schema["items"]):
arr.items.append(self.__parse_definition(name, path=f"{name}[{i}]", schema=item))
return arr
def __is_field_nullable(self, schema: Dict[str, Any]) -> Tuple[str, bool]:
item_type = schema.get("type")
if isinstance(item_type, list):
if "null" in item_type and len(set(item_type)) == 2:
deepcopy(item_type).remove("null")
return item_type[0], True
raise TypeError # pragma: no cover - not currently supporting other types TODO
return item_type, False
def __parse_definition(self, name: str, path: str, schema: Dict[str, Any]) -> AllTypes:
self.base_state["__all_json_paths__"].append(path)
item_type, is_nullable = self.__is_field_nullable(schema)
if "const" in schema:
schema["enum"] = [schema["const"]]
if "enum" in schema:
enum_list = schema["enum"]
assert len(enum_list) > 0, "Enum List is Empty"
assert all(
isinstance(item, (int, float, str, type(None))) for item in enum_list
), "Enum Type is not null, int, float or string"
return JSFEnum.from_dict({"name": name, "path": path, "is_nullable": is_nullable, **schema})
elif "type" in schema:
if item_type == "object" and "properties" in schema:
return self.__parse_object(name, path, schema)
elif item_type == "array":
if (schema.get("contains") is not None) or isinstance(schema.get("items"), dict):
return self.__parse_array(name, path, schema)
if isinstance(schema.get("items"), list) and all(isinstance(x, dict) for x in schema.get("items", [])):
return self.__parse_tuple(name, path, schema)
else:
return self.__parse_primitive(name, path, schema)
elif "$ref" in schema:
ext, frag = schema["$ref"].split("#")
if ext == "":
cls = deepcopy(self.definitions.get(f"#{frag}"))
else:
with s_open(ext, "r") as f:
external_jsf = JSF(json.load(f))
cls = deepcopy(external_jsf.definitions.get(f"#{frag}"))
cls.name = name
cls.path = path
return cls
else:
raise ValueError(f"Cannot parse schema {repr(schema)}") # pragma: no cover
def _parse(self, schema: Dict[str, Any]) -> AllTypes:
for name, definition in schema.get("definitions", {}).items():
item = self.__parse_definition(name, path="#/definitions", schema=definition)
self.definitions[f"#/definitions/{name}"] = item
self.root = self.__parse_definition(name="root", path="#", schema=schema)
@property
def context(self):
return {**self.base_context, "state": deepcopy(self.base_state)}
def generate(self, n: Optional[int] = None, validate:Optional[bool] = False) -> Any:
if n is None or n == 1:
if validate:
data = self.root.generate(context=self.context)
val(instance=data,schema=self.root_schema)
return data
return self.root.generate(context=self.context)
else:
data_arr = []
for _ in range(n):
if validate:
data = self.root.generate(context=self.context)
val(instance=data,schema=self.root_schema)
data_arr.append(data)
else:
data = self.root.generate(context=self.context)
data_arr.append(data)
return data_arr
def pydantic(self):
return self.root.model(context=self.context)[0]
def validate(self) -> None:
fake = self.root.generate(context=self.context)
val(instance=fake, schema=self.root_schema)
def to_json(self, path: str) -> None:
with open(path, "w") as f:
json.dump(self.generate(), f, indent=2)
def generate_xml(self):
data = self.generate()
data = json2xml.Json2xml(data, pretty=True).to_xml()
return data
@staticmethod
def from_json(path: str) -> "JSF":
with open(path, "r") as f:
return JSF(json.load(f))