Merge pull request #3185 from brettdh/3183-support-all-proxy-env-var
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Support ALL_PROXY environment variable
authored by Ian Cordasco · committed by Ian Cordasco · parents 12e3631, 35744c3 · Browse files · 8 files·+115 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+115 added−18 removed
- tests:+98 added−11 removed
- other:+17 added−7 removed
Provenance
- Commit
cd4e6b9- Tree
c7641bb- Author
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Committer
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Parent 1
12e3631- Parent 2
35744c3
8 files changed+115 added−18 removed
modified:requests/sessions.py+2 added-2 removed
226 unmodified lines227 228 if self.trust_env and not should_bypass_proxies(url):229 environ_proxies = get_environ_proxies(url)230 231- proxy = environ_proxies.get(scheme)231+ proxy = environ_proxies.get('all', environ_proxies.get(scheme))232 233 if proxy:234- new_proxies.setdefault(scheme, environ_proxies[scheme])234+ new_proxies.setdefault(scheme, proxy)235 236 if 'Proxy-Authorization' in headers:237 del headers['Proxy-Authorization']238 451 unmodified linesmodified:requests/utils.py+14 added-5 removed
582 unmodified lines583 """584 proxies = proxies or {}585 urlparts = urlparse(url)586 if urlparts.hostname is None:587- proxy = None588- else:589- proxy = proxies.get(urlparts.scheme+'://'+urlparts.hostname)590- if proxy is None:591- proxy = proxies.get(urlparts.scheme)587+ return proxies.get('all', proxies.get(urlparts.scheme))588+589+ proxy_keys = [590+ 'all://' + urlparts.hostname,591+ 'all',592+ urlparts.scheme + '://' + urlparts.hostname,593+ urlparts.scheme,594+ ]595+ proxy = None596+ for proxy_key in proxy_keys:597+ if proxy_key in proxies:598+ proxy = proxies[proxy_key]599+ break600+601 return proxy602 603 604 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 = iter([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+22 added
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 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'),1556+ ('all_proxy', 'https://example.com', 'socks5://proxy.com:9876'),1557+])1558+def test_proxy_env_vars_override_default(var, url, proxy):1559+ session = requests.Session()1560+ prep = PreparedRequest()1561+ prep.prepare(method='GET', url=url)1562+1563+ kwargs = {1564+ var: proxy1565+ }1566+ scheme = urlparse(url).scheme1567+ with override_environ(**kwargs):1568+ proxies = session.rebuild_proxies(prep, {})1569+ assert scheme in proxies1570+ assert proxies[scheme] == proxy1571+1572+1573 @pytest.mark.parametrize(1574 'data', (1575 (('a', 'b'), ('c', 'd')),1576 (('c', 'd'), ('a', 'b')),73 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(113 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