Skip to content

Commit f4f277a

Browse files
committed
test urllib3 version compatibility to determine mock response class
1 parent bbed3f5 commit f4f277a

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

tests/test_requests.py

+17-4
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@
3131
import requests
3232
import responses
3333
import socket
34-
import sys
3534
import threading
3635
import time
3736
from urllib.parse import urlunsplit
@@ -45,6 +44,15 @@
4544
import talisker.statsd
4645
import talisker.testing
4746

47+
try:
48+
# Compatible urllib3 HTTPResponses subclass their Base class.
49+
URLLIB3_COMPATIBLE_VERSION = issubclass(
50+
urllib3.response.HTTPResponse,
51+
urllib3.response.BaseHTTPResponse
52+
)
53+
except AttributeError:
54+
URLLIB3_COMPATIBLE_VERSION = False
55+
4856

4957
def request(method='GET', host='http://example.com', url='/', **kwargs):
5058
req = requests.Request(method, url=host + url, **kwargs)
@@ -482,7 +490,13 @@ def set_responses(self, responses):
482490
self.response_iter = iter(responses)
483491

484492
def make_response(self, content, status='200 OK', headers={}):
485-
"""Make a fake http.client.HTTPResponse based on a byte stream."""
493+
"""Make a fake HTTPResponse based on a byte stream.
494+
495+
For versions of urllib3 where urllib3.response.HTTPResponse is
496+
not API-compatible with http.client.HTTPResponse, we return the
497+
http.client version. For versions after, we return a
498+
urllib3.response.HTTPResponse.
499+
"""
486500
if not headers:
487501
headers["Content-Type"] = "text/html"
488502

@@ -496,8 +510,7 @@ def make_response(self, content, status='200 OK', headers={}):
496510
http_response = http.client.HTTPResponse(sock)
497511
http_response.begin()
498512

499-
# Python versions below 3.7 expect a non-urllib3 response.
500-
if sys.version_info.minor < 7:
513+
if not URLLIB3_COMPATIBLE_VERSION:
501514
return http_response
502515

503516
response = urllib3.response.HTTPResponse(

0 commit comments

Comments
 (0)