1
0
mirror of https://github.com/kevin1024/vcrpy.git synced 2025-12-09 17:15:35 +00:00

Format project with black (#467)

Format with line length 110 to match flake8

make black part of linting check

Update travis spec for updated black requirements

Add diff output for black on failure

update changelog
This commit is contained in:
Josh Peak
2019-08-24 11:36:35 +10:00
committed by GitHub
parent 75969de601
commit 7caf29735a
70 changed files with 2000 additions and 2217 deletions

View File

@@ -1,12 +1,8 @@
'''Stubs for patching HTTP and HTTPS requests'''
"""Stubs for patching HTTP and HTTPS requests"""
import logging
import six
from six.moves.http_client import (
HTTPConnection,
HTTPSConnection,
HTTPResponse,
)
from six.moves.http_client import HTTPConnection, HTTPSConnection, HTTPResponse
from six import BytesIO
from vcr.request import Request
from vcr.errors import CannotOverwriteExistingCassetteException
@@ -45,8 +41,7 @@ def parse_headers(header_list):
header_string = b""
for key, values in header_list.items():
for v in values:
header_string += \
key.encode('utf-8') + b":" + v.encode('utf-8') + b"\r\n"
header_string += key.encode("utf-8") + b":" + v.encode("utf-8") + b"\r\n"
return compat.get_httpmessage(header_string)
@@ -62,27 +57,28 @@ class VCRHTTPResponse(HTTPResponse):
"""
Stub response class that gets returned instead of a HTTPResponse
"""
def __init__(self, recorded_response):
self.fp = None
self.recorded_response = recorded_response
self.reason = recorded_response['status']['message']
self.status = self.code = recorded_response['status']['code']
self.reason = recorded_response["status"]["message"]
self.status = self.code = recorded_response["status"]["code"]
self.version = None
self._content = BytesIO(self.recorded_response['body']['string'])
self._content = BytesIO(self.recorded_response["body"]["string"])
self._closed = False
headers = self.recorded_response['headers']
headers = self.recorded_response["headers"]
# Since we are loading a response that has already been serialized, our
# response is no longer chunked. That means we don't want any
# libraries trying to process a chunked response. By removing the
# transfer-encoding: chunked header, this should cause the downstream
# libraries to process this as a non-chunked response.
te_key = [h for h in headers.keys() if h.upper() == 'TRANSFER-ENCODING']
te_key = [h for h in headers.keys() if h.upper() == "TRANSFER-ENCODING"]
if te_key:
del headers[te_key[0]]
self.headers = self.msg = parse_headers(headers)
self.length = compat.get_header(self.msg, 'content-length') or None
self.length = compat.get_header(self.msg, "content-length") or None
@property
def closed(self):
@@ -129,17 +125,17 @@ class VCRHTTPResponse(HTTPResponse):
return self.closed
def info(self):
return parse_headers(self.recorded_response['headers'])
return parse_headers(self.recorded_response["headers"])
def getheaders(self):
message = parse_headers(self.recorded_response['headers'])
message = parse_headers(self.recorded_response["headers"])
return list(compat.get_header_items(message))
def getheader(self, header, default=None):
values = [v for (k, v) in self.getheaders() if k.lower() == header.lower()]
if values:
return ', '.join(values)
return ", ".join(values)
else:
return default
@@ -156,41 +152,27 @@ class VCRConnection(object):
Returns empty string for the default port and ':port' otherwise
"""
port = self.real_connection.port
default_port = {'https': 443, 'http': 80}[self._protocol]
return ':{}'.format(port) if port != default_port else ''
default_port = {"https": 443, "http": 80}[self._protocol]
return ":{}".format(port) if port != default_port else ""
def _uri(self, url):
"""Returns request absolute URI"""
if url and not url.startswith('/'):
if url and not url.startswith("/"):
# Then this must be a proxy request.
return url
uri = "{}://{}{}{}".format(
self._protocol,
self.real_connection.host,
self._port_postfix(),
url,
)
uri = "{}://{}{}{}".format(self._protocol, self.real_connection.host, self._port_postfix(), url)
log.debug("Absolute URI: %s", uri)
return uri
def _url(self, uri):
"""Returns request selector url from absolute URI"""
prefix = "{}://{}{}".format(
self._protocol,
self.real_connection.host,
self._port_postfix(),
)
return uri.replace(prefix, '', 1)
prefix = "{}://{}{}".format(self._protocol, self.real_connection.host, self._port_postfix())
return uri.replace(prefix, "", 1)
def request(self, method, url, body=None, headers=None, *args, **kwargs):
'''Persist the request metadata in self._vcr_request'''
self._vcr_request = Request(
method=method,
uri=self._uri(url),
body=body,
headers=headers or {}
)
log.debug('Got {}'.format(self._vcr_request))
"""Persist the request metadata in self._vcr_request"""
self._vcr_request = Request(method=method, uri=self._uri(url), body=body, headers=headers or {})
log.debug("Got {}".format(self._vcr_request))
# Note: The request may not actually be finished at this point, so
# I'm not sending the actual request until getresponse(). This
@@ -205,25 +187,19 @@ class VCRConnection(object):
to start building up a request. Usually followed by a bunch
of putheader() calls.
"""
self._vcr_request = Request(
method=method,
uri=self._uri(url),
body="",
headers={}
)
log.debug('Got {}'.format(self._vcr_request))
self._vcr_request = Request(method=method, uri=self._uri(url), body="", headers={})
log.debug("Got {}".format(self._vcr_request))
def putheader(self, header, *values):
self._vcr_request.headers[header] = values
def send(self, data):
'''
"""
This method is called after request(), to add additional data to the
body of the request. So if that happens, let's just append the data
onto the most recent request in the cassette.
'''
self._vcr_request.body = self._vcr_request.body + data \
if self._vcr_request.body else data
"""
self._vcr_request.body = self._vcr_request.body + data if self._vcr_request.body else data
def close(self):
# Note: the real connection will only close if it's open, so
@@ -240,37 +216,27 @@ class VCRConnection(object):
self._vcr_request.body = message_body
def getresponse(self, _=False, **kwargs):
'''Retrieve the response'''
"""Retrieve the response"""
# Check to see if the cassette has a response for this request. If so,
# then return it
if self.cassette.can_play_response_for(self._vcr_request):
log.info(
"Playing response for {} from cassette".format(
self._vcr_request
)
)
log.info("Playing response for {} from cassette".format(self._vcr_request))
response = self.cassette.play_response(self._vcr_request)
return VCRHTTPResponse(response)
else:
if self.cassette.write_protected and self.cassette.filter_request(
self._vcr_request
):
if self.cassette.write_protected and self.cassette.filter_request(self._vcr_request):
raise CannotOverwriteExistingCassetteException(
cassette=self.cassette,
failed_request=self._vcr_request
cassette=self.cassette, failed_request=self._vcr_request
)
# Otherwise, we should send the request, then get the response
# and return it.
log.info(
"{} not in cassette, sending to real server".format(
self._vcr_request
)
)
log.info("{} not in cassette, sending to real server".format(self._vcr_request))
# This is imported here to avoid circular import.
# TODO(@IvanMalison): Refactor to allow normal import.
from vcr.patch import force_reset
with force_reset():
self.real_connection.request(
method=self._vcr_request.method,
@@ -284,12 +250,9 @@ class VCRConnection(object):
# put the response into the cassette
response = {
'status': {
'code': response.status,
'message': response.reason
},
'headers': serialize_headers(response),
'body': {'string': response.read()},
"status": {"code": response.status, "message": response.reason},
"headers": serialize_headers(response),
"body": {"string": response.read()},
}
self.cassette.append(self._vcr_request, response)
return VCRHTTPResponse(response)
@@ -305,8 +268,7 @@ class VCRConnection(object):
and are not write-protected.
"""
if hasattr(self, '_vcr_request') and \
self.cassette.can_play_response_for(self._vcr_request):
if hasattr(self, "_vcr_request") and self.cassette.can_play_response_for(self._vcr_request):
# We already have a response we are going to play, don't
# actually connect
return
@@ -316,6 +278,7 @@ class VCRConnection(object):
return
from vcr.patch import force_reset
with force_reset():
return self.real_connection.connect(*args, **kwargs)
@@ -334,12 +297,13 @@ class VCRConnection(object):
def __init__(self, *args, **kwargs):
if six.PY3:
kwargs.pop('strict', None) # apparently this is gone in py3
kwargs.pop("strict", None) # apparently this is gone in py3
# need to temporarily reset here because the real connection
# inherits from the thing that we are mocking out. Take out
# the reset if you want to see what I mean :)
from vcr.patch import force_reset
with force_reset():
self.real_connection = self._baseclass(*args, **kwargs)
@@ -371,7 +335,7 @@ class VCRConnection(object):
Send requests for weird attributes up to the real connection
(counterpart to __setattr above)
"""
if self.__dict__.get('real_connection'):
if self.__dict__.get("real_connection"):
# check in case real_connection has not been set yet, such as when
# we're setting the real_connection itself for the first time
return getattr(self.real_connection, name)
@@ -385,13 +349,15 @@ for k, v in HTTPConnection.__dict__.items():
class VCRHTTPConnection(VCRConnection):
'''A Mocked class for HTTP requests'''
"""A Mocked class for HTTP requests"""
_baseclass = HTTPConnection
_protocol = 'http'
_protocol = "http"
class VCRHTTPSConnection(VCRConnection):
'''A Mocked class for HTTPS requests'''
"""A Mocked class for HTTPS requests"""
_baseclass = HTTPSConnection
_protocol = 'https'
_protocol = "https"
is_verified = True