Debian Codegraph @

bin/jsonschema_validate.py

raw
1 #!/usr/bin/env python
2 # -*- encoding: utf-8 -*-
3 """
4 Validate a JSON file against its JSON schema.
5
6 SEE ALSO:
7 * https://python-jsonschema.readthedocs.org/
8 * https://python-jsonschema.readthedocs.org/en/latest/errors.html
9
10 REQUIRES:
11 Python >= 2.6
12 jsonschema >= 1.3.0
13 argparse
14 """
15
16 from __future__ import absolute_import, print_function
17
18 __author__ = "Jens Engel"
19 __version__ = "0.1.0"
20
21 from jsonschema import validate
22 import argparse
23 import os.path
24 import sys
25 import textwrap
26 try:
27 import json
28 except ImportError:
29 try:
30 import simplejson as json
31 except ImportError:
32 sys.exit("REQUIRE: simplejson (which is not installed)")
33
34
35 # -----------------------------------------------------------------------------
36 # CONSTANTS:
37 # -----------------------------------------------------------------------------
38 HERE = os.path.dirname(__file__)
39 TOP = os.path.normpath(os.path.join(HERE, ".."))
40 SCHEMA = os.path.join(TOP, "etc", "json", "behave.json-schema")
41
42
43 # -----------------------------------------------------------------------------
44 # FUNCTIONS:
45 # -----------------------------------------------------------------------------
46 def jsonschema_validate(filename, schema, encoding=None):
47 f = open(filename, "r")
48 contents = f.read()
49 f.close()
50 data = json.loads(contents, encoding=encoding)
51 return validate(data, schema)
52
53
54 def main(args=None):
55 """
56 Validate JSON files against their JSON schema.
57 NOTE: Behave's JSON-schema is used per default.
58
59 SEE ALSO:
60 * http://json-schema.org/
61 * http://tools.ietf.org/html/draft-zyp-json-schema-04
62 """
63 if args is None:
64 args = sys.argv[1:]
65 default_schema = None
66 if os.path.exists(SCHEMA):
67 default_schema = SCHEMA
68
69 parser = argparse.ArgumentParser(
70 description=textwrap.dedent(main.__doc__),
71 formatter_class=argparse.RawDescriptionHelpFormatter
72 )
73 parser.add_argument("-v", "--version",
74 action="version", version=__version__)
75 parser.add_argument("-s", "--schema",
76 help="JSON schema to use.")
77 parser.add_argument("-e", "--encoding",
78 help="Encoding for JSON/JSON schema.")
79 parser.add_argument("files", nargs="+", metavar="JSON_FILE",
80 help="JSON file to check.")
81 parser.set_defaults(
82 schema=default_schema,
83 encoding="UTF-8"
84 )
85 options = parser.parse_args(args)
86 if not options.schema:
87 parser.error("REQUIRE: JSON schema")
88 elif not os.path.isfile(options.schema):
89 parser.error("SCHEMA not found: %s" % options.schema)
90
91 try:
92 f = open(options.schema, "r")
93 contents = f.read()
94 f.close()
95 schema = json.loads(contents, encoding=options.encoding)
96 except Exception as e:
97 msg = "ERROR: %s: %s (while loading schema)" % (e.__class__.__name__, e)
98 sys.exit(msg)
99
100 error_count = 0
101 for filename in options.files:
102 validated = True
103 more_info = None
104 try:
105 print("validate:", filename, "...", end=' ')
106 jsonschema_validate(filename, schema, encoding=options.encoding)
107 except Exception as e:
108 more_info = "%s: %s" % (e.__class__.__name__, e)
109 validated = False
110 error_count += 1
111 if validated:
112 print("OK")
113 else:
114 print("FAILED\n\n%s" % more_info)
115 return error_count
116
117
118 # -----------------------------------------------------------------------------
119 # AUTO-MAIN
120 # -----------------------------------------------------------------------------
121 if __name__ == "__main__":
122 sys.exit(main())