Fast detection or simulation of WSAECONNREFUSED Fast detection or simulation of WSAECONNREFUSED windows windows

Fast detection or simulation of WSAECONNREFUSED


It's not exactly what you asked about. But if you need this in the unittests only, mock library would be useful.

import errnoimport socketimport timeimport mockPORT = 50123def connect_mock(*agrs):    raise socket.error(errno.WSAECONNREFUSED, "Testing")def main():    s = socket.socket()    s.bind(('127.0.0.1', PORT))    s.listen(0)    client = socket.socket()    client.connect(('127.0.0.1', PORT))    client2 = socket.socket()    start = time.time()    with mock.patch('socket.socket.connect', connect_mock):        try:            client2.connect(('127.0.0.1', PORT))            print "done"        except socket.error as e:            assert e.errno == errno.WSAECONNREFUSED            print 'connection attempt took', time.time() - start        finally:            client2.close()            client.close()            s.close()if __name__ == '__main__':    main()


Here is my solution based on dmitry-vakhrushev's answer which is patching the connect method more intelligent:

if sys.platform == 'win32':    n_calls = [0]    org_connect = socket.socket.connect    def refusing_connect(*args):        if n_calls[0] < 2:            n_calls[0] += 1            raise socket.error(errno.WSAECONNREFUSED, "Testing")        return org_connect(*args)    # patch socket.connect to speed up WSAECONNREFUSED detection    patcher = mock.patch('socket.socket.connect', refusing_connect)    patcher.start()    self.addCleanup(patcher.stop)