changeset 46:5a89eb717987

add a test server for easy_install testing
author Jeff Hammel <jhammel@mozilla.com>
date Thu, 01 Mar 2012 13:36:38 -0800
parents 909f577d2abb
children cb24b5265557
files tests/testserver.py
diffstat 1 files changed, 44 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/testserver.py	Thu Mar 01 13:36:38 2012 -0800
@@ -0,0 +1,44 @@
+import threading
+from wsgiref.simple_server import make_server
+
+class TestWSGIServer(object):
+    """threaded WSGI server for in process testing"""
+
+    def __init__(self, app, host, port):
+        self.app = app
+        self.host = host
+        self.port = int(port)
+        self.httpd = None
+
+    def start(self):
+        self.httpd = make_server(self.host, self.port, self.app)
+        self.server = threading.Thread(target=self.httpd.serve_forever)
+        self.server.setDaemon(True) # don't hang on exit
+        self.server.start()
+
+    def stop(self):
+        if self.httpd:
+            ### FIXME: There is no shutdown() method in Python 2.4...
+            try:
+                self.httpd.shutdown()
+            except AttributeError:
+                pass
+        self.httpd = None
+
+    __del__ = stop
+
+if __name__ == '__main__':
+    def app(environ, start_response):
+        content = 'Hello world!'
+        status = '200 OK'
+        headers = [('Content-Type', 'text/plain'),
+                   ('Content-Length', str(len(content)))]
+        start_response(status, headers)
+        return [content]
+    port = 8080
+    server = TestWSGIServer(app, 'localhost', port)
+    server.start()
+    f = urllib2.urlopen('http://localhost:%d/' % port)
+    response = f.read()
+    assert response == 'Hello world!'
+    server.stop()