开发者

How to write a unittest for importing a module in Python

开发者 https://www.devze.com 2022-12-22 02:46 出处:网络
What is the pythonic way of writing a unittest to see if a module is prop开发者_JS百科erly installed? By properly installed I mean, it does not raise an ImportError: No module named foo.

What is the pythonic way of writing a unittest to see if a module is prop开发者_JS百科erly installed? By properly installed I mean, it does not raise an ImportError: No module named foo.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号