Skip to content
Myr

Add 'all' proxy selection to select_proxy

Before adoption: this commit came in with the history the project adopted, so no landing records it.

It seems it's necessary both in pulling all_proxy from the environment (rebuild_proxies) and deciding which proxy to use (select_proxy). Also added new functional test.

authored by Brett Higgins · committed by Brett Higgins · parent 1121f8b · Browse files · 7 files+92 added−31 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+92 added−31 removed

  • tests:+77 added−26 removed
  • other:+15 added−5 removed

7 files+92 added−31 removed

modified:requests/utils.py+14 added-5 removed
578 unmodified lines
579 """580 proxies = proxies or {}581 urlparts = urlparse(url)582 if urlparts.hostname is None:583 proxy = None584 else:585 proxy = proxies.get(urlparts.scheme+'://'+urlparts.hostname)586 if proxy is None:587 proxy = proxies.get(urlparts.scheme)583 return proxies.get('all', proxies.get(urlparts.scheme))584585 proxy_keys = [586 'all://' + urlparts.hostname,587 'all',588 urlparts.scheme + '://' + urlparts.hostname,589 urlparts.scheme,590 ]591 proxy = None592 for proxy_key in proxy_keys:593 if proxy_key in proxies:594 proxy = proxies[proxy_key]595 break596597 return proxy598599600def default_user_agent(name="python-requests"):
137 unmodified lines
modified:tests/testserver/server.py+2 added-2 removed
23 unmodified lines
24class Server(threading.Thread):25 """Dummy server using for unit testing"""26 WAIT_EVENT_TIMEOUT = 52728 def __init__(self, handler, host='localhost', port=0, requests_to_handle=1, wait_to_close_event=None):28 def __init__(self, handler=None, host='localhost', port=0, requests_to_handle=1, wait_to_close_event=None):29 super(Server, self).__init__()3031 self.handler = handler31 self.handler = handler or consume_socket_content32 self.handler_results = []3334 self.host = host35 self.port = port
67 unmodified lines
modified:tests/test_lowlevel.py+38 added-1 removed
1import os2import pytest3import threading4import requests56from tests.testserver.server import Server78from .utils import override_environ91011def test_chunked_upload():12 """can safely send generators"""13 close_server = threading.Event()14 server = Server.basic_response_server(wait_to_close_event=close_server)11 data = (i for i in [b'a', b'b', b'c']) 15 data = (i for i in [b'a', b'b', b'c'])1617 with server as (host, port):18 url = 'http://{0}:{1}/'.format(host, port)19 r = requests.post(url, data=data, stream=True)20 close_server.set() # release server block2122 assert r.status_code == 20023 assert r.request.headers['Transfer-Encoding'] == 'chunked'242526_schemes_by_var_prefix = [27 ('http', ['http']),28 ('https', ['https']),29 ('all', ['http', 'https']),30]3132_proxy_combos = []33for prefix, schemes in _schemes_by_var_prefix:34 for scheme in schemes:35 _proxy_combos.append(("{0}_proxy".format(prefix), scheme))3637_proxy_combos += [(var.upper(), scheme) for var, scheme in _proxy_combos]383940@pytest.mark.parametrize("var,scheme", _proxy_combos)41def test_use_proxy_from_environment(httpbin, var, scheme):42 url = "{0}://httpbin.org".format(scheme)43 fake_proxy = Server() # do nothing with the requests; just close the socket44 with fake_proxy as (host, port):45 proxy_url = "socks5://{0}:{1}".format(host, port)46 kwargs = {var: proxy_url}47 with override_environ(**kwargs):48 # fake proxy's lack of response will cause a ConnectionError49 with pytest.raises(requests.exceptions.ConnectionError):50 requests.get(url)5152 # the fake proxy received a request53 assert len(fake_proxy.handler_results) == 15455 # it had actual content (not checking for SOCKS protocol for now)56 assert len(fake_proxy.handler_results[0]) > 0
modified:tests/test_requests.py+1 added-15 removed
28 unmodified lines
29from requests.models import urlencode30from requests.hooks import default_hooks3132from .compat import StringIO, u33from .utils import override_environ3435# Requests to this URL should always fail with a connection timeout (nothing36# listening on that port)37TARPIT = 'http://10.255.255.1'
1510 unmodified lines
1548 send_call = SendCall((response.request,), default_keyword_args)1549 assert session.calls[-1] == send_call155015511551@contextlib.contextmanager1552def override_environ(**kwargs):1553 save_env = dict(os.environ)1554 for key, value in kwargs.items():1555 if value is None:1556 del os.environ[key]1557 else:1558 os.environ[key] = value1559 try:1560 yield1561 finally:1562 os.environ.clear()1563 os.environ.update(save_env)156415651552@pytest.mark.parametrize("var,url,proxy", [1553 ('http_proxy', 'http://example.com', 'socks5://proxy.com:9876'),1554 ('https_proxy', 'https://example.com', 'socks5://proxy.com:9876'),1555 ('all_proxy', 'http://example.com', 'socks5://proxy.com:9876'),
94 unmodified lines
modified:tests/test_utils.py+19 added-8 removed
318 unmodified lines
319def test_dotted_netmask(mask, expected):320 assert dotted_netmask(mask) == expected321322323http_proxies = {'http': 'http://http.proxy',324 'http://some.host': 'http://some.host.proxy'}325all_proxies = {'all': 'socks5://http.proxy',326 'all://some.host': 'socks5://some.host.proxy'}327@pytest.mark.parametrize(324 'url, expected', (325 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy'),326 ('hTTp://u:p@Other.Host/path', 'http://http.proxy'),327 ('hTTps://Other.Host', None),328 ('file:///etc/motd', None),328 'url, expected, proxies', (329 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),330 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),331 ('hTTp:///path', 'http://http.proxy', http_proxies),332 ('hTTps://Other.Host', None, http_proxies),333 ('file:///etc/motd', None, http_proxies),334335 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),336 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),337 ('hTTp:///path', 'socks5://http.proxy', all_proxies),338 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),339340 # XXX: unsure whether this is reasonable behavior341 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),342 ))330def test_select_proxies(url, expected):343def test_select_proxies(url, expected, proxies):344 """Make sure we can select per-host proxies correctly."""332 proxies = {'http': 'http://http.proxy',333 'http://some.host': 'http://some.host.proxy'}345 assert select_proxy(url, proxies) == expected346347348@pytest.mark.parametrize(
93 unmodified lines
added:tests/utils.py+17 added
1import contextlib2import os345@contextlib.contextmanager6def override_environ(**kwargs):7 save_env = dict(os.environ)8 for key, value in kwargs.items():9 if value is None:10 del os.environ[key]11 else:12 os.environ[key] = value13 try:14 yield15 finally:16 os.environ.clear()17 os.environ.update(save_env)
modified:requirements.txt+1 added
8 unmodified lines
9Jinja2==2.810MarkupSafe==0.2311py==1.4.3112Pygments==2.1.113PySocks==1.5.614pytest==2.8.715pytest-cov==2.2.116pytest-httpbin==0.2.017pytest-mock==0.11.0
7 unmodified lines