import socketserver import urllib.request, urllib.error import threading import time import unittest HOST = "localhost" SLEEPTIME = 0.1 class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): self.request.recv(1024) time.sleep(SLEEPTIME) self.request.send(b"HTTP/1.0 Foo \n") self.request.close() class test_urllibi_except(unittest.TestCase): def test_timeout(self): with self.assertRaises(urllib.error.URLError): self._fetch_url("http://%s:%d/"%(HOST,PORT), timeout=SLEEPTIME/10) def test_badhost(self): with self.assertRaises(urllib.error.URLError): self._fetch_url("http://example.example/") def test_httperror(self): with self.assertRaises(urllib.error.URLError): self._fetch_url("http://%s:%d/"%(HOST,PORT)) @staticmethod def _fetch_url(url,timeout=SLEEPTIME*10): conn = urllib.request.urlopen(url,timeout=timeout) try: conn.read() finally: if conn: conn.close() if __name__=="__main__": server = socketserver.TCPServer((HOST, 0), MyTCPHandler) global PORT PORT = server.server_address[1] server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() unittest.main() server.shutdown()