Skip to content

Commit

Permalink
remove final remnants from 2.6
Browse files Browse the repository at this point in the history
  • Loading branch information
nateprewitt committed Oct 17, 2018
1 parent 6ae8a21 commit 7fd9267
Show file tree
Hide file tree
Showing 12 changed files with 42 additions and 70 deletions.
11 changes: 3 additions & 8 deletions requests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,14 @@ def _check_cryptography(cryptography_version):
return

if cryptography_version < [1, 3, 4]:
warning = 'Old version of cryptography ({0}) may cause slowdown.'.format(cryptography_version)
warning = 'Old version of cryptography ({}) may cause slowdown.'.format(cryptography_version)
warnings.warn(warning, RequestsDependencyWarning)

# Check imported dependencies for compatibility.
try:
check_compatibility(urllib3.__version__, chardet.__version__)
except (AssertionError, ValueError):
warnings.warn("urllib3 ({0}) or chardet ({1}) doesn't match a supported "
warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
"version!".format(urllib3.__version__, chardet.__version__),
RequestsDependencyWarning)

Expand Down Expand Up @@ -123,12 +123,7 @@ def _check_cryptography(cryptography_version):

# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
from logging import NullHandler

logging.getLogger(__name__).addHandler(NullHandler())

Expand Down
13 changes: 6 additions & 7 deletions requests/adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def cert_verify(self, conn, url, verify, cert):

if not cert_loc or not os.path.exists(cert_loc):
raise IOError("Could not find a suitable TLS CA certificate bundle, "
"invalid path: {0}".format(cert_loc))
"invalid path: {}".format(cert_loc))

conn.cert_reqs = 'CERT_REQUIRED'

Expand All @@ -247,10 +247,10 @@ def cert_verify(self, conn, url, verify, cert):
conn.key_file = None
if conn.cert_file and not os.path.exists(conn.cert_file):
raise IOError("Could not find the TLS certificate file, "
"invalid path: {0}".format(conn.cert_file))
"invalid path: {}".format(conn.cert_file))
if conn.key_file and not os.path.exists(conn.key_file):
raise IOError("Could not find the TLS key file, "
"invalid path: {0}".format(conn.key_file))
"invalid path: {}".format(conn.key_file))

