Skip to content
Myr

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

8 files+115 added−18 removed

modified:requests/sessions.py+2 added-2 removed
226 unmodified lines
227228 if self.trust_env and not should_bypass_proxies(url):229 environ_proxies = get_environ_proxies(url)230231 proxy = environ_proxies.get(scheme)231 proxy = environ_proxies.get('all', environ_proxies.get(scheme))232233 if proxy:234 new_proxies.setdefault(scheme, environ_proxies[scheme])234 new_proxies.setdefault(scheme, proxy)235236 if 'Proxy-Authorization' in headers:237 del headers['Proxy-Authorization']238
451 unmodified lines
modified:requests/utils.py+14 added-5 removed
582 unmodified lines
583 """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))588589 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 break600601 return proxy602603604def 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 = iter([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+22 added
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_call155015511552@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])1558def test_proxy_env_vars_override_default(var, url, proxy):1559 session = requests.Session()1560 prep = PreparedRequest()1561 prep.prepare(method='GET', url=url)15621563 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] == proxy157115721573@pytest.mark.parametrize(1574 'data', (1575 (('a', 'b'), ('c', 'd')),1576 (('c', 'd'), ('a', 'b')),
73 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(
113 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