Skip to content

Fix unclosed resource in validators #427

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 5 commits into from
Jul 12, 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
15 changes: 11 additions & 4 deletions jsonschema/tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -1186,14 +1186,21 @@ def test_it_retrieves_unstored_refs_via_requests(self):
def test_it_retrieves_unstored_refs_via_urlopen(self):
ref = "http://bar#baz"
schema = {"baz": 12}
resource_manager_mock = mock.MagicMock()
(resource_manager_mock.
__enter__.return_value.
read.return_value.
decode.return_value) = json.dumps(schema).encode("utf8")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't look correct, and is a good example of why mocking is sadness :/

decode returns unicode, not bytes.

Will fix on merge though, thanks.

urlopen_mock = mock.MagicMock(return_value=resource_manager_mock)

with MockImport("requests", None):
with mock.patch("jsonschema.validators.urlopen") as urlopen:
urlopen.return_value.read.return_value = (
json.dumps(schema).encode("utf8"))
with mock.patch("jsonschema.validators.urlopen", urlopen_mock):
with self.resolver.resolving(ref) as resolved:
self.assertEqual(resolved, 12)
urlopen.assert_called_once_with("http://bar")

urlopen_mock.assert_called_once_with("http://bar")
self.assertEqual(resource_manager_mock.__exit__.call_count, 1)
self.assertEqual(resource_manager_mock.__enter__.call_count, 1)

def test_it_can_construct_a_base_uri_from_a_schema(self):
schema = {"id": "foo"}
Expand Down
3 changes: 2 additions & 1 deletion jsonschema/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,7 +753,8 @@ def resolve_remote(self, uri):
result = requests.get(uri).json
else:
# Otherwise, pass off to urllib and assume utf-8
result = json.loads(urlopen(uri).read().decode("utf-8"))
with urlopen(uri) as url:
result = json.loads(url.read().decode("utf-8"))

if self.cache_remote:
self.store[uri] = result
Expand Down