Fix failing test_proxy
I was getting the following error in my environment:
> E   socket.gaierror: [Errno 8] nodename nor servname provided, or not known
Binding to `localhost` by hostname is error-prone anyways, so it has
been changed to `127.0.0.1`.
@@ -34,24 +34,49 @@ def pipe_sockets(sock1, sock2, timeout):
sock.close()
+class Future(object):
+ # concurrent.futures.Future docs say that they shouldn't be instantiated
+ # directly, so this is a simple implementation which mimics the Future
+ # which can safely be instantiated!
+
+ def __init__(self):
+ self._event = threading.Event()
+ self._result = None
+ self._exc = None
+
+ def result(self, timeout=None):
+ if not self._event.wait(timeout):
+ raise AssertionError("Future timed out")
+ if self._exc is not None:
+ raise self._exc
+ return self._result
+
+ def set_result(self, result):
+ self._result = result
+ self._event.set()
+
+ def set_exception(self, exception):
+ self._exc = exception
+ self._event.set()
+
+
class ProxyServerThread(threading.Thread):
spinup_timeout = 10
def __init__(self, timeout=None):
- self.proxy_host = 'localhost'
+ self.proxy_host = '127.0.0.1'
self.proxy_port = None # randomly selected by OS
self.timeout = timeout
self.proxy_server = None
- self.socket_created_event = threading.Event()
+ self.socket_created_future = Future()
self.requests = []
super(ProxyServerThread, self).__init__()
self.daemon = True
def get_proxy_url(self):
- if not self.socket_created_event.wait(self.spinup_timeout):
- raise AssertionError("Proxy Server didn't successfully start")
+ assert self.socket_created_future.result(self.spinup_timeout)
return "http://%s:%s" % (self.proxy_host, self.proxy_port)
def run(self):
@@ -98,6 +123,7 @@ class ProxyServerThread(threading.Thread):
# the serve_forever loop doesn't block until connection is closed
# (unlike TCPServer). This allows to shutdown the serve_forever loop
# even if there's an open connection.
+ try:
self.proxy_server = SocketServer.ThreadingTCPServer(
(self.proxy_host, 0),
Proxy
@@ -107,7 +133,12 @@ class ProxyServerThread(threading.Thread):
self.proxy_server.daemon_threads = True
self.proxy_port = self.proxy_server.server_address[1]
- self.socket_created_event.set()
+ except Exception as e:
+ self.socket_created_future.set_exception(e)
+ raise
+ else:
+ self.socket_created_future.set_result(True)
+
self.proxy_server.serve_forever()
def stop(self):
