Python automatic testing: mocking an imported module?

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


"Silfheed" <silfheed at gmail.com> writes:

> So we have the following situation: we have a testee.py 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 tester.py to test the code for testee.py
> without changing the code for testee.py.

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

> testee.py has a module in it

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

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

Excellent idea.


===== foo.py =====
class Bar(object):
    def __init__(self):
        self.name = "bar"
=====

===== dostuff.py =====
import foo

def get_bar():
    return foo.Bar()
=====

===== test_dostuff.py =====
import dostuff

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

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

def test_dostuff_get_bar_should_create_bar():
    """ The dostuff.get_bar function should create a new Bar """
    dostuff.foo = Mock_foo_module()
    test_bar = dostuff.get_bar()
    if not test_bar.name == "banana":
        raise AssertionError("test_bar.name 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
test.

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
expected.

-- 
 \         "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