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
Provenance
- Commit
4bf8866- Tree
cfdea35- Author
Brett Higgins <brhiggins@arbor.net>- Committer
Brett Higgins <brhiggins@arbor.net>- Parent
1121f8b
7 files changed+92 added−31 removed
modified:requests/utils.py+14 added-5 removed
578 unmodified lines579 """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))584+585+ 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+ break596+597 return proxy598 599 600 def default_user_agent(name="python-requests"):137 unmodified linesmodified:tests/testserver/server.py+2 added-2 removed
23 unmodified lines24 class Server(threading.Thread):25 """Dummy server using for unit testing"""26 WAIT_EVENT_TIMEOUT = 527 28- 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__()30 31- self.handler = handler31+ self.handler = handler or consume_socket_content32 self.handler_results = []33 34 self.host = host35 self.port = port67 unmodified linesmodified:tests/test_lowlevel.py+38 added-1 removed
1+import os2+import pytest3 import threading4 import requests5 6 from tests.testserver.server import Server7 8+from .utils import override_environ9 10+11 def 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'])16 17 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 block21 22 assert r.status_code == 20023 assert r.request.headers['Transfer-Encoding'] == 'chunked'24+25+26+_schemes_by_var_prefix = [27+ ('http', ['http']),28+ ('https', ['https']),29+ ('all', ['http', 'https']),30+]31+32+_proxy_combos = []33+for prefix, schemes in _schemes_by_var_prefix:34+ for scheme in schemes:35+ _proxy_combos.append(("{0}_proxy".format(prefix), scheme))36+37+_proxy_combos += [(var.upper(), scheme) for var, scheme in _proxy_combos]38+39+40+@pytest.mark.parametrize("var,scheme", _proxy_combos)41+def 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)51+52+ # the fake proxy received a request53+ assert len(fake_proxy.handler_results) == 154+55+ # it had actual content (not checking for SOCKS protocol for now)56+ assert len(fake_proxy.handler_results[0]) > 0modified:tests/test_requests.py+1 added-15 removed
28 unmodified lines29 from requests.models import urlencode30 from requests.hooks import default_hooks31 32 from .compat import StringIO, u33+from .utils import override_environ34 35 # Requests to this URL should always fail with a connection timeout (nothing36 # listening on that port)37 TARPIT = 'http://10.255.255.1'1510 unmodified lines1548 send_call = SendCall((response.request,), default_keyword_args)1549 assert session.calls[-1] == send_call1550 1551 1551-@contextlib.contextmanager1552-def 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)1564-1565-1552 @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 linesmodified:tests/test_utils.py+19 added-8 removed
318 unmodified lines319 def test_dotted_netmask(mask, expected):320 assert dotted_netmask(mask) == expected321 322 323+http_proxies = {'http': 'http://http.proxy',324+ 'http://some.host': 'http://some.host.proxy'}325+all_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),334+335+ ('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),339+340+ # XXX: unsure whether this is reasonable behavior341+ ('file:///etc/motd', 'socks5://http.proxy', all_proxies),342 ))330-def test_select_proxies(url, expected):343+def 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) == expected346 347 348 @pytest.mark.parametrize(93 unmodified linesadded:tests/utils.py+17 added
1+import contextlib2+import os3+4+5+@contextlib.contextmanager6+def 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 lines9 Jinja2==2.810 MarkupSafe==0.2311 py==1.4.3112 Pygments==2.1.113+PySocks==1.5.614 pytest==2.8.715 pytest-cov==2.2.116 pytest-httpbin==0.2.017 pytest-mock==0.11.07 unmodified lines