@@ -81,17 +81,65 @@ def _wrap_socket(self, sock):
81
81
def run (self ):
82
82
self .server = self ._start_server ()
83
83
84
+ class SocketProxyThread (threading .Thread ):
85
+ """
86
+ :param ready_event: Event which gets set when the socket handler is
87
+ ready to receive requests.
88
+ """
89
+ def __init__ (self ,
90
+ socket_handler ,
91
+ proxy_host = 'localhost' ,
92
+ host = 'localhost' ,
93
+ port = 80 ,
94
+ secure = False ):
95
+ threading .Thread .__init__ (self )
96
+
97
+ self .socket_handler = socket_handler
98
+ self .host = host
99
+ self .port = port
100
+ self .proxy_host = proxy_host
101
+ self .daemon = True
102
+
103
+ assert not self .secure , "HTTPS Proxies not supported"
104
+
105
+ def _start_proxy (self ):
106
+ tx_sock = socket .socket (socket .AF_INET6 )
107
+ rx_sock = socket .socket (socket .AF_INET6 )
108
+
109
+ if sys .platform != 'win32' :
110
+ for sock in [tx_sock , rx_sock ]:
111
+ sock .setsockopt (socket .SOL_SOCKET , socket .SO_REUSEADDR , 1 )
112
+
113
+ sock_rx .bind ((self .proxy_host , 0 ))
114
+ self .proxy_port = sock_rx .getsockname ()[1 ]
115
+
116
+ # Once listen() returns, the server socket is ready
117
+ rx_sock .listen (1 )
118
+ tx_sock .connect ((host , port ))
119
+
120
+ self .socket_handler (tx_sock , rx_sock )
121
+ sock .close ()
122
+
123
+ def _wrap_socket (self , sock ):
124
+ raise NotImplementedError ()
125
+
126
+ def run (self ):
127
+ self .proxy = self ._start_proxy ()
128
+
84
129
85
130
class SocketLevelTest (object ):
86
131
"""
87
132
A test-class that defines a few helper methods for running socket-level
88
133
tests.
89
134
"""
90
- def set_up (self , secure = True ):
135
+ def set_up (self , secure = True , proxy = False ):
91
136
self .host = None
92
137
self .port = None
93
- self .secure = secure
138
+ self .proxy = proxy
139
+ self .secure = secure if not proxy else False
140
+
94
141
self .server_thread = None
142
+ self .proxy_thread = None
95
143
96
144
def _start_server (self , socket_handler ):
97
145
"""
@@ -110,6 +158,24 @@ def _start_server(self, socket_handler):
110
158
self .port = self .server_thread .port
111
159
self .secure = self .server_thread .secure
112
160
161
+ if proxy :
162
+ self ._start_proxy ()
163
+ self .proxy_host = self .proxy_thread .proxy_host
164
+
165
+ def _start_proxy (self ):
166
+ """
167
+ Starts a background thread that runs the given socket handler.
168
+ """
169
+ def _proxy_socket_handler (tx_sock , rx_sock ):
170
+ rx_sock_add = rx_sock .accept ()[0 ]
171
+ tx_sock .send (rx_sock_add .recv (65535 ))
172
+ rx_sock_add = sock .close ()
173
+
174
+ self .proxy_thread = SocketProxyThread (
175
+ socket_handler = _proxy_socket_handler
176
+ )
177
+ self .proxy_thread .start ()
178
+
113
179
def get_connection (self ):
114
180
if self .h2 :
115
181
return HTTP20Connection (self .host , self .port , self .secure )
0 commit comments