1
1
"""Test using a proxy."""
2
2
3
+ import asyncio
3
4
import http .server
4
5
import socketserver
5
6
import threading
@@ -36,6 +37,35 @@ def do_GET(self):
36
37
self .end_headers ()
37
38
self .copyfile (upstream_response , self .wfile )
38
39
40
+ def do_CONNECT (self ):
41
+ host , port = self .path .split (":" )
42
+
43
+ asyncio .run (self ._tunnel (host , port , self .connection ))
44
+
45
+ async def _tunnel (self , host , port , client_sock ):
46
+ target_r , target_w = await asyncio .open_connection (host = host , port = port )
47
+
48
+ self .send_response (http .HTTPStatus .OK )
49
+ self .end_headers ()
50
+
51
+ source_r , source_w = await asyncio .open_connection (sock = client_sock )
52
+
53
+ async def channel (reader , writer ):
54
+ while True :
55
+ data = await reader .read (1024 )
56
+ if not data :
57
+ break
58
+ writer .write (data )
59
+ await writer .drain ()
60
+
61
+ writer .close ()
62
+ await writer .wait_closed ()
63
+
64
+ await asyncio .gather (
65
+ channel (target_r , source_w ),
66
+ channel (source_r , target_w ),
67
+ )
68
+
39
69
40
70
@pytest .fixture (scope = "session" )
41
71
def proxy_server ():
@@ -52,10 +82,26 @@ def test_use_proxy(tmpdir, httpbin, proxy_server):
52
82
with vcr .use_cassette (str (tmpdir .join ("proxy.yaml" ))):
53
83
response = requests .get (httpbin .url , proxies = {"http" : proxy_server })
54
84
55
- with vcr .use_cassette (str (tmpdir .join ("proxy.yaml" )), mode = "once " ) as cassette :
85
+ with vcr .use_cassette (str (tmpdir .join ("proxy.yaml" )), mode = "none " ) as cassette :
56
86
cassette_response = requests .get (httpbin .url , proxies = {"http" : proxy_server })
57
87
58
- for key in set (cassette_response .headers .keys ()) & set (response .headers .keys ()):
59
- assert cassette_response .headers [key ] == response .headers [key ]
60
88
assert cassette_response .headers == response .headers
61
89
assert cassette .play_count == 1
90
+
91
+
92
+ def test_use_https_proxy (tmpdir , httpbin_secure , proxy_server ):
93
+ """Ensure that it works with an HTTPS proxy."""
94
+ with vcr .use_cassette (str (tmpdir .join ("proxy.yaml" ))):
95
+ response = requests .get (httpbin_secure .url , proxies = {"https" : proxy_server })
96
+
97
+ with vcr .use_cassette (str (tmpdir .join ("proxy.yaml" )), mode = "none" ) as cassette :
98
+ cassette_response = requests .get (
99
+ httpbin_secure .url ,
100
+ proxies = {"https" : proxy_server },
101
+ )
102
+
103
+ assert cassette_response .headers == response .headers
104
+ assert cassette .play_count == 1
105
+
106
+ # The cassette URL points to httpbin, not the proxy
107
+ assert cassette .requests [0 ].url == httpbin_secure .url + "/"
0 commit comments