def build_response(self, req, resp):
"""Builds a :class:`Response <requests.Response>` object from a urllib3
Expand Down Expand Up @@ -425,7 +425,7 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox
timeout = TimeoutSauce(connect=connect, read=read)
except ValueError as e:
# this may raise a string formatting error.
err = ("Invalid timeout {0}. Pass a (connect, read) "
err = ("Invalid timeout {}. Pass a (connect, read) "
"timeout tuple, or a single float to set "
"both timeouts to the same value".format(timeout))
raise ValueError(err)
Expand Down Expand Up @@ -475,11 +475,10 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox

# Receive the response from the server
try:
# For Python 2.7+ versions, use buffering of HTTP
# responses
# For Python 2.7, use buffering of HTTP responses
r = low_conn.getresponse(buffering=True)
except TypeError:
# For compatibility with Python 2.6 versions and back
# For compatibility with Python 3.3+
r = low_conn.getresponse()

resp = HTTPResponse.from_httplib(
Expand Down
4 changes: 2 additions & 2 deletions requests/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def _basic_auth_str(username, password):
if not isinstance(username, basestring):
warnings.warn(
"Non-string usernames will no longer be supported in Requests "
"3.0.0. Please convert the object you've passed in ({0!r}) to "
"3.0.0. Please convert the object you've passed in ({!r}) to "
"a string or bytes object in the near future to avoid "
"problems.".format(username),
category=DeprecationWarning,
Expand All @@ -48,7 +48,7 @@ def _basic_auth_str(username, password):
if not isinstance(password, basestring):
warnings.warn(
"Non-string passwords will no longer be supported in Requests "
"3.0.0. Please convert the object you've passed in ({0!r}) to "
"3.0.0. Please convert the object you've passed in ({!r}) to "
"a string or bytes object in the near future to avoid "
"problems.".format(password),
category=DeprecationWarning,
Expand Down
3 changes: 1 addition & 2 deletions requests/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,8 @@
import cookielib
from Cookie import Morsel
from StringIO import StringIO
from collections import Callable, Mapping, MutableMapping
from collections import Callable, Mapping, MutableMapping, OrderedDict

from urllib3.packages.ordered_dict import OrderedDict

builtin_str = str
bytes = str
Expand Down
3 changes: 1 addition & 2 deletions requests/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,7 @@ def info():
'version': getattr(idna, '__version__', ''),
}

# OPENSSL_VERSION_NUMBER doesn't exist in the Python 2.6 ssl module.
system_ssl = getattr(ssl, 'OPENSSL_VERSION_NUMBER', None)
system_ssl = ssl.OPENSSL_VERSION_NUMBER
system_ssl_info = {
'version': '%x' % system_ssl if system_ssl is not None else ''
}
Expand Down
11 changes: 3 additions & 8 deletions requests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def get_netrc_auth(url, raise_errors=False):

for f in NETRC_FILES:
try:
loc = os.path.expanduser('~/{0}'.format(f))
loc = os.path.expanduser('~/{}'.format(f))
except KeyError:
# os.path.expanduser can fail when $HOME is undefined and
# getpwuid fails. See https://bugs.python.org/issue20164 &
Expand Down Expand Up @@ -729,21 +729,16 @@ def should_bypass_proxies(url, no_proxy):
else:
host_with_port = parsed.hostname
if parsed.port:
host_with_port += ':{0}'.format(parsed.port)
host_with_port += ':{}'.format(parsed.port)

for host in no_proxy:
if parsed.hostname.endswith(host) or host_with_port.endswith(host):
# The URL does match something in no_proxy, so we don't want
# to apply the proxies on this URL.
return True

# If the system proxy settings indicate that this URL should be bypassed,
# don't proxy.
# The proxy_bypass function is incredibly buggy on OS X in early versions
# of Python 2.6, so allow this call to fail. Only catch the specific
# exceptions we've seen, though: this call failing in other ways can reveal
# legitimate problems.
with set_environ('no_proxy', no_proxy_arg):
# parsed.hostname can be `None` in cases such as a file URI.
try:
bypass = proxy_bypass(parsed.hostname)
except (TypeError, socket.gaierror):
Expand Down
12 changes: 3 additions & 9 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,6 @@ def run_tests(self):
os.system('twine upload dist/*')
sys.exit()

# pyOpenSSL version 18.0.0 dropped support for Python 2.6
if sys.version_info < (2, 7):
PYOPENSSL_VERSION = 'pyOpenSSL >= 0.14, < 18.0.0'
else:
PYOPENSSL_VERSION = 'pyOpenSSL >= 0.14'

packages = ['requests']

requires = [
Expand Down Expand Up @@ -85,7 +79,7 @@ def run_tests(self):
package_data={'': ['LICENSE', 'NOTICE'], 'requests': ['*.pem']},
package_dir={'requests': 'requests'},
include_package_data=True,
python_requires=">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
install_requires=requires,
license=about['__license__'],
zip_safe=False,
Expand All @@ -108,8 +102,8 @@ def run_tests(self):
cmdclass={'test': PyTest},
tests_require=test_requirements,
extras_require={
'security': [PYOPENSSL_VERSION, 'cryptography>=1.3.4', 'idna>=2.0.0'],
'security': ['pyOpenSSL >= 0.14', 'cryptography>=1.3.4', 'idna>=2.0.0'],
'socks': ['PySocks>=1.5.6, !=1.5.7'],
'socks:sys_platform == "win32" and (python_version == "2.7" or python_version == "2.6")': ['win_inet_pton'],
'socks:sys_platform == "win32" and python_version == "2.7"': ['win_inet_pton'],
},
)
9 changes: 0 additions & 9 deletions tests/test_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,6 @@
from requests.help import info


@pytest.mark.skipif(sys.version_info[:2] != (2,6), reason="Only run on Python 2.6")
def test_system_ssl_py26():
"""OPENSSL_VERSION_NUMBER isn't provided in Python 2.6, verify we don't
blow up in this case.
"""
assert info()['system_ssl'] == {'version': ''}


@pytest.mark.skipif(sys.version_info < (2,7), reason="Only run on Python 2.7+")
def test_system_ssl():
"""Verify we're actually setting system_ssl when it should be available."""
assert info()['system_ssl']['version'] != ''
Expand Down
28 changes: 14 additions & 14 deletions tests/test_lowlevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def test_chunked_upload():
data = iter([b'a', b'b', b'c'])

