Python automatic testing: mocking an imported module?

Ben Finney bignose+hates-spam at
Wed Mar 28 06:02:32 CEST 2007

"Silfheed" <silfheed at> writes:

> So we have the following situation: we have a that we want
> to automatically test out and verifiy that it is worthy of being
> deployed.

This is sometimes called the "module under test". I wish there was a
more succinct name in common usage.

> We want our to test the code for
> without changing the code for

This is called a "unit test" for the module.

> has a module in it

Looking at your example, *imports* a module; it doesn't
contain another one.

> that we want to mock in some tests and in othemodule.

Excellent idea.

===== =====
class Bar(object):
    def __init__(self): = "bar"

===== =====
import foo

def get_bar():
    return foo.Bar()

===== =====
import dostuff

class Mock_foo_module(object):
    """ Mock object for foo module """

    class Bar(object):
        def __init__(self):
   = "banana"

def test_dostuff_get_bar_should_create_bar():
    """ The dostuff.get_bar function should create a new Bar """ = Mock_foo_module()
    test_bar = dostuff.get_bar()
    if not == "banana":
        raise AssertionError(" should be banana")

This is simply using an instance of a class (Mock_foo_module) to be a
mock 'module' object. That mock module has the required 'Bar'
attribute, bound to a class; so the 'dostuff' module's 'foo' attribute
can be replaced with our mock module object for the purpose of the

The mock module's Bar class behaves in an idiomatic way (setting the
'name' attribute of its instance to a known value) that we use to
check whether the 'dostuff' module actually used our mock module.

This can be extended to mock any module interface you like, and then
confirm that the module under test has actually used the module as

 \         "A politician is an animal which can sit on a fence and yet |
  `\               keep both ears to the ground."  -- Henry L. Mencken |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list