test_schemas.py 2.07 KB
Newer Older
1
2
3
4
5
6
7
8
from __future__ import print_function

import json
import unittest
import os
from os import path
from fnmatch import fnmatch

9
from jsonschema import RefResolver, Draft4Validator, ValidationError
10
11
12
13
14
15

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')

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
16

17
18
19
class JSONSchemaTests(unittest.TestCase):
    pass

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
20

21
22
23
24
25
26
27
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']
J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
28
29
            with open(os.path.join(schema_folder, schema_name +
                                   ".json")) as file_object:
30
31
32
33
34
35
36
                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
37
38
            return
        assert success
39
40
    return do_expected

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
41

42
43
44
45
46
47
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)
J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
48
49
50
51
52
                test_method.__name__ = 'test_file_%s_success_%s' % (filename,
                                                                    success)
                test_method.__doc__ = '%s should %svalidate' % (filename, ''
                                                                if success else
                                                                'not')
53
54
55
                setattr(JSONSchemaTests, test_method.__name__, test_method)
                del test_method

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
56

57
58
59
60
61
add_examples(examples_path, True)
add_examples(bad_examples_path, False)

if __name__ == '__main__':
    unittest.main()