Python automatic testing: mocking an imported module?

Peter Otten __peter__ at web.de
Wed Mar 28 03:34:51 EDT 2007


Silfheed wrote:

> 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.  We want our tester.py to test the code for testee.py
> without changing the code for testee.py.  testee.py has a module in it
> that we want to mock in some tests and in others use the real module.
> 
> /foo.py:  (real module)
> class bar:
>    def __init__(self):
>         "I am real"
> 
> /foo_fake/foo.py: (fake module)
> class bar:
>    def ___init__(self):
>         "I am a banana"
> 
> /testee.py:
> import foo
> foo.bar()
> 
> /tester.py:
> from foo_fake import foo
>    foo.bar()    # prints I am a banana
>    testee.py  # also prints I am a banana
> import foo
>    foo.bar()   # prints I am real
>    testee.py # also prints I am real
> 
> 
> This isnt working as we would like, does anyone have any tips  on how
> to get something like this working?

You can put foo_fake.foo into sys.modules as foo:

import sys
from foo_fake import foo

assert "foo" not in sys.modules
sys.modules["foo"] = foo

foo.bar()    # prints I am a banana
import foo
foo.bar()    # prints I am a banana

Peter




More information about the Python-list mailing list