1"""Basic http server for tests to simulate PyPI or custom indexes 2""" 3 4import time 5import threading 6 7from setuptools.extern.six.moves import BaseHTTPServer, SimpleHTTPServer 8 9 10class IndexServer(BaseHTTPServer.HTTPServer): 11 """Basic single-threaded http server simulating a package index 12 13 You can use this server in unittest like this:: 14 s = IndexServer() 15 s.start() 16 index_url = s.base_url() + 'mytestindex' 17 # do some test requests to the index 18 # The index files should be located in setuptools/tests/indexes 19 s.stop() 20 """ 21 22 def __init__(self, server_address=('', 0), 23 RequestHandlerClass=SimpleHTTPServer.SimpleHTTPRequestHandler): 24 BaseHTTPServer.HTTPServer.__init__(self, server_address, 25 RequestHandlerClass) 26 self._run = True 27 28 def start(self): 29 self.thread = threading.Thread(target=self.serve_forever) 30 self.thread.start() 31 32 def stop(self): 33 "Stop the server" 34 35 # Let the server finish the last request and wait for a new one. 36 time.sleep(0.1) 37 38 self.shutdown() 39 self.thread.join() 40 self.socket.close() 41 42 def base_url(self): 43 port = self.server_port 44 return 'http://127.0.0.1:%s/setuptools/tests/indexes/' % port 45 46 47class RequestRecorder(BaseHTTPServer.BaseHTTPRequestHandler): 48 def do_GET(self): 49 requests = vars(self.server).setdefault('requests', []) 50 requests.append(self) 51 self.send_response(200, 'OK') 52 53 54class MockServer(BaseHTTPServer.HTTPServer, threading.Thread): 55 """ 56 A simple HTTP Server that records the requests made to it. 57 """ 58 59 def __init__(self, server_address=('', 0), 60 RequestHandlerClass=RequestRecorder): 61 BaseHTTPServer.HTTPServer.__init__(self, server_address, 62 RequestHandlerClass) 63 threading.Thread.__init__(self) 64 self.setDaemon(True) 65 self.requests = [] 66 67 def run(self): 68 self.serve_forever() 69 70 @property 71 def url(self): 72 return 'http://localhost:%(server_port)s/' % vars(self) 73