Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 616
Evgenyt Avatar asked Dec 01 '25 21:12

Evgenyt


1 Answers

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;-).

like image 137
Alex Martelli Avatar answered Dec 04 '25 10:12

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!