summaryrefslogtreecommitdiff
path: root/jsonschema/tests/_suite.py
blob: 6be05bed9a821fe1097df4e2b5fe2af880304d67 (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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""
Python representations of the JSON Schema Test Suite tests.
"""
from __future__ import annotations

from collections.abc import Iterable, Mapping
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, Any
import json
import os
import re
import subprocess
import sys
import unittest

from attrs import field, frozen
from referencing import Registry
import referencing.jsonschema

if TYPE_CHECKING:
    import pyperf

from jsonschema.validators import _VALIDATORS
import jsonschema

_DELIMITERS = re.compile(r"[\W\- ]+")


def _find_suite():
    root = os.environ.get("JSON_SCHEMA_TEST_SUITE")
    if root is not None:
        return Path(root)

    root = Path(jsonschema.__file__).parent.parent / "json"
    if not root.is_dir():  # pragma: no cover
        raise ValueError(
            (
                "Can't find the JSON-Schema-Test-Suite directory. "
                "Set the 'JSON_SCHEMA_TEST_SUITE' environment "
                "variable or run the tests from alongside a checkout "
                "of the suite."
            ),
        )
    return root


@frozen
class Suite:

    _root: Path = field(factory=_find_suite)
    _remotes: referencing.jsonschema.SchemaRegistry = field(init=False)

    def __attrs_post_init__(self):
        jsonschema_suite = self._root.joinpath("bin", "jsonschema_suite")
        argv = [sys.executable, str(jsonschema_suite), "remotes"]
        remotes = subprocess.check_output(argv).decode("utf-8")

        resources = json.loads(remotes)

        li = "http://localhost:1234/locationIndependentIdentifierPre2019.json"
        li4 = "http://localhost:1234/locationIndependentIdentifierDraft4.json"

        registry = Registry().with_resources(
            [
                (
                    li,
                    referencing.jsonschema.DRAFT7.create_resource(
                        contents=resources.pop(li),
                    ),
                ),
                (
                    li4,
                    referencing.jsonschema.DRAFT4.create_resource(
                        contents=resources.pop(li4),
                    ),
                ),
            ],
        ).with_contents(
            resources.items(),
            default_specification=referencing.jsonschema.DRAFT202012,
        )
        object.__setattr__(self, "_remotes", registry)

    def benchmark(self, runner: pyperf.Runner):  # pragma: no cover
        for name, Validator in _VALIDATORS.items():
            self.version(name=name).benchmark(
                runner=runner,
                Validator=Validator,
            )

    def version(self, name) -> Version:
        return Version(
            name=name,
            path=self._root / "tests" / name,
            remotes=self._remotes,
        )


@frozen
class Version:

    _path: Path
    _remotes: referencing.jsonschema.SchemaRegistry

    name: str

    def benchmark(self, **kwargs):  # pragma: no cover
        for case in self.cases():
            case.benchmark(**kwargs)

    def cases(self) -> Iterable[_Case]:
        return self._cases_in(paths=self._path.glob("*.json"))

    def format_cases(self) -> Iterable[_Case]:
        return self._cases_in(paths=self._path.glob("optional/format/*.json"))

    def optional_cases_of(self, name: str) -> Iterable[_Case]:
        return self._cases_in(paths=[self._path / "optional" / f"{name}.json"])

    def to_unittest_testcase(self, *groups, **kwargs):
        name = kwargs.pop("name", "Test" + self.name.title().replace("-", ""))
        methods = {
            method.__name__: method
            for method in (
                test.to_unittest_method(**kwargs)
                for group in groups
                for case in group
                for test in case.tests
            )
        }
        cls = type(name, (unittest.TestCase,), methods)

        try:
            cls.__module__ = _someone_save_us_the_module_of_the_caller()
        except Exception:  # pragma: no cover
            # We're doing crazy things, so if they go wrong, like a function
            # behaving differently on some other interpreter, just make them
            # not happen.
            pass

        return cls

    def _cases_in(self, paths: Iterable[Path]) -> Iterable[_Case]:
        for path in paths:
            for case in json.loads(path.read_text(encoding="utf-8")):
                yield _Case.from_dict(
                    case,
                    version=self,
                    subject=path.stem,
                    remotes=self._remotes,
                )


@frozen
class _Case:

    version: Version

    subject: str
    description: str
    schema: Mapping[str, Any] | bool
    tests: list[_Test]
    comment: str | None = None

    @classmethod
    def from_dict(cls, data, remotes, **kwargs):
        data.update(kwargs)
        tests = [
            _Test(
                version=data["version"],
                subject=data["subject"],
                case_description=data["description"],
                schema=data["schema"],
                remotes=remotes,
                **test,
            ) for test in data.pop("tests")
        ]
        return cls(tests=tests, **data)

    def benchmark(self, runner: pyperf.Runner, **kwargs):  # pragma: no cover
        for test in self.tests:
            runner.bench_func(
                test.fully_qualified_name,
                partial(test.validate_ignoring_errors, **kwargs),
            )


@frozen(repr=False)
class _Test:

    version: Version

    subject: str
    case_description: str
    description: str

    data: Any
    schema: Mapping[str, Any] | bool

    valid: bool

    _remotes: referencing.jsonschema.SchemaRegistry

    comment: str | None = None

    def __repr__(self):  # pragma: no cover
        return f"<Test {self.fully_qualified_name}>"

    @property
    def fully_qualified_name(self):  # pragma: no cover
        return " > ".join(
            [
                self.version.name,
                self.subject,
                self.case_description,
                self.description,
            ],
        )

    def to_unittest_method(self, skip=lambda test: None, **kwargs):
        if self.valid:
            def fn(this):
                self.validate(**kwargs)
        else:
            def fn(this):
                with this.assertRaises(jsonschema.ValidationError):
                    self.validate(**kwargs)

        fn.__name__ = "_".join(
            [
                "test",
                _DELIMITERS.sub("_", self.subject),
                _DELIMITERS.sub("_", self.case_description),
                _DELIMITERS.sub("_", self.description),
            ],
        )
        reason = skip(self)
        if reason is None or os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0":
            return fn
        elif os.environ.get("JSON_SCHEMA_EXPECTED_FAILURES", "0") != "0":
            return unittest.expectedFailure(fn)
        else:
            return unittest.skip(reason)(fn)

    def validate(self, Validator, **kwargs):
        Validator.check_schema(self.schema)
        validator = Validator(
            schema=self.schema,
            registry=self._remotes,
            **kwargs,
        )
        if os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0":
            breakpoint()
        validator.validate(instance=self.data)

    def validate_ignoring_errors(self, Validator):  # pragma: no cover
        try:
            self.validate(Validator=Validator)
        except jsonschema.ValidationError:
            pass


def _someone_save_us_the_module_of_the_caller():
    """
    The FQON of the module 2nd stack frames up from here.

    This is intended to allow us to dynamically return test case classes that
    are indistinguishable from being defined in the module that wants them.

    Otherwise, trial will mis-print the FQON, and copy pasting it won't re-run
    the class that really is running.

    Save us all, this is all so so so so so terrible.
    """

    return sys._getframe(2).f_globals["__name__"]