Wednesday, 30 April 2008

Dear LazyWeb - How to write a unittest for when a Python module is unavailable?

I have a Python module (cinfony.pybel) which I am testing with the standard unittest module. One of the classes in the module has an optional dependency; if the Python Imaging Library (PIL) is available, a particular draw() method will work, otherwise it should raise an ImportError with a helpful message (I am simplifying the situation somewhat but this is the general problem).

I have two related questions:

(1) Should I place the "import Image" statement for PIL at the start of the draw() method, or at the start of the module (and catch the exception but set a flag)? Personally, I feel that its more Pythonic to keep all of the imports at the start of the module; that is, to be up-front about dependencies, optional or not.

(2) How can I test this code in a unittest? That is, how can I call this draw() method with PIL available, and a second time, without PIL available?