Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger ImportError to test Coverage of Fallback Code

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:

  1. code runs from test_somemod.py which has import somemod
  2. Mocking ImportError in Python covers some of this, but is complicated!
like image 641
Gregg Lind Avatar asked Sep 05 '25 20:09

Gregg Lind


1 Answers

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
like image 177
jterrace Avatar answered Sep 08 '25 11:09

jterrace