I have an application that imports a module from PyPI.
I want to write unittests for that application's source code, but I do not want to use the module from PyPI in those tests.
I want to mock it entirely (the testing machine will not contain that PyPI module, so any import will fail).
Currently, each time I try to load the class I want to test in the unittests, I immediately get an import error. so I thought about maybe using
try:
except ImportError:
and catch that import error, then use command_module.run(). This seems pretty risky/ugly and I was wondering if there's another way.
Another idea was writing an adapter to wrap that PyPI module, but I'm still working on that.
If you know any way I can mock an entire python package, I would appreciate it very much. Thanks.
If you want to dig into the Python import system, I highly recommend David Beazley's talk.
As for your specific question, here is an example that tests a module when its dependency is missing.
bar.py- the module you want to test when my_bogus_module is missingmock_bogus.py- a file in with your tests that will load a mock moduletest_bar.py- testsbar.pywhenmy_bogus_moduleis not availableYou should probably make that a little safer by checking that
my_bogus_moduleisn't actually available when you run your test. You could also look at thepydoc.locate()method that will try to import something, and returnNoneif it fails. It seems to be a public method, but it isn't really documented.