import socket, requests, threading, time g_host = 'localhost' g_post = 8000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((g_host, g_post)) s.listen(1) g_timeout_wait = 5 g_success = False def background_func(): global g_success for i in range(g_timeout_wait - 1): time.sleep(1) print i g_success = True background_thread = threading.Thread(target=background_func) background_thread.start() try: # change "https" to "http" and then it will succeed. requests.get('https://%s:%d'%(g_host, g_post), timeout=g_timeout_wait) except Exception as e: print e else: assert 0, 'expected exception' print 'g_success =', g_success