doctest (python) 中的模拟 Y (from X import Y)
我正在尝试创建一个带有模拟功能的文档测试,该功能位于单独的模块中 并按以下方式导入
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!"
这失败了。
如果我将 import 更改为 import foomodule 并在任何地方使用 foomodule.foo 然后就可以了。
但是对于通过上述方式导入的模拟函数有什么解决方案吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您刚刚遇到了最好不要从“内部”模块导入对象的众多原因之一——仅导入模块本身(可能来自包内)。我们已将此规则纳入 Google 风格指南(发布于此处) 我衷心向每一位 Python 程序员推荐它。
话虽这么说,您需要做的就是获取刚刚用模拟替换的 foomodule.foo 并将其粘贴到当前模块中。我不记得足够多的 doctest 内部来确认是否
足够了——尝试一下,如果不起作用,那就做是
的,这是一团糟,但造成这种混乱的原因是看起来无辜的
from foomodule import foo
-- 避免这种情况,你的生活会更简单、更有效率;-)。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
will suffice for that -- give it a try, and if it doesn't work, do instead
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;-).最后发现这是MiniMock trunk版本的问题。
老稳定的表现符合预期。
Finally, found out that this was rather an issue of trunk version of MiniMock.
Old stable one performs as expected.