Skip to content

Commit

Permalink
test urllib3 version compatibility to determine mock response class
Browse files Browse the repository at this point in the history
  • Loading branch information
Perfect5th committed Apr 12, 2024
1 parent bbed3f5 commit fdb470d
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import requests
import responses
import socket
import sys
import threading
import time
from urllib.parse import urlunsplit
Expand All @@ -45,6 +44,15 @@
import talisker.statsd
import talisker.testing

try:
# Compatible urllib3 HTTPResponses subclass their Base class.
URLLIB3_COMPATIBLE_VERSION = issubclass(
urllib3.response.HTTPResponse,
urllib3.response.BaseHTTPResponse
)
except AttributeError:
URLLIB3_COMPATIBLE_VERSION = False


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

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

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

# Python versions below 3.7 expect a non-urllib3 response.
if sys.version_info.minor < 7:
if not URLLIB3_COMPATIBLE_VERSION:
return http_response

response = urllib3.response.HTTPResponse(
Expand Down

0 comments on commit fdb470d

Please sign in to comment.