views:

68

answers:

2

I'm trying to create a doctest with mock of function that resides in a separate module and that is imported as bellow

from foomodule import foo

def bar():
    """
    >>> from minimock import mock
    >>> mock('foo', nsdicts=(bar.func_globals,), returns=5)
    >>> bar()
    Called foo()
    10
    """
    return foo() * 2


import doctest
doctest.testmod()

foomodule.py:

def foo():
    raise ValueError, "Don't call me during testing!"

This fails.

If I change import to import foomodule and use foomodule.foo everywhere Then it works.

But is there any solution for mocking function imported the way above?

+1  A: 

You've just met one of the many reasons that make it best to never import object from "within" modules -- only modules themselves (possibly from within packages). We've made this rule part of our style guidelines at Google (published here) and I heartily recommend it to every Python programmer.

That being said, what you need to do is to take the foomodule.foo that you've just replaced with a mock and stick it in the current module. I don't recall enough of doctest's internal to confirm whether

   >>> import foomodule
   >>> foo = foomodule.foo

will suffice for that -- give it a try, and if it doesn't work, do instead

   >>> import foomodule
   >>> import sys
   >>> sys.modules[__name__].foo = foomodule.foo

yeah, it's a mess, but the cause of that mess is that innocent-looking from foomodule import foo -- eschew that, and your life will be simpler and more productive;-).

Alex Martelli
Alex, thanks for your guidelines link. I'll definitely use in addition to standard PEPs.
Evgenyt
A: 

Finally, found out that this was rather an issue of trunk version of MiniMock. Old stable one performs as expected.

Evgenyt