with server as (host, port):
url = 'http://{0}:{1}/'.format(host, port)
url = 'http://{}:{}/'.format(host, port)
r = requests.post(url, data=data, stream=True)
close_server.set() # release server block

Expand Down Expand Up @@ -77,7 +77,7 @@ def digest_response_handler(sock):
server = Server(digest_response_handler, wait_to_close_event=close_server)

with server as (host, port):
url = 'http://{0}:{1}/'.format(host, port)
url = 'http://{}:{}/'.format(host, port)
r = requests.get(url, auth=auth)
# Verify server succeeded in authenticating.
assert r.status_code == 200
Expand Down Expand Up @@ -127,7 +127,7 @@ def digest_failed_response_handler(sock):
server = Server(digest_failed_response_handler, wait_to_close_event=close_server)

with server as (host, port):
url = 'http://{0}:{1}/'.format(host, port)
url = 'http://{}:{}/'.format(host, port)
r = requests.get(url, auth=auth)
# Verify server didn't authenticate us.
assert r.status_code == 401
Expand Down Expand Up @@ -164,7 +164,7 @@ def digest_response_handler(sock):
server = Server(digest_response_handler, wait_to_close_event=close_server)

with server as (host, port):
url = 'http://{0}:{1}/'.format(host, port)
url = 'http://{}:{}/'.format(host, port)
r = requests.get(url, auth=auth)
# Verify server didn't receive auth from us.
assert r.status_code == 200
Expand All @@ -181,17 +181,17 @@ def digest_response_handler(sock):
_proxy_combos = []
for prefix, schemes in _schemes_by_var_prefix:
for scheme in schemes:
_proxy_combos.append(("{0}_proxy".format(prefix), scheme))
_proxy_combos.append(("{}_proxy".format(prefix), scheme))

_proxy_combos += [(var.upper(), scheme) for var, scheme in _proxy_combos]


@pytest.mark.parametrize("var,scheme", _proxy_combos)
def test_use_proxy_from_environment(httpbin, var, scheme):
url = "{0}://httpbin.org".format(scheme)
url = "{}://httpbin.org".format(scheme)
fake_proxy = Server() # do nothing with the requests; just close the socket
with fake_proxy as (host, port):
proxy_url = "socks5://{0}:{1}".format(host, port)
proxy_url = "socks5://{}:{}".format(host, port)
kwargs = {var: proxy_url}
with override_environ(**kwargs):
# fake proxy's lack of response will cause a ConnectionError
Expand All @@ -212,7 +212,7 @@ def test_redirect_rfc1808_to_non_ascii_location():

def redirect_resp_handler(sock):
consume_socket_content(sock, timeout=0.5)
location = u'//{0}:{1}/{2}'.format(host, port, path)
location = u'//{}:{}/{}'.format(host, port, path)
sock.send(
b'HTTP/1.1 301 Moved Permanently\r\n'
b'Content-Length: 0\r\n'
Expand All @@ -226,13 +226,13 @@ def redirect_resp_handler(sock):
server = Server(redirect_resp_handler, wait_to_close_event=close_server)

with server as (host, port):
url = u'http://{0}:{1}'.format(host, port)
url = u'http://{}:{}'.format(host, port)
r = requests.get(url=url, allow_redirects=True)
assert r.status_code == 200
assert len(r.history) == 1
assert r.history[0].status_code == 301
assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')
assert r.url == u'{0}/{1}'.format(url, expected_path.decode('ascii'))
assert r.url == u'{}/{}'.format(url, expected_path.decode('ascii'))

close_server.set()

Expand All @@ -250,7 +250,7 @@ def response_handler(sock):
server = Server(response_handler, wait_to_close_event=close_server)

with server as (host, port):
url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)
url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)
r = requests.get(url)
raw_request = r.content

