I am trying to verify a code that reconnects to the server after disconnecting. This works fine outside of tests, but does not confirm that the socket is disconnected during tests.
I am using a Gevent Stream server to bully a real listening server:
import gevent.server from gevent import queue class TestServer(gevent.server.StreamServer): def __init__(self, *args, **kwargs): super(TestServer, self).__init__(*args, **kwargs) self.sockets = {} def handle(self, socket, address): self.sockets[address] = (socket, queue.Queue()) socket.sendall('testing the connection\r\n') gevent.spawn(self.recv, address) def recv(self, address): socket = self.sockets[address][0] queue = self.sockets[address][1] print 'Connection accepted %s:%d' % address try: for data in socket.recv(1024): queue.put(data) except: pass def murder(self): self.stop() for sock in self.sockets.iteritems(): print sock sock[1][0].shutdown(socket.SHUT_RDWR) sock[1][0].close() self.sockets = {} def run_server(): test_server = TestServer(('127.0.0.1', 10666)) test_server.start() return test_server
And my test is as follows:
def test_can_reconnect(self): test_server = run_server() client_config = {'host': '127.0.0.1', 'port': 10666} client = Connection('test client', client_config, get_config()) client.connect() assert client.socket_connected test_server.murder()
Cannot execute assert not client.socket_connected .
I detect "no data" during recv. If it is None, then I set some variables so that other code can decide whether to reconnect (do not reconnect if it was user_disconnect, etc.). This behavior has worked and always worked for me in the past, I just never tried to pass the test so far. Is there anything strange with socket connections and areas of local function or something else? it looks like the connection still exists even after the server stops.
The code I'm trying to verify is open: https://github.com/kyleterry/tenyks.git
If you run the tests, you will see the one I'm trying to fix.