Commits

Robert Brewer committed 41f5dfb

New test_servers.py

Comments (0)

Files changed (6)

magicbus/plugins/servers.py

 protocols, etc.), you can manually register each one and then start them all
 with bus.start::
 
-    s1 = ServerAdapter(bus, MyWSGIServer(host='0.0.0.0', port=80))
-    s2 = ServerAdapter(bus, another.HTTPServer(host='127.0.0.1', SSL=True))
+    s1 = ServerPlugin(bus, MyWSGIServer(host='0.0.0.0', port=80))
+    s2 = ServerPlugin(bus, another.HTTPServer(host='127.0.0.1', SSL=True))
     s1.subscribe()
     s2.subscribe()
     bus.start()
 
 There are also Flup\ **F**\ CGIServer and Flup\ **S**\ CGIServer classes in
 :mod:`magicbus.plugins.servers`. To start an fcgi server, for example,
-wrap an instance of it in a ServerAdapter::
+wrap an instance of it in a ServerPlugin::
 
     addr = ('0.0.0.0', 4000)
     f = servers.FlupFCGIServer(application=mywsgiapp, bindAddress=addr)
-    s = servers.ServerAdapter(bus, httpserver=f, bind_addr=addr)
+    s = servers.ServerPlugin(bus, httpserver=f, bind_addr=addr)
     s.subscribe()
 
 Note that you need to download and install `flup <http://trac.saddi.com/flup>`_
 of the possible configuration options.
 """
 
+import socket
 import sys
+import threading
 import time
 
 
-class ServerAdapter(object):
-    """Adapter for an HTTP server.
+class ServerPlugin(object):
+    """Bus plugin for an HTTP server.
+    
+    You don't have to use this plugin; you can make your own that listens on
+    the appropriate bus channels. This one is designed to:
+
+        * wrap HTTP servers whose accept loop blocks by running it in a
+          separate thread; any exceptions in it exit the bus
+        * wait until the server is truly ready to receive requests before
+          returning from the bus.start listener
+        * wait until the server has finished processing requestss before
+          returning from the bus.stop listener
+        * log server start/stop via the bus
+
+    The httpserver argument MUST possess 'start' and 'stop' methods,
+    and a 'ready' boolean attribute which is True when the HTTP server
+    is ready to receive requests on its socket.
     
     If you need to start more than one HTTP server (to serve on multiple
     ports, or protocols, etc.), you can manually register each one and then
     start them all with bus.start:
     
-        s1 = ServerAdapter(bus, MyWSGIServer(host='0.0.0.0', port=80))
-        s2 = ServerAdapter(bus, another.HTTPServer(host='127.0.0.1', SSL=True))
+        s1 = ServerPlugin(bus, MyWSGIServer(host='0.0.0.0', port=80))
+        s2 = ServerPlugin(bus, another.HTTPServer(host='127.0.0.1', SSL=True))
         s1.subscribe()
         s2.subscribe()
         bus.start()
         if isinstance(self.bind_addr, tuple):
             wait_for_free_port(*self.bind_addr)
         
-        import threading
         t = threading.Thread(target=self._start_http_thread)
         t.setName("HTTPServer " + t.getName())
         t.start()
         self.start()
 
 
+
+# ------- Wrappers for various HTTP servers for use with ServerPlugin ------- #
+
+
 class FlupCGIServer(object):
     """Adapter for a flup.server.cgi.WSGIServer."""
    
     
     def __init__(self, *args, **kwargs):
         if kwargs.get('bindAddress', None) is None:
-            import socket
             if not hasattr(socket, 'fromfd'):
                 raise ValueError(
                     'Dynamic FCGI server not available on this platform. '
         self.scgiserver._threadPool.maxSpare = 0
 
 
+
+# ---------------------------- Utility functions ---------------------------- #
+
+
 def client_host(server_host):
     """Return the host on which a client can connect to the given listener."""
     if server_host == '0.0.0.0':
     host = client_host(host)
     port = int(port)
     
-    import socket
-    
     # AF_INET or AF_INET6 socket
     # Get the correct address family for our host (allows IPv6 addresses)
     try:

magicbus/test/__init__.py

 from subprocess import Popen
 import threading
 
+from magicbus.plugins import SimplePlugin
+
 
 def assertEqual(x, y, msg=None):
     if not x == y:
         # Sigh. Really, standard library, really? Double underscores?
         self._BaseServer__shutdown_request = True
 
+    def handle_error(self, request, client_address):
+        # Simulate unsafe servers that don't trap errors well
+        raise
+
 
 class WebService(object):
 
-    def __init__(self, bus, address=('127.0.0.1', 8000), handler_class=None):
-        self.bus = bus
+    def __init__(self, address=('127.0.0.1', 8000), handler_class=None):
         self.address = address
         self.handler_class = handler_class
         self.httpd = None
-        self.running = False
-
-    def subscribe(self):
-        self.bus.subscribe('start', self.start)
-        self.bus.subscribe('stop', self.stop)
+        self.ready = False
 
     def start(self):
         self.httpd = WebServer(self.address, self.handler_class)
-        threading.Thread(target=self.httpd.serve_forever).start()
-        self.running = True
-    # Make sure we start httpd after the daemonizer.
-    start.priority = 75
+        self.ready = True
+        self.httpd.serve_forever()
 
     def stop(self):
         if self.httpd is not None:
             self.httpd.stop()
-        self.running = False
-    stop.priority = 25
+        self.httpd = None
+        self.ready = False
 
     def do_GET(self, uri):
         conn = HTTPConnection(*self.address)
             conn.close()
 
 
+class WebAdapter(SimplePlugin):
+
+    def __init__(self, bus, service):
+        self.bus = bus
+        self.service = service
+
+    def start(self):
+        threading.Thread(target=self.service.start).start()
+    # Make sure we start httpd after the daemonizer.
+    start.priority = 75
+
+    def stop(self):
+        self.service.stop()
+    stop.priority = 25
+
+
 class WebHandler(HTTPHandler):
 
     def log_request(self, code="-", size="-"):
         self.bus.publish('acquire_thread')
         HTTPHandler.handle(self, *args, **kwargs)
 
-
-class Counter(object):
-
-    def __init__(self, bus):
-        self.bus = bus
-        self.running = False
-        self.startcount = 0
-        self.gracecount = 0
-        self.threads = {}
-
-    def subscribe(self):
-        self.bus.subscribe('start', self.start)
-        self.bus.subscribe('stop', self.stop)
-        self.bus.subscribe('graceful', self.graceful)
-        self.bus.subscribe('start_thread', self.startthread)
-        self.bus.subscribe('stop_thread', self.stopthread)
-
-    def start(self):
-        self.running = True
-        self.startcount += 1
-
-    def stop(self):
-        self.running = False
-
-    def graceful(self):
-        self.gracecount += 1
-
-    def startthread(self, thread_id):
-        self.threads[thread_id] = None
-
-    def stopthread(self, thread_id):
-        del self.threads[thread_id]
-

magicbus/test/test_opsys.py

 
 from magicbus import bus
 from magicbus.plugins import loggers, opsys
-from magicbus.test import assertEqual, Process, WebService, WebHandler
+from magicbus.test import assertEqual, Process, WebAdapter, WebService, WebHandler
 
 #loggers.StdoutLogger(bus).subscribe()
 pidfile = opsys.PIDFile(bus, os.path.join(thismodule + ".pid"))
             self.bus.exit()
         else:
             self.respond(status=404)
-service = WebService(bus, handler_class=Handler)
+service = WebService(handler_class=Handler)
 
 
 class TestOpsys(object):
     if mode == 'daemonize':
         opsys.Daemonizer(bus).subscribe()
     pidfile.subscribe()
-    service.subscribe()
+    WebAdapter(bus, service).subscribe()
     bus.start()
     bus.block()
 

magicbus/test/test_servers.py

+from magicbus import bus
+from magicbus.wspbus import ChannelFailures
+from magicbus.plugins import loggers, servers
+from magicbus.test import assertEqual, WebService, WebHandler
+
+#loggers.StdoutLogger(bus).subscribe()
+
+
+class Handler(WebHandler):
+
+    bus = bus
+
+    def do_GET(self):
+        if self.path == '/':
+            self.respond("Hello World")
+        elif self.path == '/ctrlc':
+            self.respond("okey-doke")
+            raise KeyboardInterrupt
+        elif self.path == '/exit':
+            self.respond("ok")
+            self.bus.exit()
+        else:
+            self.respond(status=404)
+service = WebService(handler_class=Handler)
+adapter = servers.ServerPlugin(bus, service, service.address)
+adapter.subscribe()
+
+
+class TestServers(object):
+
+    def test_keyboard_interrupt(self):
+        # Raise a keyboard interrupt in the HTTP server's main thread.
+        bus.start()
+        resp = service.do_GET("/ctrlc")
+        assertEqual(resp.status, 200)
+        bus.block()
+        assertEqual(bus.state, bus.states.EXITING)
+

magicbus/test/test_states.py

-from magicbus._compat import BadStatusLine, ntob
-import os
-import sys
-import threading
-import time
-
-from magicbus import bus
-thisdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
-
-
-class StateTests(object):
-
-    def test_2_KeyboardInterrupt(self):
-        # Raise a keyboard interrupt in the HTTP server's main thread.
-        # We must start the server in this, the main thread
-        bus.start()
-        cherrypy.server.start()
-
-        self.persistent = True
-        try:
-            # Make the first request and assert there's no "Connection: close".
-            self.getPage("/")
-            self.assertStatus('200 OK')
-            self.assertBody("Hello World")
-            self.assertNoHeader("Connection")
-
-            cherrypy.server.httpserver.interrupt = KeyboardInterrupt
-            bus.block()
-
-            self.assertEqual(db_connection.running, False)
-            self.assertEqual(len(db_connection.threads), 0)
-            self.assertEqual(bus.state, bus.states.EXITING)
-        finally:
-            self.persistent = False
-
-        # Raise a keyboard interrupt in a page handler; on multithreaded
-        # servers, this should occur in one of the worker threads.
-        # This should raise a BadStatusLine error, since the worker
-        # thread will just die without writing a response.
-        bus.start()
-        cherrypy.server.start()
-
-        try:
-            self.getPage("/ctrlc")
-        except BadStatusLine:
-            pass
-        else:
-            print(self.body)
-            self.fail("AssertionError: BadStatusLine not raised")
-
-        bus.block()
-        self.assertEqual(db_connection.running, False)
-        self.assertEqual(len(db_connection.threads), 0)
-
-    def test_5_Start_Error(self):
-        # If a process errors during start, it should stop the bus
-        # and exit with a non-zero exit code.
-        p = helper.CPProcess(ssl=(self.scheme.lower()=='https'),
-                             wait=True)
-        p.write_conf(
-                extra="""starterror: True
-test_case_name: "test_5_Start_Error"
-"""
-        )
-        p.start(imports='magicbus.test._test_states_demo')
-        if p.exit_code == 0:
-            self.fail("Process failed to return nonzero exit code.")
-
-
-class SignalHandlingTests(helper.CPWebCase):
-    def test_SIGHUP_tty(self):
-        # When not daemonized, SIGHUP should shut down the server.
-        try:
-            from signal import SIGHUP
-        except ImportError:
-            return self.skip("skipped (no SIGHUP) ")
-
-        # Spawn the process.
-        p = helper.CPProcess(ssl=(self.scheme.lower()=='https'))
-        p.write_conf(
-                extra='test_case_name: "test_SIGHUP_tty"')
-        p.start(imports='magicbus.test._test_states_demo')
-        # Send a SIGHUP
-        os.kill(p.get_pid(), SIGHUP)
-        # This might hang if things aren't working right, but meh.
-        p.join()
-
-    def test_SIGHUP_daemonized(self):
-        # When daemonized, SIGHUP should restart the server.
-        try:
-            from signal import SIGHUP
-        except ImportError:
-            return self.skip("skipped (no SIGHUP) ")
-
-        if os.name not in ['posix']:
-            return self.skip("skipped (not on posix) ")
-
-        # Spawn the process and wait, when this returns, the original process
-        # is finished.  If it daemonized properly, we should still be able
-        # to access pages.
-        p = helper.CPProcess(ssl=(self.scheme.lower()=='https'),
-                             wait=True, daemonize=True)
-        p.write_conf(
-             extra='test_case_name: "test_SIGHUP_daemonized"')
-        p.start(imports='magicbus.test._test_states_demo')
-
-        pid = p.get_pid()
-        try:
-            # Send a SIGHUP
-            os.kill(pid, SIGHUP)
-            # Give the server some time to restart
-            time.sleep(2)
-            self.getPage("/pid")
-            self.assertStatus(200)
-            new_pid = int(self.body)
-            self.assertNotEqual(new_pid, pid)
-        finally:
-            # Shut down the spawned process
-            self.getPage("/exit")
-        p.join()
-
-    def test_SIGTERM(self):
-        # SIGTERM should shut down the server whether daemonized or not.
-        try:
-            from signal import SIGTERM
-        except ImportError:
-            return self.skip("skipped (no SIGTERM) ")
-
-        try:
-            from os import kill
-        except ImportError:
-            return self.skip("skipped (no os.kill) ")
-
-        # Spawn a normal, undaemonized process.
-        p = helper.CPProcess(ssl=(self.scheme.lower()=='https'))
-        p.write_conf(
-                extra='test_case_name: "test_SIGTERM"')
-        p.start(imports='magicbus.test._test_states_demo')
-        # Send a SIGTERM
-        os.kill(p.get_pid(), SIGTERM)
-        # This might hang if things aren't working right, but meh.
-        p.join()
-
-        if os.name in ['posix']:
-            # Spawn a daemonized process and test again.
-            p = helper.CPProcess(ssl=(self.scheme.lower()=='https'),
-                                 wait=True, daemonize=True)
-            p.write_conf(
-                 extra='test_case_name: "test_SIGTERM_2"')
-            p.start(imports='magicbus.test._test_states_demo')
-            # Send a SIGTERM
-            os.kill(p.get_pid(), SIGTERM)
-            # This might hang if things aren't working right, but meh.
-            p.join()
-
-    def test_signal_handler_unsubscribe(self):
-        try:
-            from signal import SIGTERM
-        except ImportError:
-            return self.skip("skipped (no SIGTERM) ")
-
-        try:
-            from os import kill
-        except ImportError:
-            return self.skip("skipped (no os.kill) ")
-
-        # Spawn a normal, undaemonized process.
-        p = helper.CPProcess(ssl=(self.scheme.lower()=='https'))
-        p.write_conf(
-            extra="""unsubsig: True
-test_case_name: "test_signal_handler_unsubscribe"
-""")
-        p.start(imports='magicbus.test._test_states_demo')
-        # Send a SIGTERM
-        os.kill(p.get_pid(), SIGTERM)
-        # This might hang if things aren't working right, but meh.
-        p.join()
-
-        # Assert the old handler ran.
-        target_line = open(p.error_log, 'rb').readlines()[-10]
-        if not ntob("I am an old SIGTERM handler.") in target_line:
-            self.fail("Old SIGTERM handler did not run.\n%r" % target_line)
-

magicbus/test/test_tasks.py

 from magicbus._compat import ntob
 from magicbus import bus
 from magicbus.plugins import tasks
-from magicbus.test import assertEqual, Counter, WebService, WebHandler
+from magicbus.test import assertEqual, WebAdapter, WebService, WebHandler
 
 
 class Handler(WebHandler):
     def test_thread_manager(self):
         bus.clear()
 
-        service = WebService(bus, handler_class=Handler)
-        service.subscribe()
+        service = WebService(handler_class=Handler)
+        WebAdapter(bus, service).subscribe()
 
         tm = tasks.ThreadManager(bus)
         tm.subscribe()
         bus.start()
         try:
             assertEqual(bus.state, bus.states.STARTED)
-            assertEqual(service.running, True)
+            assertEqual(service.ready, True)
             assertEqual(len(tm.threads), 0)
 
             assertEqual(service.do_GET("/").read(), ntob("Hello World"))