2121from unittest .mock import Mock , patch
2222
2323import requests_mock
24+ from requests .adapters import HTTPAdapter
2425from requests .exceptions import ConnectTimeout
2526
2627import libcloud .common .base
@@ -36,6 +37,7 @@ class BaseConnectionClassTestCase(unittest.TestCase):
3637 def setUp (self ):
3738 self .orig_http_proxy = os .environ .pop ("http_proxy" , None )
3839 self .orig_https_proxy = os .environ .pop ("https_proxy" , None )
40+ self .orig_no_proxy = os .environ .pop ("no_proxy" , None )
3941
4042 def tearDown (self ):
4143 if self .orig_http_proxy :
@@ -48,6 +50,11 @@ def tearDown(self):
4850 elif "https_proxy" in os .environ :
4951 del os .environ ["https_proxy" ]
5052
53+ if self .orig_no_proxy :
54+ os .environ ["no_proxy" ] = self .orig_no_proxy
55+ elif "no_proxy" in os .environ :
56+ del os .environ ["no_proxy" ]
57+
5158 libcloud .common .base .ALLOW_PATH_DOUBLE_SLASHES = False
5259
5360 def test_parse_proxy_url (self ):
@@ -154,6 +161,40 @@ def test_constructor(self):
154161 {"http" : "https://127.0.0.6:3129" , "https" : "https://127.0.0.6:3129" },
155162 )
156163
164+ def test_proxy_environment_variables_respected (self ):
165+ """
166+ Test that proxy environment variables are respected by the underlying Requests library
167+ """
168+ def mock_send (self , request , ** kwargs ):
169+ captured_proxies .update (kwargs .get ('proxies' , {}))
170+ nonlocal captured_url
171+ captured_url = request .url
172+ mock_response = Mock ()
173+ mock_response .status_code = 200
174+ mock_response .headers = {'content-type' : 'application/json' , 'location' : '' }
175+ mock_response .text = "OK"
176+ mock_response .history = [] # No redirects
177+ return mock_response
178+
179+ with patch .object (HTTPAdapter , 'send' , mock_send ):
180+ os .environ ["http_proxy" ] = "http://proxy.example.com:8080"
181+ os .environ ["https_proxy" ] = "https://secure-proxy.example.com:8443"
182+ os .environ ["no_proxy" ] = "localhost,127.0.0.1"
183+ captured_proxies = {}
184+ captured_url = None
185+
186+ conn = LibcloudConnection (host = "localhost" , port = 80 )
187+ conn .request ("GET" , "/get" )
188+
189+ self .assertEqual (captured_proxies , {})
190+ self .assertIn ('localhost' , captured_url )
191+
192+ conn = LibcloudConnection (host = "test.com" , port = 80 )
193+ conn .request ("GET" , "/get" )
194+
195+ self .assertEqual (captured_proxies .get ('http' , None ), 'http://proxy.example.com:8080' )
196+ self .assertEqual (captured_proxies .get ('https' , None ), 'https://secure-proxy.example.com:8443' )
197+
157198 def test_connection_to_unusual_port (self ):
158199 conn = LibcloudConnection (host = "localhost" , port = 8080 )
159200 self .assertIsNone (conn .proxy_scheme )
0 commit comments