Skip to content

Move requests import to runtime #388

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions jsonschema/tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -1013,6 +1013,26 @@ def test_schema_error_message(self):
)


class MockImport(object):

def __init__(self, module, _mock):
self._module = module
self._mock = _mock
self._orig_import = None

def __enter__(self):
self._orig_import = sys.modules.get(self._module, None)
sys.modules[self._module] = self._mock
return self._mock

def __exit__(self, *args):
if self._orig_import is None:
del sys.modules[self._module]
else:
sys.modules[self._module] = self._orig_import
return True


class TestRefResolver(TestCase):

base_uri = ""
Expand Down Expand Up @@ -1062,7 +1082,7 @@ def test_it_retrieves_unstored_refs_via_requests(self):
ref = "http://bar#baz"
schema = {"baz": 12}

with mock.patch("jsonschema.validators.requests") as requests:
with MockImport("requests", mock.Mock()) as requests:
requests.get.return_value.json.return_value = schema
with self.resolver.resolving(ref) as resolved:
self.assertEqual(resolved, 12)
Expand All @@ -1072,7 +1092,7 @@ def test_it_retrieves_unstored_refs_via_urlopen(self):
ref = "http://bar#baz"
schema = {"baz": 12}

with mock.patch("jsonschema.validators.requests", None):
with MockImport("requests", None):
with mock.patch("jsonschema.validators.urlopen") as urlopen:
urlopen.return_value.read.return_value = (
json.dumps(schema).encode("utf8"))
Expand Down
9 changes: 4 additions & 5 deletions jsonschema/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,6 @@

from six import add_metaclass

try:
import requests
except ImportError:
requests = None

from jsonschema import _utils, _validators, _types
from jsonschema.compat import (
Sequence, urljoin, urlsplit, urldefrag, unquote, urlopen,
Expand Down Expand Up @@ -671,6 +666,10 @@ def resolve_remote(self, uri):
.. _requests: http://pypi.python.org/pypi/requests/

"""
try:
import requests
except ImportError:
requests = None

scheme = urlsplit(uri).scheme

Expand Down