Expand Down Expand Up @@ -293,7 +293,7 @@ def response_handler(sock):
server = Server(response_handler, wait_to_close_event=close_server)

with server as (host, port):
url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)
url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)
r = requests.get(url)
raw_request = r.content

Expand All @@ -302,8 +302,8 @@ def response_handler(sock):
assert r.history[0].request.url == url

# Verify we haven't overwritten the location with our previous fragment.
assert r.history[1].request.url == 'http://{0}:{1}/get#relevant-section'.format(host, port)
assert r.history[1].request.url == 'http://{}:{}/get#relevant-section'.format(host, port)
# Verify previous fragment is used and not the original.
assert r.url == 'http://{0}:{1}/final-url/#relevant-section'.format(host, port)
assert r.url == 'http://{}:{}/final-url/#relevant-section'.format(host, port)

close_server.set()
10 changes: 5 additions & 5 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def test_mixed_case_scheme_acceptable(self, httpbin, scheme):
url = scheme + parts.netloc + parts.path
r = requests.Request('GET', url)
r = s.send(r.prepare())
assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)
assert r.status_code == 200, 'failed for scheme {}'.format(scheme)

def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):
r = requests.Request('GET', httpbin('get'))
Expand Down Expand Up @@ -816,17 +816,17 @@ def test_invalid_ca_certificate_path(self, httpbin_secure):
INVALID_PATH = '/garbage'
with pytest.raises(IOError) as e:
requests.get(httpbin_secure(), verify=INVALID_PATH)
assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {0}'.format(INVALID_PATH)
assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {}'.format(INVALID_PATH)

def test_invalid_ssl_certificate_files(self, httpbin_secure):
INVALID_PATH = '/garbage'
with pytest.raises(IOError) as e:
requests.get(httpbin_secure(), cert=INVALID_PATH)
assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {0}'.format(INVALID_PATH)
assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {}'.format(INVALID_PATH)

with pytest.raises(IOError) as e:
requests.get(httpbin_secure(), cert=('.', INVALID_PATH))
assert str(e.value) == 'Could not find the TLS key file, invalid path: {0}'.format(INVALID_PATH)
assert str(e.value) == 'Could not find the TLS key file, invalid path: {}'.format(INVALID_PATH)

def test_http_with_certificate(self, httpbin):
r = requests.get(httpbin(), cert='.')
Expand Down Expand Up @@ -1458,7 +1458,7 @@ def test_params_are_merged_case_sensitive(self, httpbin):
assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}

def test_long_authinfo_in_url(self):
url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(
url = 'http://{}:{}@{}:9000/path?query#frag'.format(
'E8A3BE87-9E3F-4620-8858-95478E385B5B',
'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',
'exactly-------------sixty-----------three------------characters',
Expand Down
6 changes: 3 additions & 3 deletions tests/test_testserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def test_text_response(self):
)

with server as (host, port):
r = requests.get('http://{0}:{1}'.format(host, port))
r = requests.get('http://{}:{}'.format(host, port))

assert r.status_code == 200
assert r.text == u'roflol'
Expand All @@ -59,7 +59,7 @@ def test_text_response(self):
def test_basic_response(self):
"""the basic response server returns an empty http response"""
with Server.basic_response_server() as (host, port):
r = requests.get('http://{0}:{1}'.format(host, port))
r = requests.get('http://{}:{}'.format(host, port))
assert r.status_code == 200
assert r.text == u''
assert r.headers['Content-Length'] == '0'
Expand All @@ -83,7 +83,7 @@ def test_multiple_requests(self):
server = Server.basic_response_server(requests_to_handle=requests_to_handle)

with server as (host, port):
server_url = 'http://{0}:{1}'.format(host, port)
server_url = 'http://{}:{}'.format(host, port)
for _ in range(requests_to_handle):
r = requests.get(server_url)
assert r.status_code == 200
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tox]
envlist = py26,py27,py34,py35,py36
envlist = py27,py34,py35,py36

[testenv]

Expand Down

0 comments on commit 7fd9267

Please sign in to comment.