[PyQt] Unit testing PyQt applications

Andreas Pakulat apaku at gmx.de
Wed Mar 7 17:13:40 GMT 2012

On 07.03.12 15:42:34, Mads Ipsen wrote:
> OK, I agree, the snippets I provided were not nice, and I apologize
> for that.
> But suppose that the constructor in your class starts a thread that
> generates say an icon for a QStandardItem. Then you want to make
> sure that the thread has finished before you test that the icon has
> been created.
> * What would be the proper way of unit testing this?

I'd try to put in some moc-objects and split the testing. So one
unit-test would just test the loading of the icon from whatever source
it comes, without a thread in a blocking way.

Another unit-test would put in a moc-object that immediately returns the
icon so you can be sure that the amount of time the thread needs to run
is relatively small. Then in the unit-test, create the widget and then
let the main thread sleep for a bit so the background thread finishes.
Afterwards verify the moc-icon is properly retrieved. You don't need an
event loop here yet, unless you want the widget to be actually drawn.

> * How should starting/stopping the event loop be handled?

Hmm, the Qt unit-test framework works by starting the event-loop and
triggering the unit-test functions via a timer. I guess this could also
be done in python with the unittest framework somehow.

Personally I'd probably avoid testing the actual event-loop-requiring
bits of the application via unit-tests completely. Instead I'd go for a
gui-test-tool to test those parts and use unit-tests for all the
business-logic and non-gui stuff.


More information about the PyQt mailing list