Skip to content

Commit 594e80d

Browse files
authored
Merge pull request #1416 from gudnimg/gudni-urllib-import
validators: avoid `urllib.request` at import-time
2 parents c3855b9 + 1f3616b commit 594e80d

File tree

3 files changed

+35
-6
lines changed

3 files changed

+35
-6
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
A benchmark which measures the import time of jsonschema
3+
"""
4+
5+
import subprocess
6+
import sys
7+
8+
9+
def import_time(loops):
10+
total_us = 0
11+
for _ in range(loops):
12+
p = subprocess.run( # noqa: S603 (arguments are static)
13+
[sys.executable, "-X", "importtime", "-c", "import jsonschema"],
14+
stderr=subprocess.PIPE,
15+
stdout=subprocess.DEVNULL,
16+
check=True,
17+
)
18+
19+
line = p.stderr.splitlines()[-1]
20+
field = line.split(b"|")[-2].strip()
21+
us = int(field) # microseconds
22+
total_us += us
23+
24+
# pyperf expects seconds
25+
return total_us / 1_000_000.0
26+
27+
if __name__ == "__main__":
28+
from pyperf import Runner
29+
runner = Runner()
30+
31+
runner.bench_time_func("Import time (cumulative)", import_time)

jsonschema/tests/test_validators.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2379,11 +2379,9 @@ def fake_urlopen(url):
23792379
self.assertEqual(url, "http://bar")
23802380
yield BytesIO(json.dumps(schema).encode("utf8"))
23812381

2382-
self.addCleanup(setattr, validators, "urlopen", validators.urlopen)
2383-
validators.urlopen = fake_urlopen
2384-
2385-
with self.resolver.resolving(ref) as resolved:
2386-
pass
2382+
with mock.patch("urllib.request.urlopen", new=fake_urlopen): # noqa: SIM117
2383+
with self.resolver.resolving(ref) as resolved:
2384+
pass
23872385
self.assertEqual(resolved, 12)
23882386

23892387
def test_it_retrieves_local_refs_via_urlopen(self):

jsonschema/validators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
from operator import methodcaller
1010
from typing import TYPE_CHECKING
1111
from urllib.parse import unquote, urldefrag, urljoin, urlsplit
12-
from urllib.request import urlopen
1312
from warnings import warn
1413
import contextlib
1514
import json
@@ -1225,6 +1224,7 @@ def resolve_remote(self, uri):
12251224
result = requests.get(uri).json()
12261225
else:
12271226
# Otherwise, pass off to urllib and assume utf-8
1227+
from urllib.request import urlopen
12281228
with urlopen(uri) as url: # noqa: S310
12291229
result = json.loads(url.read().decode("utf-8"))
12301230

0 commit comments

Comments
 (0)