【问题标题】:How to Mock Import for Read the Docs?如何模拟导入以阅读文档?
【发布时间】:2017-04-05 18:57:20
【问题描述】:

问题:

我一直在和Read the Docs打架。导入的模块与 I/O 交互,因此文档不包含任何文本。 但是构建并没有失败。

尝试的解决方案:

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

所需的解决方案

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

我只是想mock ALL 的元素为一个模块。 函数变量任何带有 DocString 的东西。

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

详情

example.py

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

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

我的具体案例可以在here找到。

docs/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()

我尝试了十几种不同的方法,但都没有成功。在 RTD 中使用 mockMagicMock,不同的 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 连接器/Python

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

import mysql.connector as db

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

【问题讨论】:

    标签: python mocking read-the-docs


    【解决方案1】:

    我在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()
    

    请注意,您需要从 unittest 导入 mock,因为 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多