(タイトルは「Python で書かれた DBUS サービスの単体テストの書き方」)
dbus-python を使用して DBUS サービスの作成を開始しましたが、テスト ケースの作成に問題があります。
これが私が作成しようとしているテストの例です。setUp() に GLib イベント ループを配置したことに注意してください。ここで問題が発生します。
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()
私の問題は、DBUS 実装では、イベントのディスパッチを開始できるようにイベント ループを開始する必要があることです。一般的なアプローチは、GLib の gobject.MainLoop().start() を使用することです (ただし、誰かがより良い提案を持っている場合、私はこのアプローチと結婚していません)。イベント ループを開始しないと、サービスは引き続きブロックされ、クエリも実行できません。
テストでサービスを開始すると、イベント ループによってテストの完了がブロックされます。qdbus ツールを使用して外部からサービスにクエリを実行できるため、サービスが機能していることはわかっていますが、サービスを開始するテスト内でこれを自動化することはできません。
これを処理するためにテスト内である種のプロセスフォークを行うことを検討していますが、誰かがよりきちんとした解決策を持っているか、少なくともこのようなテストを書くための良い出発点を持っていることを望んでいました.