Search code examples
python-3.xpyqt5python-unittestqdesktopservices

How can I write unit tests against code that uses QDesktopServices openUrl?


I'm working on a python (3.5) program that use a PyQt5 GUI. In the GUI, I need to add some help links to the documentation on a website. I manage to make it work with:

QDesktopServices.openUrl(QUrl("my_url"))

It works fine but I want to be sure that it will always be the case.

A quick and dirty unittest is to call the function and simply notice that there is no error. I would like to make a test that will check that the correct website page did show up. What should I use?


Solution

  • Checking for an error is not going to work at all, because Qt itself never raises errors (of course, Python or PyQt might do, but for completely unrelated reasons). The best you can do is check the return value of openUrl, which will simply return True or False depending on whether it was "successful". But note the following from the Qt docs for openUrl:

    Warning: A return value of true indicates that the application has successfully requested the operating system to open the URL in an external application. The external application may still fail to launch or fail to open the requested URL. This result will not be reported back to the application.

    If you want more control, I suggest you use Python's webbrowser module instead. This would, for example, allow you to register your own mock-browser class for the purposes of testing. The webbrowser module is written in pure Python and the code is quite straightforward.