Python MagicMock在使用装饰器时嘲弄太多

问题描述 投票:0回答:1

我试图通过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 ...>

但是,我总是得到该类的模拟,<MagicMock spec='str' id='139887652701072'>,当然没有我想要构建的任何文档。有任何想法吗?

python mocking python-sphinx read-the-docs
1个回答
0
投票

原来问题是来自模拟类的继承。开始明确基类并创建一个空类

class SomeBaseClass:
    pass

conf.py补丁解决了这个问题

© www.soinside.com 2019 - 2024. All rights reserved.