-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
generator.py
529 lines (446 loc) · 23.8 KB
/
generator.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
# ___
# \./ DANGER: This module implements some code generation
# .--.O.--. techniques involving string concatenation.
# \/ \/ If you look at it, you might die.
#
from collections import OrderedDict
import re
import requests
from .exceptions import JsonSchemaException
from .indent import indent
def enforce_list(variable):
if isinstance(variable, list):
return variable
return [variable]
class CodeGenerator:
"""
This class is not supposed to be used directly. Anything
inside of this class can be changed without noticing.
This class generates code of validation function from JSON
schema object as string. Example:
.. code-block:: python
CodeGenerator(json_schema_definition).func_code
"""
INDENT = 4 # spaces
JSON_TYPE_TO_PYTHON_TYPE = {
'null': 'NoneType',
'boolean': 'bool',
'number': 'int, float',
'integer': 'int',
'string': 'str',
'array': 'list',
'object': 'dict',
}
def __init__(self, definition):
self._code = []
self._compile_regexps = {}
self._variables = set()
self._indent = 0
self._variable = None
self._variable_name = None
self._root_definition = definition
self._definition = None
self._json_keywords_to_function = OrderedDict((
('$ref', self.generate_ref),
('type', self.generate_type),
('enum', self.generate_enum),
('allOf', self.generate_all_of),
('anyOf', self.generate_any_of),
('oneOf', self.generate_one_of),
('not', self.generate_not),
('minLength', self.generate_min_length),
('maxLength', self.generate_max_length),
('pattern', self.generate_pattern),
('format', self.generate_format),
('minimum', self.generate_minimum),
('maximum', self.generate_maximum),
('multipleOf', self.generate_multiple_of),
('minItems', self.generate_min_items),
('maxItems', self.generate_max_items),
('uniqueItems', self.generate_unique_items),
('items', self.generate_items),
('minProperties', self.generate_min_properties),
('maxProperties', self.generate_max_properties),
('required', self.generate_required),
('properties', self.generate_properties),
('patternProperties', self.generate_pattern_properties),
('additionalProperties', self.generate_additional_properties),
))
self.generate_func_code(definition)
@property
def func_code(self):
"""
Returns generated code of whole validation function as string.
"""
return '\n'.join(self._code)
@property
def global_state(self):
"""
Returns global variables for generating function from ``func_code``. Includes
compiled regular expressions and imports, so it does not have to do it every
time when validation function is called.
"""
return dict(
self._compile_regexps,
re=re,
JsonSchemaException=JsonSchemaException,
)
@indent
def l(self, line, *args, **kwds):
"""
Short-cut of line. Used for inserting line. It's formated with parameters
``variable``, ``variable_name`` (as ``name`` for short-cut), all keys from
current JSON schema ``definition`` and also passed arguments in ``args``
and named ``kwds``.
.. code-block:: python
self.l('if {variable} not in {enum}: raise JsonSchemaException("Wrong!")')
When you want to indent block, use it as context manager. For example:
.. code-block:: python
with self.l('if {variable} not in {enum}:'):
self.l('raise JsonSchemaException("Wrong!")')
"""
spaces = ' ' * self.INDENT * self._indent
name = self._variable_name
if name and '{' in name:
name = '"+"{}".format(**locals())+"'.format(self._variable_name)
context = dict(
self._definition or {},
variable=self._variable,
name=name,
**kwds
)
self._code.append(spaces + line.format(*args, **context))
def create_variable_with_length(self):
"""
Append code for creating variable with length of that variable
(for example length of list or dictionary) with name ``{variable}_len``.
It can be called several times and always it's done only when that variable
still does not exists.
"""
variable_name = '{}_len'.format(self._variable)
if variable_name in self._variables:
return
self._variables.add(variable_name)
self.l('{variable}_len = len({variable})')
def create_variable_keys(self):
"""
Append code for creating variable with keys of that variable (dictionary)
with name ``{variable}_len``. It can be called several times and always
it's done only when that variable still does not exists.
"""
variable_name = '{}_keys'.format(self._variable)
if variable_name in self._variables:
return
self._variables.add(variable_name)
self.l('{variable}_keys = set({variable}.keys())')
def generate_func_code(self, definition):
"""
Creates base code of validation function and calls helper
for creating code by definition.
"""
with self.l('def func(data):'):
self.l('NoneType = type(None)')
self.generate_func_code_block(definition, 'data', 'data')
self.l('return data')
def generate_func_code_block(self, definition, variable, variable_name, clear_variables=False):
"""
Creates validation rules for current definition.
"""
backup = self._definition, self._variable, self._variable_name
self._definition, self._variable, self._variable_name = definition, variable, variable_name
if clear_variables:
backup_variables = self._variables
self._variables = set()
for key, func in self._json_keywords_to_function.items():
if key in definition:
func()
self._definition, self._variable, self._variable_name = backup
if clear_variables:
self._variables = backup_variables
def generate_ref(self):
"""
Ref can be link to remote or local definition.
.. code-block:: python
{'$ref': 'http://json-schema.org/draft-04/schema#'}
{
'properties': {
'foo': {'type': 'integer'},
'bar': {'$ref': '#/properties/foo'}
}
}
"""
if self._definition['$ref'].startswith('http'):
res = requests.get(self._definition['$ref'])
definition = res.json()
self.generate_func_code_block(definition, self._variable, self._variable_name)
elif self._definition['$ref'] == '#':
self.l('func({variable})')
else:
#TODO: Create more functions for any ref and call it here.
self.l('pass')
def generate_type(self):
"""
Validation of type. Can be one type or list of types.
.. code-block:: python
{'type': 'string'}
{'type': ['string', 'number']}
"""
types = enforce_list(self._definition['type'])
python_types = ', '.join(self.JSON_TYPE_TO_PYTHON_TYPE.get(t) for t in types)
extra = ''
if ('number' in types or 'integer' in types) and 'boolean' not in types:
extra = ' or isinstance({variable}, bool)'.format(variable=self._variable)
with self.l('if not isinstance({variable}, ({})){}:', python_types, extra):
self.l('raise JsonSchemaException("{name} must be {}")', ' or '.join(types))
def generate_enum(self):
"""
Means that only value specified in the enum is valid.
.. code-block:: python
{
'enum': ['a', 'b'],
}
"""
with self.l('if {variable} not in {enum}:'):
self.l('raise JsonSchemaException("{name} must be one of {enum}")')
def generate_all_of(self):
"""
Means that value have to be valid by all of those definitions. It's like put it in
one big definition.
.. code-block:: python
{
'allOf': [
{'type': 'number'},
{'minimum': 5},
],
}
Valid values for this definition are 5, 6, 7, ... but not 4 or 'abc' for example.
"""
for definition_item in self._definition['allOf']:
self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True)
def generate_any_of(self):
"""
Means that value have to be valid by any of those definitions. It can also be valid
by all of them.
.. code-block:: python
{
'anyOf': [
{'type': 'number', 'minimum': 10},
{'type': 'number', 'maximum': 5},
],
}
Valid values for this definition are 3, 4, 5, 10, 11, ... but not 8 for example.
"""
self.l('{variable}_any_of_count = 0')
for definition_item in self._definition['anyOf']:
with self.l('if not {variable}_any_of_count:'):
with self.l('try:'):
self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True)
self.l('{variable}_any_of_count += 1')
self.l('except JsonSchemaException: pass')
with self.l('if not {variable}_any_of_count:'):
self.l('raise JsonSchemaException("{name} must be valid by one of anyOf definition")')
def generate_one_of(self):
"""
Means that value have to be valid by only one of those definitions. It can't be valid
by two or more of them.
.. code-block:: python
{
'oneOf': [
{'type': 'number', 'multipleOf': 3},
{'type': 'number', 'multipleOf': 5},
],
}
Valid values for this definitions are 3, 5, 6, ... but not 15 for example.
"""
self.l('{variable}_one_of_count = 0')
for definition_item in self._definition['oneOf']:
with self.l('try:'):
self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True)
self.l('{variable}_one_of_count += 1')
self.l('except JsonSchemaException: pass')
with self.l('if {variable}_one_of_count != 1:'):
self.l('raise JsonSchemaException("{name} must be valid exactly by one of oneOf definition")')
def generate_not(self):
"""
Means that value have not to be valid by this definition.
.. code-block:: python
{'not': {'type': 'null'}}
Valid values for this definitions are 'hello', 42, {} ... but not None.
"""
if not self._definition['not']:
with self.l('if {}:', self._variable):
self.l('raise JsonSchemaException("{name} must not be valid by not definition")')
else:
with self.l('try:'):
self.generate_func_code_block(self._definition['not'], self._variable, self._variable_name)
self.l('except JsonSchemaException: pass')
self.l('else: raise JsonSchemaException("{name} must not be valid by not definition")')
def generate_min_length(self):
with self.l('if isinstance({variable}, str):'):
self.create_variable_with_length()
with self.l('if {variable}_len < {minLength}:'):
self.l('raise JsonSchemaException("{name} must be longer than or equal to {minLength} characters")')
def generate_max_length(self):
with self.l('if isinstance({variable}, str):'):
self.create_variable_with_length()
with self.l('if {variable}_len > {maxLength}:'):
self.l('raise JsonSchemaException("{name} must be shorter than or equal to {maxLength} characters")')
def generate_pattern(self):
with self.l('if isinstance({variable}, str):'):
self._compile_regexps['{}_re'.format(self._definition['pattern'])] = re.compile(self._definition['pattern'])
with self.l('if not globals()["{}_re"].search({variable}):', self._definition['pattern']):
self.l('raise JsonSchemaException("{name} must match pattern {pattern}")')
def generate_format(self):
with self.l('if isinstance({variable}, str):'):
self._generate_format('date-time', 'date_time_re_pattern', r'^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)?$')
self._generate_format('uri', 'uri_re_pattern', r'^\w+:(\/?\/?)[^\s]+$')
self._generate_format('email', 'email_re_pattern', r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
self._generate_format('ipv4', 'ipv4_re_pattern', r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')
self._generate_format('ipv6', 'ipv6_re_pattern', r'^(?:(?:[0-9A-Fa-f]{1,4}:){6}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|::(?:[0-9A-Fa-f]{1,4}:){5}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,3}[0-9A-Fa-f]{1,4})?::[0-9A-Fa-f]{1,4}:(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,4}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,5}[0-9A-Fa-f]{1,4})?::[0-9A-Fa-f]{1,4}|(?:(?:[0-9A-Fa-f]{1,4}:){,6}[0-9A-Fa-f]{1,4})?::)$')
self._generate_format('hostname', 'hostname_re_pattern', r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{1,62}[A-Za-z0-9])$')
def _generate_format(self, format_name, regexp_name, regexp):
if self._definition['format'] == format_name:
self._compile_regexps[regexp_name] = re.compile(regexp)
with self.l('if not {}.match({variable}):', regexp_name):
self.l('raise JsonSchemaException("{name} must be {}")', format_name)
def generate_minimum(self):
with self.l('if isinstance({variable}, (int, float)):'):
if self._definition.get('exclusiveMinimum', False):
with self.l('if {variable} <= {minimum}:'):
self.l('raise JsonSchemaException("{name} must be bigger than {minimum}")')
else:
with self.l('if {variable} < {minimum}:'):
self.l('raise JsonSchemaException("{name} must be bigger than or equal to {minimum}")')
def generate_maximum(self):
with self.l('if isinstance({variable}, (int, float)):'):
if self._definition.get('exclusiveMaximum', False):
with self.l('if {variable} >= {maximum}:'):
self.l('raise JsonSchemaException("{name} must be smaller than {maximum}")')
else:
with self.l('if {variable} > {maximum}:'):
self.l('raise JsonSchemaException("{name} must be smaller than or equal to {maximum}")')
def generate_multiple_of(self):
with self.l('if isinstance({variable}, (int, float)):'):
self.l('quotient = {variable} / {multipleOf}')
with self.l('if int(quotient) != quotient:'):
self.l('raise JsonSchemaException("{name} must be multiple of {multipleOf}")')
def generate_min_items(self):
with self.l('if isinstance({variable}, list):'):
self.create_variable_with_length()
with self.l('if {variable}_len < {minItems}:'):
self.l('raise JsonSchemaException("{name} must contain at least {minItems} items")')
def generate_max_items(self):
with self.l('if isinstance({variable}, list):'):
self.create_variable_with_length()
with self.l('if {variable}_len > {maxItems}:'):
self.l('raise JsonSchemaException("{name} must contain less than or equal to {maxItems} items")')
def generate_unique_items(self):
"""
With Python 3.4 module ``timeit`` recommended this solutions:
.. code-block:: python
>>> timeit.timeit("len(x) > len(set(x))", "x=range(100)+range(100)", number=100000)
0.5839540958404541
>>> timeit.timeit("len({}.fromkeys(x)) == len(x)", "x=range(100)+range(100)", number=100000)
0.7094449996948242
>>> timeit.timeit("seen = set(); any(i in seen or seen.add(i) for i in x)", "x=range(100)+range(100)", number=100000)
2.0819358825683594
>>> timeit.timeit("np.unique(x).size == len(x)", "x=range(100)+range(100); import numpy as np", number=100000)
2.1439831256866455
"""
self.create_variable_with_length()
with self.l('if {variable}_len > len(set(str(x) for x in {variable})):'):
self.l('raise JsonSchemaException("{name} must contain unique items")')
def generate_items(self):
with self.l('if isinstance({variable}, list):'):
self.create_variable_with_length()
if isinstance(self._definition['items'], list):
for x, item_definition in enumerate(self._definition['items']):
with self.l('if {variable}_len > {}:', x):
self.l('{variable}_{0} = {variable}[{0}]', x)
self.generate_func_code_block(
item_definition,
'{}_{}'.format(self._variable, x),
'{}[{}]'.format(self._variable_name, x),
)
if 'default' in item_definition:
self.l('else: {variable}.append({})', repr(item_definition['default']))
if 'additionalItems' in self._definition:
if self._definition['additionalItems'] is False:
self.l('if {variable}_len > {}: raise JsonSchemaException("{name} must contain only specified items")', len(self._definition['items']))
else:
with self.l('for {variable}_x, {variable}_item in enumerate({variable}[{0}:], {0}):', len(self._definition['items'])):
self.generate_func_code_block(
self._definition['additionalItems'],
'{}_item'.format(self._variable),
'{}[{{{}_x}}]'.format(self._variable_name, self._variable),
)
else:
if self._definition['items']:
with self.l('for {variable}_x, {variable}_item in enumerate({variable}):'):
self.generate_func_code_block(
self._definition['items'],
'{}_item'.format(self._variable),
'{}[{{{}_x}}]'.format(self._variable_name, self._variable),
)
def generate_min_properties(self):
with self.l('if isinstance({variable}, dict):'):
self.create_variable_with_length()
with self.l('if {variable}_len < {minProperties}:'):
self.l('raise JsonSchemaException("{name} must contain at least {minProperties} properties")')
def generate_max_properties(self):
with self.l('if isinstance({variable}, dict):'):
self.create_variable_with_length()
with self.l('if {variable}_len > {maxProperties}:'):
self.l('raise JsonSchemaException("{name} must contain less than or equal to {maxProperties} properties")')
def generate_required(self):
with self.l('if isinstance({variable}, dict):'):
self.create_variable_with_length()
with self.l('if not all(prop in {variable} for prop in {required}):'):
self.l('raise JsonSchemaException("{name} must contain {required} properties")')
def generate_properties(self):
with self.l('if isinstance({variable}, dict):'):
self.create_variable_keys()
for key, prop_definition in self._definition['properties'].items():
key_name = re.sub(r'($[^a-zA-Z]|[^a-zA-Z0-9])', '', key)
with self.l('if "{}" in {variable}_keys:', key):
self.l('{variable}_keys.remove("{}")', key)
self.l('{variable}_{0} = {variable}["{1}"]', key_name, key)
self.generate_func_code_block(
prop_definition,
'{}_{}'.format(self._variable, key_name),
'{}.{}'.format(self._variable_name, key),
)
if 'default' in prop_definition:
self.l('else: {variable}["{}"] = {}', key, repr(prop_definition['default']))
def generate_pattern_properties(self):
with self.l('if isinstance({variable}, dict):'):
self.create_variable_keys()
for pattern, definition in self._definition['patternProperties'].items():
self._compile_regexps['{}_re'.format(pattern)] = re.compile(pattern)
with self.l('for key, val in {variable}.items():'):
for pattern, definition in self._definition['patternProperties'].items():
with self.l('if globals()["{}_re"].search(key):', pattern):
with self.l('if key in {variable}_keys:'):
self.l('{variable}_keys.remove(key)')
self.generate_func_code_block(
definition,
'val',
'{}.{{key}}'.format(self._variable_name),
)
def generate_additional_properties(self):
with self.l('if isinstance({variable}, dict):'):
self.create_variable_keys()
add_prop_definition = self._definition["additionalProperties"]
if add_prop_definition:
properties_keys = self._definition.get("properties", {}).keys()
with self.l('for {variable}_key in {variable}_keys:'):
with self.l('if {variable}_key not in "{}":', properties_keys):
self.l('{variable}_value = {variable}.get({variable}_key)')
self.generate_func_code_block(
add_prop_definition,
'{}_value'.format(self._variable),
'{}.{{{}_key}}'.format(self._variable_name, self._variable),
)
else:
with self.l('if {variable}_keys:'):
self.l('raise JsonSchemaException("{name} must contain only specified properties")')