How to write a unittest for importing a module in Python

django, python, unit-testing

Solution

As I have to deploy my Django application on a different server and it requires some extra modules I want to make sure that all required modules are installed.

This is not a unit test scenario at all.

This is a production readiness process and it isn't -- technically -- a test of your application.

It's a query about the environment. Ours includes dozens of things.

Start with a simple script like this. Add each thing you need to be sure exists.

try:
    import simplejson
except ImportError:
    print "***FAILURE: simplejson missing***"
    sys.exit( 2 )
sys.exit( 0 )

Just run this script in each environment as part of installation. It's not a unit test at all. It's a precondition for setup install.

Problem

What is the pythonic way of writing a unittest to see if a module is properly installed? By properly installed I mean, it does not raise an ImportError: No module named foo.

Original source