如何模拟导入以阅读文档?

时间:2016-11-22 07:32:38

标签: python mocking read-the-docs

问题:

我一直在与Read the Docs作战。导入的模块与I / O交互,因此文档不包含任何文本。 但构建不会失败。

尝试解决方案:

我正在尝试在doc / conf.py中使用mockMagicMock,但它不起作用。

期望的解决方案

基本上,我想mock整个导入。因此,RTD 尝试运行任何代码。只需从DocStrings生成文档。

我只想要mock 所有模块的元素。 函数变量任何带有DocString的内容。

目前我必须在virtualenv中安装项目,以满足导入要求。如果没有必要,我想避免这种情况。现在......如果我不这样做,文档也不会包含任何文本。 同样,构建不会失败。

详细

example.py

"""Basic DocSting Comments"""
from external.module import *

foo = module()
foo.connect()
"""
I want this to show up in RTD.
"""

我的具体案例可以找到here

文档/ conf.py

from mock import MagicMock

MOCK_MODULES = ['external.module', 'eternal.module.module', 'external.module.module.connect']
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = MagicMock()

我尝试了十几种不同的东西,没有运气。使用mockMagicMock,在RTD中使用不同的advanced settings一切都没有运气。

丑陋的黑客:

我确实遇到过一个丑陋的黑客。但它违背了使用DocStrings的目的。第二次编写代码以便RTD可以捕获DocStings,也可以将其写在单独的文档中。

if __name__ == "__main__":
    this = foo.connect()
    """
    This is where the real DocStrings go.
    """
else:
    this = 'this is the connect'
    """
    This is where the RTD DocStrings would go
    """

我不想以两倍的代码结束,只是为了添加一些文档。

MySQL Connector / Python

我还想将它与MySQL Connector一起使用。由于RTD在遇到此软件包时也会中断。我无法使用requirements.txt修复它。

import mysql.connector as db

db_connection = db.connect(**my_config)
"""
Perhaps I want to include some details here.
"""

1 个答案:

答案 0 :(得分:0)

我在 this blog post 上找到的以下解决方案对我有用。我想模拟 open3d 并且我能够做到这一点:

from unittest import mock

# Mock open3d because it fails to build in readthedocs
MOCK_MODULES = ["open3d"]
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = mock.Mock()

请注意,您需要从 mock 导入 unittest,因为 unittest.mock 是从 Python 3.3 (source) 开始的内置模块。

如果你想模拟多个包,你可以这样做:

from unittest import mock

# Mock open3d because it fails to build in readthedocs
MOCK_MODULES = ["open3d", "numpy", "matplotlib", "matplotlib.pyplot"]
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = mock.Mock()