title: How to write a functional test for a DBUS service written in Python?
body: <p>(Title was: "How to write a unit test for a DBUS service written in Python?")</p>
  
  <p>I've started to write a DBUS service using dbus-python, but I'm having trouble writing a test case for it.</p>
  
  <p>Here is an example of the test I am trying to create. Notice that I have put a GLib event loop in the setUp(), this is where the problem hits:</p>
  
  <pre><code>import unittest
  
  import gobject
  import dbus
  import dbus.service
  import dbus.glib
  
  class MyDBUSService(dbus.service.Object):
      def __init__(self):
          bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus())
          dbus.service.Object.__init__(self, bus_name, '/test/helloservice')
  
      @dbus.service.method('test.helloservice')
      def hello(self):
          return "Hello World!"
  
  
  class BaseTestCase(unittest.TestCase):
  
      def setUp(self):
          myservice = MyDBUSService()
          loop = gobject.MainLoop()
          loop.run()
          # === Test blocks here ===
  
      def testHelloService(self):
          bus = dbus.SessionBus()
          helloservice = bus.get_object('test.helloservice', '/test/helloservice')
          hello = helloservice.get_dbus_method('hello', 'test.helloservice')
          assert hello() == "Hello World!"
  
  if __name__ == '__main__':
      unittest.main()
  </code></pre>
  
  <p>My problem is that the DBUS implementation requires you to start an event loop so that it can start dispatching events. The common approach is to use GLib's gobject.MainLoop().start() (although I'm not married to this approach, if someone has a better suggestion). If you don't start an event loop, the service still blocks, and you also cannot query it.</p>
  
  <p>If I start my service in the test, the event loop blocks the test from completing. I know the service is working because I can query the service externally using the qdbus tool, but I can't automate this inside the test that starts it.</p>
  
  <p>I'm considering doing some kind of process forking inside the test to handle this, but I was hoping someone might have a neater solution, or at least a good starting place for how I would write a test like this.</p>