summaryrefslogtreecommitdiff
path: root/json/bin/jsonschema_suite
blob: 19dc65e97d46215071c59334107be60f1d11f1cb (plain)
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
#! /usr/bin/env python3
import argparse
import errno
import fnmatch
import json
import os
import random
import shutil
import sys
import textwrap
import unittest
import warnings

try:
    import jsonschema.validators
except ImportError:
    jsonschema = None
    VALIDATORS = {}
else:
    VALIDATORS = {
        "draft3": jsonschema.validators.Draft3Validator,
        "draft4": jsonschema.validators.Draft4Validator,
        "draft6": jsonschema.validators.Draft6Validator,
        "draft7": jsonschema.validators.Draft7Validator,
        "draft2019-09": jsonschema.validators.Draft201909Validator,
        "draft2020-12": jsonschema.validators.Draft202012Validator,
        "latest": jsonschema.validators.Draft202012Validator,
    }


ROOT_DIR = os.path.abspath(
    os.path.join(os.path.dirname(__file__), os.pardir).rstrip("__pycache__"),
)
SUITE_ROOT_DIR = os.path.join(ROOT_DIR, "tests")
REMOTES_DIR = os.path.join(ROOT_DIR, "remotes")


with open(os.path.join(ROOT_DIR, "test-schema.json")) as schema:
    TESTSUITE_SCHEMA = json.load(schema)


def files(paths):
    """
    Each test file in the provided paths.
    """
    for path in paths:
        with open(path) as test_file:
            yield json.load(test_file)


def groups(paths):
    """
    Each test group within each file in the provided paths.
    """
    for test_file in files(paths):
        for group in test_file:
            yield group


def cases(paths):
    """
    Each individual test case within all groups within the provided paths.
    """
    for test_group in groups(paths):
        for test in test_group["tests"]:
            test["schema"] = test_group["schema"]
            yield test


def collect(root_dir):
    """
    All of the test file paths within the given root directory, recursively.
    """
    for root, _, files in os.walk(root_dir):
        for filename in fnmatch.filter(files, "*.json"):
            yield os.path.join(root, filename)


class SanityTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print("Looking for tests in %s" % SUITE_ROOT_DIR)
        print("Looking for remotes in %s" % REMOTES_DIR)
        cls.test_files = list(collect(SUITE_ROOT_DIR))
        cls.remote_files = list(collect(REMOTES_DIR))
        print("Found %s test files" % len(cls.test_files))
        print("Found %s remote files" % len(cls.remote_files))
        assert cls.test_files, "Didn't find the test files!"
        assert cls.remote_files, "Didn't find the remote files!"

    def test_all_test_files_are_valid_json(self):
        for path in self.test_files:
            with open(path) as test_file:
                try:
                    json.load(test_file)
                except ValueError as error:
                    self.fail("%s contains invalid JSON (%s)" % (path, error))

    def test_all_remote_files_are_valid_json(self):
        for path in self.remote_files:
            with open(path) as remote_file:
                try:
                    json.load(remote_file)
                except ValueError as error:
                    self.fail("%s contains invalid JSON (%s)" % (path, error))

    def test_all_descriptions_have_reasonable_length(self):
        for case in cases(self.test_files):
            description = case["description"]
            self.assertLess(
                len(description),
                70,
                "%r is too long! (keep it to less than 70 chars)" % (
                    description,
                ),
            )

    def test_all_descriptions_are_unique(self):
        for group in groups(self.test_files):
            descriptions = set(test["description"] for test in group["tests"])
            self.assertEqual(
                len(descriptions),
                len(group["tests"]),
                "%r contains a duplicate description" % (group,)
            )

    @unittest.skipIf(jsonschema is None, "Validation library not present!")
    def test_all_schemas_are_valid(self):
        for version in os.listdir(SUITE_ROOT_DIR):
            Validator = VALIDATORS.get(version)
            if Validator is not None:
                test_files = collect(os.path.join(SUITE_ROOT_DIR, version))
                for case in cases(test_files):
                    try:
                        Validator.check_schema(case["schema"])
                    except jsonschema.SchemaError as error:
                        self.fail("%s contains an invalid schema (%s)" %
                                  (case, error))
            else:
                warnings.warn("No schema validator for %s" % schema)

    @unittest.skipIf(jsonschema is None, "Validation library not present!")
    def test_suites_are_valid(self):
        Validator = jsonschema.validators.validator_for(TESTSUITE_SCHEMA)
        validator = Validator(TESTSUITE_SCHEMA)
        for tests in files(self.test_files):
            try:
                validator.validate(tests)
            except jsonschema.ValidationError as error:
                self.fail(str(error))


