import eventlet
import tests
socket = eventlet.patcher.original('socket')
threading = eventlet.patcher.original('threading')

class TcpEchoClientProtocol(tests.asyncio.Protocol):
    def __init__(self, message, loop):
        self.message = message
        self.loop = loop
        self.state = 'new'
        self.received = None

    def connection_made(self, transport):
        self.state = 'ping'
        transport.write(self.message)

    def data_received(self, data):
        self.state = 'pong'
        self.received = data

    def connection_lost(self, exc):
        self.state = 'closed'
        self.loop.stop()


class TcpServer(threading.Thread):
    def __init__(self, host, port):
        super(TcpServer, self).__init__()
        self.host = host
        self.port = port
        self.sock = None
        self.client = None

    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock = sock
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind((self.host, self.port))
            sock.listen(1)

            client, addr = sock.accept()
            self.client = client
            try:
                message = client.recv(100)
                client.sendall(message)
            finally:
                client.close()
                self.client = None
        finally:
            sock.close()
            self.sock = None

    def stop(self):
        self.join()


class NetworkTests(tests.TestCase):
    def test_tcp_hello(self):
        port = 8888
        host = '127.0.0.1'
        message = b'Hello World!'

        server = TcpServer(host, port)
        server.start()
        self.addCleanup(server.stop)

        proto = TcpEchoClientProtocol(message, self.loop)
        coro = self.loop.create_connection(lambda: proto, host, port)
        self.loop.run_until_complete(coro)
        self.assertNotEqual(proto.state, 'new')

        self.loop.run_forever()
        self.assertEqual(proto.state, 'closed')
        self.assertEqual(proto.received, message)


if __name__ == '__main__':
    import unittest
    unittest.main()

@@ -683,24 +683,31 @@
 , host, port
+, event
 ):%0A        s
@@ -789,16 +789,43 @@
  = port%0A
+        self.event = event%0A
         
@@ -1136,16 +1136,45 @@
 ten(1)%0A%0A
+            self.event.set()%0A
         
@@ -1688,16 +1688,50 @@
 orld!'%0A%0A
+        event = threading.Event()%0A
         
@@ -1751,32 +1751,39 @@
 erver(host, port
+, event
 )%0A        server
@@ -1827,16 +1827,37 @@
 er.stop)
+%0A        event.wait()
 %0A%0A      

Fix test_tcp_hello(): wait until the server is listening