Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a unittest for importing a module in Python

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.

like image 970
DrDee Avatar asked Mar 04 '10 17:03

DrDee


2 Answers

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.

like image 147
S.Lott Avatar answered Nov 02 '22 10:11

S.Lott


I don't see why you'd need to test this, but something like:

def my_import_test(self):
    import my_module

If an import error is raised the test has failed, if not it passes.

like image 44
Alex Gaynor Avatar answered Nov 02 '22 12:11

Alex Gaynor