2017-01-10 09:02:14 +00:00
|
|
|
from __future__ import print_function
|
|
|
|
|
|
|
|
import json
|
|
|
|
import unittest
|
|
|
|
import os
|
|
|
|
from os import path
|
|
|
|
from fnmatch import fnmatch
|
|
|
|
|
2017-01-10 10:10:10 +00:00
|
|
|
from jsonschema import RefResolver, Draft4Validator, ValidationError
|
2017-01-10 09:02:14 +00:00
|
|
|
|
2018-05-14 09:38:02 +00:00
|
|
|
from senpy.models import read_schema
|
|
|
|
|
2017-01-10 09:02:14 +00:00
|
|
|
root_path = path.join(path.dirname(path.realpath(__file__)), '..')
|
|
|
|
schema_folder = path.join(root_path, 'senpy', 'schemas')
|
|
|
|
examples_path = path.join(root_path, 'docs', 'examples')
|
|
|
|
bad_examples_path = path.join(root_path, 'docs', 'bad-examples')
|
|
|
|
|
2017-01-10 09:16:45 +00:00
|
|
|
|
2017-01-10 09:02:14 +00:00
|
|
|
class JSONSchemaTests(unittest.TestCase):
|
2018-05-14 09:38:02 +00:00
|
|
|
def test_definitions(self):
|
|
|
|
read_schema('definitions.json')
|
2017-01-10 09:02:14 +00:00
|
|
|
|
2017-01-10 09:16:45 +00:00
|
|
|
|
2017-01-10 09:02:14 +00:00
|
|
|
def do_create_(jsfile, success):
|
|
|
|
def do_expected(self):
|
|
|
|
with open(jsfile) as f:
|
|
|
|
js = json.load(f)
|
|
|
|
try:
|
|
|
|
assert '@type' in js
|
|
|
|
schema_name = js['@type']
|
2017-01-10 09:16:45 +00:00
|
|
|
with open(os.path.join(schema_folder, schema_name +
|
|
|
|
".json")) as file_object:
|
2017-01-10 09:02:14 +00:00
|
|
|
schema = json.load(file_object)
|
|
|
|
resolver = RefResolver('file://' + schema_folder + '/', schema)
|
|
|
|
validator = Draft4Validator(schema, resolver=resolver)
|
|
|
|
validator.validate(js)
|
|
|
|
except (AssertionError, ValidationError, KeyError) as ex:
|
|
|
|
if success:
|
|
|
|
raise
|
2017-08-19 19:55:48 +00:00
|
|
|
return
|
|
|
|
assert success
|
2017-01-10 09:02:14 +00:00
|
|
|
return do_expected
|
|
|
|
|
2017-01-10 09:16:45 +00:00
|
|
|
|
2017-01-10 09:02:14 +00:00
|
|
|
def add_examples(dirname, success):
|
|
|
|
for dirpath, dirnames, filenames in os.walk(dirname):
|
|
|
|
for i in filenames:
|
|
|
|
if fnmatch(i, '*.json'):
|
|
|
|
filename = path.join(dirpath, i)
|
|
|
|
test_method = do_create_(filename, success)
|
2017-01-10 09:16:45 +00:00
|
|
|
test_method.__name__ = 'test_file_%s_success_%s' % (filename,
|
|
|
|
success)
|
|
|
|
test_method.__doc__ = '%s should %svalidate' % (filename, ''
|
|
|
|
if success else
|
|
|
|
'not')
|
2017-01-10 09:02:14 +00:00
|
|
|
setattr(JSONSchemaTests, test_method.__name__, test_method)
|
|
|
|
del test_method
|
|
|
|
|
2017-01-10 09:16:45 +00:00
|
|
|
|
2017-01-10 09:02:14 +00:00
|
|
|
add_examples(examples_path, True)
|
|
|
|
add_examples(bad_examples_path, False)
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
unittest.main()
|