diff --git a/jsonschema/benchmarks/import_benchmark.py b/jsonschema/benchmarks/import_benchmark.py new file mode 100644 index 000000000..59fa921dd --- /dev/null +++ b/jsonschema/benchmarks/import_benchmark.py @@ -0,0 +1,31 @@ +""" +A benchmark which measures the import time of jsonschema +""" + +import subprocess +import sys + + +def import_time(loops): + total_us = 0 + for _ in range(loops): + p = subprocess.run( # noqa: S603 (arguments are static) + [sys.executable, "-X", "importtime", "-c", "import jsonschema"], + stderr=subprocess.PIPE, + stdout=subprocess.DEVNULL, + check=True, + ) + + line = p.stderr.splitlines()[-1] + field = line.split(b"|")[-2].strip() + us = int(field) # microseconds + total_us += us + + # pyperf expects seconds + return total_us / 1_000_000.0 + +if __name__ == "__main__": + from pyperf import Runner + runner = Runner() + + runner.bench_time_func("Import time (cumulative)", import_time) diff --git a/jsonschema/tests/test_validators.py b/jsonschema/tests/test_validators.py index 28cc40273..d419ddf8e 100644 --- a/jsonschema/tests/test_validators.py +++ b/jsonschema/tests/test_validators.py @@ -2379,11 +2379,9 @@ def fake_urlopen(url): self.assertEqual(url, "http://bar") yield BytesIO(json.dumps(schema).encode("utf8")) - self.addCleanup(setattr, validators, "urlopen", validators.urlopen) - validators.urlopen = fake_urlopen - - with self.resolver.resolving(ref) as resolved: - pass + with mock.patch("urllib.request.urlopen", new=fake_urlopen): # noqa: SIM117 + with self.resolver.resolving(ref) as resolved: + pass self.assertEqual(resolved, 12) def test_it_retrieves_local_refs_via_urlopen(self): diff --git a/jsonschema/validators.py b/jsonschema/validators.py index dbc029fc0..98ddf6bfb 100644 --- a/jsonschema/validators.py +++ b/jsonschema/validators.py @@ -9,7 +9,6 @@ from operator import methodcaller from typing import TYPE_CHECKING from urllib.parse import unquote, urldefrag, urljoin, urlsplit -from urllib.request import urlopen from warnings import warn import contextlib import json @@ -1225,6 +1224,7 @@ def resolve_remote(self, uri): result = requests.get(uri).json() else: # Otherwise, pass off to urllib and assume utf-8 + from urllib.request import urlopen with urlopen(uri) as url: # noqa: S310 result = json.loads(url.read().decode("utf-8"))