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

混江龙づ霸主 提交于 2019-12-22 10:59:49

问题


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:


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




回答2:


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



来源:https://stackoverflow.com/questions/2216828/mock-y-of-from-x-import-y-in-doctest-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!