Python automatic testing: mocking an imported module?

Mark T nospam at nospam.com
Wed Mar 28 11:13:38 EDT 2007


"Silfheed" <silfheed at gmail.com> wrote in message 
news:1175033934.795913.292030 at l77g2000hsb.googlegroups.com...
> Heyas
>
> 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?
>

If you add the foo_fake directory to the front of sys.path, "import foo" 
will import the foo.py in foo_fake directory before the one in the local 
directory.

# unverified code
import sys
sys.path.append(0,'foo_fake') # add foo_fake to front of path
import foo
foo.bar()
execfile('testee.py')
sys.path.pop(0) # remove foo_fake
reload(foo)
foo.bar()
execfile('testee.py')

-Mark 




More information about the Python-list mailing list