def main(arguments):
    if arguments.command == "check":
        suite = unittest.TestLoader().loadTestsFromTestCase(SanityTests)
        result = unittest.TextTestRunner(verbosity=2).run(suite)
        sys.exit(not result.wasSuccessful())
    elif arguments.command == "flatten":
        selected_cases = [case for case in cases(collect(arguments.version))]

        if arguments.randomize:
            random.shuffle(selected_cases)

        json.dump(selected_cases, sys.stdout, indent=4, sort_keys=True)
    elif arguments.command == "remotes":
        remotes = {}
        for path in collect(REMOTES_DIR):
            relative_path = os.path.relpath(path, REMOTES_DIR)
            with open(path) as schema_file:
                remotes[relative_path] = json.load(schema_file)
        json.dump(remotes, sys.stdout, indent=4, sort_keys=True)
    elif arguments.command == "dump_remotes":
        if arguments.update:
            shutil.rmtree(arguments.out_dir, ignore_errors=True)

        try:
            shutil.copytree(REMOTES_DIR, arguments.out_dir)
        except OSError as e:
            if e.errno == errno.EEXIST:
                print("%s already exists. Aborting." % arguments.out_dir)
                sys.exit(1)
            raise
    elif arguments.command == "serve":
        try:
            import flask
        except ImportError:
            print(textwrap.dedent("""
                The Flask library is required to serve the remote schemas.

                You can install it by running `pip install Flask`.

                Alternatively, see the `jsonschema_suite remotes` or
                `jsonschema_suite dump_remotes` commands to create static files
                that can be served with your own web server.
            """.strip("\n")))
            sys.exit(1)

        app = flask.Flask(__name__)

        @app.route("/<path:path>")
        def serve_path(path):
            return flask.send_from_directory(REMOTES_DIR, path)

        app.run(port=1234)


parser = argparse.ArgumentParser(
    description="JSON Schema Test Suite utilities",
)
subparsers = parser.add_subparsers(
    help="utility commands", dest="command", metavar="COMMAND"
)
subparsers.required = True

check = subparsers.add_parser("check", help="Sanity check the test suite.")

flatten = subparsers.add_parser(
    "flatten",
    help="Output a flattened file containing a selected version's test cases."
)
flatten.add_argument(
    "--randomize",
    action="store_true",
    help="Randomize the order of the outputted cases.",
)
flatten.add_argument(
    "version", help="The directory containing the version to output",
)

remotes = subparsers.add_parser(
    "remotes",
    help="Output the expected URLs and their associated schemas for remote "
         "ref tests as a JSON object."
)

dump_remotes = subparsers.add_parser(
    "dump_remotes", help="Dump the remote ref schemas into a file tree",
)
dump_remotes.add_argument(
    "--update",
    action="store_true",
    help="Update the remotes in an existing directory.",
)
dump_remotes.add_argument(
    "--out-dir",
    default=REMOTES_DIR,
    type=os.path.abspath,
    help="The output directory to create as the root of the file tree",
)

serve = subparsers.add_parser(
    "serve",
    help="Start a webserver to serve schemas used by remote ref tests."
)

if __name__ == "__main__":
    main(parser.parse_args())