Skip to content

Commit 7454f0f

Browse files
author
Gaetano Guerriero
committed
fix urlopen usage in python2 when resolving refs
urlopen() result was used as a context manager in python2 too and this was causing error.
1 parent 7e2a6bc commit 7454f0f

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

jsonschema/compat.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import operator
23
import sys
34

@@ -27,7 +28,10 @@
2728
urljoin, urlunsplit, SplitResult, urlsplit as _urlsplit # noqa
2829
)
2930
from urllib import unquote # noqa
30-
from urllib2 import urlopen # noqa
31+
import urllib2 # noqa
32+
def urlopen(*args, **kwargs):
33+
return contextlib.closing(urllib2.urlopen(*args, **kwargs))
34+
3135
str_types = basestring
3236
int_types = int, long
3337
iteritems = operator.methodcaller("iteritems")

jsonschema/tests/test_validators.py

+17
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
from io import BytesIO
55
from unittest import TestCase
66
import json
7+
import os
78
import sys
9+
import tempfile
810
import unittest
911

1012
from twisted.trial.unittest import SynchronousTestCase
@@ -22,6 +24,12 @@
2224
from jsonschema.tests.compat import mock
2325

2426

27+
if PY3:
28+
from urllib.request import pathname2url
29+
else:
30+
from urllib import pathname2url
31+
32+
2533
def startswith(validator, startswith, instance, schema):
2634
if not instance.startswith(startswith):
2735
yield ValidationError(u"Whoops!")
@@ -1341,6 +1349,15 @@ def fake_urlopen(url):
13411349
pass
13421350
self.assertEqual(resolved, 12)
13431351

1352+
def test_it_retrieves_local_refs_via_urlopen(self):
1353+
with tempfile.NamedTemporaryFile(delete=False, mode='wt') as tempf:
1354+
self.addCleanup(os.remove, tempf.name)
1355+
json.dump({'foo': 'bar'}, tempf)
1356+
1357+
ref = "file://{}#foo".format(pathname2url(tempf.name))
1358+
with self.resolver.resolving(ref) as resolved:
1359+
self.assertEqual(resolved, 'bar')
1360+
13441361
def test_it_can_construct_a_base_uri_from_a_schema(self):
13451362
schema = {"id": "foo"}
13461363
resolver = validators.RefResolver.from_schema(

0 commit comments

Comments
 (0)