如何测试Sphinx文档的有效性?

8 投票
1 回答
1430 浏览
提问于 2025-05-11 00:14

我有一堆关于我的Python包的文档,这些文档是用标准的Sphinx .rst文件写的。我还为我的包写了一些测试,其中我想加入一个测试,看看文档是否能正确编译成预期的输出。简单来说,我想抓住那些链接指向错误地方或者标题格式不对的情况。

我知道我可以写一个测试,去调用 make html 并检查返回的代码,但这样做感觉不太好,所以我在想一定有更好的方法。有人知道吗?

相关文章:

  • 暂无相关问题
暂无标签

1 个回答

4

你可以像为代码写单元测试一样,为你的文档创建单元测试。为了捕捉警告,你可以在Sphinx的配置中设置 warningiserror=True

from django.utils import unittest
from sphinx.application import Sphinx


class DocTest(unittest.TestCase):
    source_dir = u'docs/source'
    config_dir = u'docs/source'
    output_dir = u'docs/build'
    doctree_dir = u'docs/build/doctrees'
    all_files = 1

    def test_html_documentation(self):
        app = Sphinx(self.source_dir,
                     self.config_dir,
                     self.output_dir,
                     self.doctree_dir,
                     buildername='html',
                     warningiserror=True,
        )
        app.build(force_all=self.all_files)
        # TODO: additional checks here if needed

    def test_text_documentation(self):
        # The same, but with different buildername
        app = Sphinx(self.source_dir,
                     self.config_dir,
                     self.output_dir,
                     self.doctree_dir,
                     buildername='text',
                     warningiserror=True,
        )
        app.build(force_all=self.all_files)
        # TODO:  additional checks if needed

    def tearDown(self):
        # TODO: clean up the output directory
        pass

撰写回答