Skip to content

Commit 57181d6

Browse files
authored
[1.26] Improve error message when calling urllib3.request() (#3058)
1 parent 3c01480 commit 57181d6

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/urllib3/request.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
from __future__ import absolute_import
22

3+
import sys
4+
35
from .filepost import encode_multipart_formdata
6+
from .packages import six
47
from .packages.six.moves.urllib.parse import urlencode
58

69
__all__ = ["RequestMethods"]
@@ -168,3 +171,21 @@ def request_encode_body(
168171
extra_kw.update(urlopen_kw)
169172

170173
return self.urlopen(method, url, **extra_kw)
174+
175+
176+
if not six.PY2:
177+
178+
class RequestModule(sys.modules[__name__].__class__):
179+
def __call__(self, *args, **kwargs):
180+
"""
181+
If user tries to call this module directly urllib3 v2.x style raise an error to the user
182+
suggesting they may need urllib3 v2
183+
"""
184+
raise TypeError(
185+
"'module' object is not callable\n"
186+
"urllib3.request() method is not supported in this release, "
187+
"upgrade to urllib3 v2 to use it\n"
188+
"see https://urllib3.readthedocs.io/en/stable/v2-migration-guide.html"
189+
)
190+
191+
sys.modules[__name__].__class__ = RequestModule

test/test_request.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import types
2+
3+
import pytest
4+
5+
import urllib3
6+
from urllib3.packages import six
7+
8+
9+
@pytest.mark.skipif(
10+
six.PY2,
11+
reason="This behaviour isn't added when running urllib3 in Python 2",
12+
)
13+
class TestRequestImport(object):
14+
def test_request_import_error(self):
15+
"""Ensure an appropriate error is raised to the user
16+
if they try and run urllib3.request()"""
17+
with pytest.raises(TypeError) as exc_info:
18+
urllib3.request(1, a=2)
19+
assert "urllib3 v2" in exc_info.value.args[0]
20+
21+
def test_request_module_properties(self):
22+
"""Ensure properties of the overridden request module
23+
are still present"""
24+
assert isinstance(urllib3.request, types.ModuleType)
25+
expected_attrs = {"RequestMethods", "encode_multipart_formdata", "urlencode"}
26+
assert set(dir(urllib3.request)).issuperset(expected_attrs)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy