Mock Y of (from X import Y) to doctest (python)

I am trying to create a doctrine with a mock function that is in a separate module and which is imported as below

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

It fails.

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

But is there any solution for the bullying function imported above?

+3
python testing mocking doctest
source share
2 answers

Finally, it turned out that this was more of a problem with the backbone version of MiniMock. The old stable works as expected.

+2
source share

You just met one of the many reasons why it is better to never import an object from the modules "inside" - only the modules themselves (possibly from packages). We made this rule part of our style rules on Google (published here ), and I wholeheartedly recommend it to every Python programmer.

To say what you need to do is take foomodule.foo, which you just replaced with the layout and paste it into the current module. I don’t remember enough doctrine to confirm

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

enough for this - try, and if that doesn't work, do instead

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

Yes, this is a mess, but the reason for this mess is that looking innocently from foomodule import foo is to avoid it and your life will be simpler and more productive; -).

+4
source share

All Articles