Skippng Python unit tests if a dependency is missing

Update: this is a flawed method of skipping the tests, I’ve written up an improved version based on the feedback I received.

In all the examples of using python unittest to skip tests I’ve not seen anyone explaining how to skip tests if a library isn’t installed.

The simplest way to do it appears to be to simply try to import the relevant libraries and catch the exception thrown if the library isn’t there.

import unittest
try:
    import PyQt4.QtCore
    import PyQt4.QtGui
except:
    raise unittest.SkipTest("Need PyQt4 installed to do gui tests")

This example at the top of a test file simply skips all the tests if PyQt4 isn’t available.