def http_server(): httpd = HTTPServer(('127.0.0.1', 0), HTTPRequestHandler) httpd.base_url = 'http://{}:{}'.format(*httpd.server_address) thread = threading.Thread(target=httpd.serve_forever) thread.start() try: yield httpd finally: httpd.shutdown() thread.join()