Python running glib mainloop in unittest

I am new to python and trying to set up a functional test environment. The test environment should receive DBus signals and evaluate them. The DBus signal uses GLib MainLoop. I have the following class encapsulating a loop:

class SignalLoop(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.__l = gobject.MainLoop() def run(self): self.__l.run() def quit(self): self.__l.quit() 

and in the module that executes DBus processing, I tried:

 class __ModuleInitializer: def __init__(self): print('Module was initialized') gobject.threads_init() sl = SignalLoop() sl.start() def __del__(self): print('Module was deinitialized') sl.quit() __module_init = __ModuleInitializer() 

I also tried the following:

  • setUp / tearDownModule () doesn't work for me - at least in python 2.5.2
  • __ init __ () and __del __ () and putting all the test windows in one class. __del __ () is never called, and this solution will not scale with a lot of test cases.

When I run the code, sl.qui () is never executed, and I don't know why. I have to kill my master when starting from the console, because it never returns. However, this is not a problem for the test runner PyDev.

Is there any hook that I can use to destroy the test environment? I want to be able to run one test and a couple of tests, so "hacking" it in the methods themselves is not an option.

Can you help me?

+4
source share
3 answers

I would not start and stop the main loop during setup and deletion methods. Instead, make your asynchronous request (or something else), then start the iteration of the main loop iterate until your result is reached.

Example:

 make_asynchronous_request() main_context = GLib.MainContext.default() while main_context.pending(): main_context.iteration(False) assert(result_is_ok()) 
+3
source

I used ptomato to create one that worked for me. The difference is probably related to some version of python. In my case, the code that works is:

 make_asynchronous_request() main_context = GLib.MainLoop.get_context() while main_context.pending(): main_context.iteration(False) assert(result_is_ok()) 
+2
source

I think you should define the SignalLoop class as a daemon stream. This will allow the program to close when it is done, even if the loop signal flow is still running. When the program closes, the __module_init object will be garbage collected and the __del__ function will be called.

Docs at daemon http://docs.python.org/2.6/library/threading.html#threading.Thread.daemon

0
source

All Articles