Given code like this in somemod.py:
try:
Import cStringIO as StringIO
except ImportError:
import StringIO
How can one test the ‘fallback’ branch?
(Use case: trying to achieve 100% coverage. Agreed that this is a bit of a silly goal 🙂 )
Complications:
- code runs from
test_somemod.pywhich hasimport somemod - Mocking ImportError in Python covers some of this, but is complicated!
First, create a function to use for testing:
Now, as explained here, you can hook in to the import function:
After the test case, you should set it back: