Skip to content
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

[1.26] Improve error message when calling urllib3.request() #3058

Merged
merged 7 commits into from Jun 12, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/urllib3/request.py
@@ -1,6 +1,9 @@
from __future__ import absolute_import

import sys

pquentin marked this conversation as resolved.
Show resolved Hide resolved
from .filepost import encode_multipart_formdata
from .packages import six
from .packages.six.moves.urllib.parse import urlencode

__all__ = ["RequestMethods"]
Expand Down Expand Up @@ -168,3 +171,20 @@ def request_encode_body(
extra_kw.update(urlopen_kw)

return self.urlopen(method, url, **extra_kw)


if not six.PY2:

class RequestModule(sys.modules[__name__].__class__):
def __call__(self, *args, **kwargs):
"""
If user tries to call this module directly urllib3 v2.x style raise an error to the user
suggesting they may need urllib3 v2
"""
raise TypeError(
"'module' object is not callable\n"
"urllib3.request() method is not supported in this release, "
"upgrade to urllib3 v2 to use it"
sg3-141-592 marked this conversation as resolved.
Show resolved Hide resolved
)

sys.modules[__name__].__class__ = RequestModule
26 changes: 26 additions & 0 deletions test/test_request.py
@@ -0,0 +1,26 @@
import types

import pytest

import urllib3
from urllib3.packages import six


@pytest.mark.skipif(
six.PY2,
reason="This behaviour isn't added when running urllib3 in Python 2",
)
class TestRequestImport(object):
def test_request_import_error(self):
"""Ensure an appropriate error is raised to the user
if they try and run urllib3.request()"""
with pytest.raises(TypeError) as exc_info:
urllib3.request(1, a=2)
assert "urllib3 v2" in exc_info.value.args[0]

def test_request_module_properties(self):
"""Ensure properties of the overridden request module
are still present"""
assert isinstance(urllib3.request, types.ModuleType)
expected_attrs = {"RequestMethods", "encode_multipart_formdata", "urlencode"}
assert set(dir(urllib3.request)).issuperset(expected_attrs)