本文介绍了使用Python Mock模拟功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python 模拟模块.

I am trying to Mock a function (that returns some external content) using the python mock module.

我在导入到模块中的模拟功能时遇到了麻烦.

I'm having some trouble mocking functions that are imported into a module.

例如,在util.py中,我有

def get_content():
  return "stuff"

我想模拟util.get_content,以便它返回其他内容.

I want to mock util.get_content so that it returns something else.

我正在尝试:

util.get_content=Mock(return_value="mocked stuff")

如果get_content在另一个模块中被调用,它实际上似乎从不返回模拟对象.我在使用Mock方面缺少一些东西吗?

If get_content gets invoked inside another module, it never actually seems to return the mocked object. Am I missing something in terms of how to use Mock?

请注意,如果我调用以下内容,则一切正常:

Note that if I invoke the following, things work correctly:

>>> util.get_content=Mock(return_value="mocked stuff")
>>> util.get_content()
"mocked stuff"

但是,如果从另一个模块内部调用get_content,它将调用原始函数而不是模拟版本:

However, if get_content is called from inside another module, it invokes the original function instead of the mocked version:

>>> from mymodule import MyObj
>>> util.get_content=Mock(return_value="mocked stuff")
>>> m=MyObj()
>>> m.func()
"stuff"

mymodule.py

from util import get_content

class MyObj:
    def func():
        get_content()

所以我想我的问题是-如何从我调用的模块内部调用函数的模拟版本?

So I guess my question is - how do I get invoke the Mocked version of a function from inside a module that I call?

from module import function似乎应该归咎于此,因为它没有指向Mocked函数.

It appears that the from module import function may be to blame here, in that it doesn't point to the Mocked function.

推荐答案

我认为我有一种解决方法,尽管对于如何解决一般情况尚不十分清楚

I think I have a workaround, though it's still not quite clear on how to solve the general case

mymodule中,如果我替换

from util import get_content

class MyObj:
    def func():
        get_content()

使用

import util

class MyObj:
    def func():
        util.get_content()

Mock似乎被调用.看起来名称空间需要匹配(这很有意义).但是,奇怪的是我希望

The Mock seems to get invoked. It looks like the namespaces need to match (which makes sense). However, the weird thing is that I would expect

import mymodule
mymodule.get_content = mock.Mock(return_value="mocked stuff")

在我使用from/import语法(现在将get_content拉入mymodule)的原始情况下,

可以解决问题.但这仍指未模拟的get_content.

to do the trick in the original case where I am using the from/import syntax (which now pulls in get_content into mymodule). But this still refers to the unmocked get_content.

证明名称空间很重要-编写代码时只需记住这一点.

Turns out the namespace matters - just need to keep that in mind when writing your code.

这篇关于使用Python Mock模拟功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:31