【问题标题】:Python MagicMock mocks too much when using decoratorPython MagicMock 在使用装饰器时模拟太多
【发布时间】:2018-08-31 12:18:32
【问题描述】:

我正在尝试通过 Sphinx 在 ReadTheDocs 安装上获取文档。我正在记录的类继承自一个更大的框架,我无法轻松安装,因此想模拟。然而,Mock 似乎过于贪婪地模拟我真正想要记录的类。有问题的代码如下:

# imports that need to be mocked
from big.framework import a_class_decorator, ..., SomeBaseClass


@a_class_decorator("foo", "bar")
class ToDocument(SomeBaseClass):
    """ Lots of nice documentation here

    which will never appear
    """

def a_function_that_is_being_documented():
    """ This will show up on RTD
    """

我达到了确保我不会盲目地嘲笑装饰器的地步,而是在我的 Sphinx conf.py 中明确表示。否则,我会按照 RTD 建议来模拟模块:

class MyMock(MagicMock):

    @classmethod
    def a_class_decorator(cls, classid, version):
        def real_decorator(theClass):                
             print(theClass)
             return theClass     
        return real_decorator

    @classmethod
    def __getattr__(cls, name):
        return MagicMock()

sys.modules['big.framework'] = MyMock()

现在我希望对于打印输出,我会得到一些关于我要记录的类的内容,例如<ToDocument ...>

但是,我也总是得到该类的 Mock,<MagicMock spec='str' id='139887652701072'>,当然它没有任何我正在尝试构建的文档。有什么想法吗?

【问题讨论】:

  • 我应该补充一点,模块中的所有顶级函数都已正确评估并记录在案。

标签: python mocking python-sphinx read-the-docs


【解决方案1】:

原来问题在于从模拟类继承。开始明确基类并创建一个空类

class SomeBaseClass:
    pass

conf.py 中打补丁解决了问题

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 2012-11-01
    • 2018-06-01
    • 2020-07-30
    • 2020-02-29
    • 2021-03-20
    • 2022-01-07
    • 2016-08-20
    • 1970-01-01
    相关资源
    最近更新 更多