From 2d4a89f5dc561dbf062ec5c85d6f6ca32a511042 Mon Sep 17 00:00:00 2001 From: Nate Prewitt Date: Tue, 19 Jul 2016 15:23:11 -0600 Subject: [PATCH] adding in pep8 fixes --- requests/auth.py | 3 +++ requests/cookies.py | 1 + requests/hooks.py | 1 + requests/models.py | 13 +++++++------ requests/sessions.py | 3 +-- requests/status_codes.py | 2 +- requests/structures.py | 2 ++ requests/utils.py | 6 ++++-- tests/test_lowlevel.py | 2 +- tests/test_requests.py | 10 ++++------ tests/test_testserver.py | 24 +++++++++++++----------- tests/test_utils.py | 1 + 12 files changed, 39 insertions(+), 29 deletions(-) diff --git a/requests/auth.py b/requests/auth.py index 73f8e9da..4f09b911 100644 --- a/requests/auth.py +++ b/requests/auth.py @@ -43,6 +43,7 @@ class AuthBase(object): class HTTPBasicAuth(AuthBase): """Attaches HTTP Basic Authentication to the given Request object.""" + def __init__(self, username, password): self.username = username self.password = password @@ -63,6 +64,7 @@ class HTTPBasicAuth(AuthBase): class HTTPProxyAuth(HTTPBasicAuth): """Attaches HTTP Proxy Authentication to a given Request object.""" + def __call__(self, r): r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password) return r @@ -70,6 +72,7 @@ class HTTPProxyAuth(HTTPBasicAuth): class HTTPDigestAuth(AuthBase): """Attaches HTTP Digest Authentication to the given Request object.""" + def __init__(self, username, password): self.username = username self.password = password diff --git a/requests/cookies.py b/requests/cookies.py index eee5168f..af6238c3 100644 --- a/requests/cookies.py +++ b/requests/cookies.py @@ -178,6 +178,7 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping): .. warning:: dictionary operations that are normally O(1) may be O(n). """ + def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over diff --git a/requests/hooks.py b/requests/hooks.py index 9da94366..3a33da68 100644 --- a/requests/hooks.py +++ b/requests/hooks.py @@ -14,6 +14,7 @@ Available hooks: """ HOOKS = ['response'] + def default_hooks(): return dict((event, []) for event in HOOKS) diff --git a/requests/models.py b/requests/models.py index d9bcfc82..b80ae270 100644 --- a/requests/models.py +++ b/requests/models.py @@ -27,7 +27,7 @@ from .exceptions import ( from .utils import ( guess_filename, get_auth_from_url, requote_uri, stream_decode_response_unicode, to_key_val_list, parse_header_links, - iter_slices, guess_json_utf, super_len, to_native_string, + iter_slices, guess_json_utf, super_len, to_native_string, check_header_validity) from .compat import ( cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO, @@ -38,11 +38,11 @@ from .status_codes import codes #: The set of HTTP status codes that indicate an automatically #: processable redirect. REDIRECT_STATI = ( - codes.moved, # 301 - codes.found, # 302 - codes.other, # 303 - codes.temporary_redirect, # 307 - codes.permanent_redirect, # 308 + codes.moved, # 301 + codes.found, # 302 + codes.other, # 303 + codes.temporary_redirect, # 307 + codes.permanent_redirect, # 308 ) DEFAULT_REDIRECT_LIMIT = 30 @@ -209,6 +209,7 @@ class Request(RequestHooksMixin): """ + def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): diff --git a/requests/sessions.py b/requests/sessions.py index 3f405ba9..96455045 100644 --- a/requests/sessions.py +++ b/requests/sessions.py @@ -195,7 +195,7 @@ class SessionRedirectMixin(object): if 'Authorization' in headers: # If we get redirected to a new host, we should strip out any - # authentication headers. + # authentication headers. original_parsed = urlparse(response.request.url) redirect_parsed = urlparse(url) @@ -376,7 +376,6 @@ class Session(SessionRedirectMixin): merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) - # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: diff --git a/requests/status_codes.py b/requests/status_codes.py index 0137c91d..db2986bb 100644 --- a/requests/status_codes.py +++ b/requests/status_codes.py @@ -31,7 +31,7 @@ _codes = { 306: ('switch_proxy',), 307: ('temporary_redirect', 'temporary_moved', 'temporary'), 308: ('permanent_redirect', - 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 + 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 # Client Error. 400: ('bad_request', 'bad'), diff --git a/requests/structures.py b/requests/structures.py index 991056e4..596ac404 100644 --- a/requests/structures.py +++ b/requests/structures.py @@ -41,6 +41,7 @@ class CaseInsensitiveDict(collections.MutableMapping): behavior is undefined. """ + def __init__(self, data=None, **kwargs): self._store = OrderedDict() if data is None: @@ -87,6 +88,7 @@ class CaseInsensitiveDict(collections.MutableMapping): def __repr__(self): return str(dict(self.items())) + class LookupDict(dict): """Dictionary lookup object.""" diff --git a/requests/utils.py b/requests/utils.py index 397a655e..79b12fbe 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -384,7 +384,7 @@ def stream_decode_response_unicode(iterator, r): def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 - if slice_length is None or slice_length <= 0: + if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] @@ -734,6 +734,7 @@ def to_native_string(string, encoding='ascii'): return out + # Moved outside of function to avoid recompile every call _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$') _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$') @@ -755,9 +756,10 @@ def check_header_validity(header): if not pat.match(value): raise InvalidHeader("Invalid return character or leading space in header: %s" % name) except TypeError: - raise InvalidHeader("Header value %s must be of type str or bytes, " + raise InvalidHeader("Header value %s must be of type str or bytes, " "not %s" % (value, type(value))) + def urldefragauth(url): """ Given a url remove the fragment and the authentication part diff --git a/tests/test_lowlevel.py b/tests/test_lowlevel.py index f3dd1b11..98834271 100644 --- a/tests/test_lowlevel.py +++ b/tests/test_lowlevel.py @@ -17,7 +17,7 @@ def test_chunked_upload(): with server as (host, port): url = 'http://{0}:{1}/'.format(host, port) r = requests.post(url, data=data, stream=True) - close_server.set() # release server block + close_server.set() # release server block assert r.status_code == 200 assert r.request.headers['Transfer-Encoding'] == 'chunked' diff --git a/tests/test_requests.py b/tests/test_requests.py index 73616272..e6cb8b0d 100755 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -564,8 +564,7 @@ class TestRequests: assert post1.status_code == 200 with open('requirements.txt') as f: - post2 = requests.post(url, - data={'some': 'data'}, files={'some': f}) + post2 = requests.post(url, data={'some': 'data'}, files={'some': f}) assert post2.status_code == 200 post4 = requests.post(url, data='[{"some": "json"}]') @@ -940,8 +939,7 @@ class TestRequests: def test_time_elapsed_blank(self, httpbin): r = requests.get(httpbin('get')) td = r.elapsed - total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) - * 10**6) / 10**6) + total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6) assert total_seconds > 0.0 def test_response_is_iterable(self): @@ -990,7 +988,7 @@ class TestRequests: r.reason = u'Komponenttia ei löydy'.encode('utf-8') r.status_code = 404 r.encoding = None - assert not r.ok # old behaviour - crashes here + assert not r.ok # old behaviour - crashes here def test_response_chunk_size_type(self): """Ensure that chunk_size is passed as None or an integer, otherwise @@ -1152,7 +1150,7 @@ class TestRequests: per discussion in GH issue #3386 """ headers_int = {'foo': 3} - headers_dict = {'bar': {'foo':'bar'}} + headers_dict = {'bar': {'foo': 'bar'}} headers_list = {'baz': ['foo', 'bar']} # Test for int diff --git a/tests/test_testserver.py b/tests/test_testserver.py index 9a35460e..94a89483 100644 --- a/tests/test_testserver.py +++ b/tests/test_testserver.py @@ -6,16 +6,19 @@ import pytest import requests from tests.testserver.server import Server + class TestTestServer: + def test_basic(self): """messages are sent and received properly""" question = b"sucess?" answer = b"yeah, success" + def handler(sock): text = sock.recv(1000) - assert text == question + assert text == question sock.sendall(answer) - + with Server(handler) as (host, port): sock = socket.socket() sock.connect((host, port)) @@ -39,7 +42,7 @@ class TestTestServer: def test_text_response(self): """the text_response_server sends the given text""" server = Server.text_response_server( - "HTTP/1.1 200 OK\r\n" + + "HTTP/1.1 200 OK\r\n" + "Content-Length: 6\r\n" + "\r\nroflol" ) @@ -49,8 +52,8 @@ class TestTestServer: assert r.status_code == 200 assert r.text == u'roflol' - assert r.headers['Content-Length'] == '6' - + assert r.headers['Content-Length'] == '6' + def test_basic_response(self): """the basic response server returns an empty http response""" with Server.basic_response_server() as (host, port): @@ -69,12 +72,12 @@ class TestTestServer: sock.sendall(b'send something') time.sleep(2.5) sock.sendall(b'still alive') - block_server.set() # release server block + block_server.set() # release server block def test_multiple_requests(self): """multiple requests can be served""" requests_to_handle = 5 - + server = Server.basic_response_server(requests_to_handle=requests_to_handle) with server as (host, port): @@ -96,7 +99,7 @@ class TestTestServer: with server as address: sock1 = socket.socket() sock2 = socket.socket() - + sock1.connect(address) sock1.sendall(first_request) sock1.close() @@ -121,19 +124,18 @@ class TestTestServer: assert server.handler_results[0] == b'' - def test_request_recovery_with_bigger_timeout(self): """a biggest timeout can be specified""" server = Server.basic_response_server(request_timeout=3) data = b'bananadine' with server as address: - sock = socket.socket() + sock = socket.socket() sock.connect(address) time.sleep(1.5) sock.sendall(data) sock.close() - + assert server.handler_results[0] == data def test_server_finishes_on_error(self): diff --git a/tests/test_utils.py b/tests/test_utils.py index ab5c2e37..8eb0a34f 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -389,6 +389,7 @@ def test_iter_slices(value, length): else: assert len(list(iter_slices(value, 1))) == length + @pytest.mark.parametrize( 'value, expected', ( (