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:
test_somemod.py
which has import somemod
First, create a function to use for testing:
>>> def somecode():
... try:
... import cStringIO as StringIO
... print 'got cStringIO'
... except ImportError:
... import StringIO
... print 'got StringIO'
>>> somecode()
got cStringIO
Now, as explained here, you can hook in to the import function:
>>> import __builtin__
>>> original_import = __builtin__.__import__
>>> def import_hook(name, *args, **kwargs):
... if name == 'cStringIO': raise ImportError('test case module import failure')
... else: return original_import(name, *args, **kwargs)
...
>>>
>>> __builtin__.__import__ = import_hook
>>> somecode()
got StringIO
After the test case, you should set it back:
>>> __builtin__.__import__ = original_import
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With