diff --git a/Lib/test/test_asyncore.py b/Lib/test/test_asyncore.py index aa2d732faf8..f19ff35f9ed 100644 --- a/Lib/test/test_asyncore.py +++ b/Lib/test/test_asyncore.py @@ -12,7 +12,7 @@ from test.test_support import TESTFN, run_unittest, unlink from StringIO import StringIO HOST = "127.0.0.1" -PORT = 54329 +PORT = None class dummysocket: def __init__(self): @@ -53,12 +53,14 @@ class crashingdummy: # used when testing senders; just collects what it gets until newline is sent def capture_server(evt, buf): - serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - serv.settimeout(3) - serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - serv.bind(("", PORT)) - serv.listen(5) try: + serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + serv.settimeout(3) + serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + serv.bind(("", 0)) + global PORT + PORT = serv.getsockname()[1] + serv.listen(5) conn, addr = serv.accept() except socket.timeout: pass @@ -78,6 +80,7 @@ def capture_server(evt, buf): conn.close() finally: serv.close() + PORT = None evt.set() @@ -338,12 +341,26 @@ class DispatcherWithSendTests(unittest.TestCase): self.evt = threading.Event() cap = StringIO() threading.Thread(target=capture_server, args=(self.evt,cap)).start() - time.sleep(1) # Give server time to initialize - data = "Suppose there isn't a 16-ton weight?"*5 + # wait until server thread has assigned a port number + n = 1000 + while PORT is None and n > 0: + time.sleep(0.01) + n -= 1 + + # wait a little longer for the server to initialize (it sometimes + # refuses connections on slow machines without this wait) + time.sleep(0.2) + + data = "Suppose there isn't a 16-ton weight?" d = dispatcherwithsend_noread() d.create_socket(socket.AF_INET, socket.SOCK_STREAM) d.connect((HOST, PORT)) + + # give time for socket to connect + time.sleep(0.1) + + d.send(data) d.send(data) d.send('\n') @@ -354,7 +371,7 @@ class DispatcherWithSendTests(unittest.TestCase): self.evt.wait() - self.assertEqual(cap.getvalue(), data) + self.assertEqual(cap.getvalue(), data*2) class DispatcherWithSendTests_UsePoll(DispatcherWithSendTests):