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.

Advertisements

2 thoughts on “Skippng Python unit tests if a dependency is missing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s