我可以修改doctest来测试sphinx文档中的bash吗



我最初的问题是"我可以测试bash吗;?

我发现了一些类似的问题,答案基本上是:

  1. 使用subprocess
  2. 使用其他模块(docshtest是我能找到的最好的模块(

我想换一种方法。是否可以修补doctest?我自己更改了代码以运行shell而不是python。这是我的区别:

1329,1330c1329
<                 exec(compile(example.source, filename, "single",
<                              compileflags, 1), test.globs)
---
>                 import subprocess; proc = subprocess.run(example.source, shell=True, stdout=subprocess.PIPE)
1339c1338
<             got = self._fakeout.getvalue()  # the actual output
---
>             got = proc.stdout.decode()  # the actual output

这显然不理想,但它完成了任务:


运行示例:

(venv) docs$ make doctest
Running Sphinx v4.4.0
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [doctest]: targets for 1 source files that are out of date
updating environment: 0 added, 1 changed, 0 removed
reading sources... [100%] index
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
running tests...
Document: index
---------------
**********************************************************************
File "index.rst", line 3, in default
Failed example:
echo bla
Expected:
blu
Got:
bla
**********************************************************************
1 items had failures:
1 of   2 in default
2 tests in 1 items.
1 passed and 1 failed.
***Test Failed*** 1 failures.
Doctest summary
===============
2 tests
1 failure in tests
0 failures in setup code
0 failures in cleanup code
build finished with problems.
Makefile:20: recipe for target 'doctest' failed
make: *** [doctest] Error 1

这是在包含shell示例而不是python示例的index.rst上运行的:

.. doctest:: 
>>> echo bla
bla
>>> echo bla
blu

所以,我的问题是——我如何修补doctest以允许用户运行bash示例和python示例?

我需要写一个包装器模块来模拟doctest中的东西吗?或者我可以派生一些东西(这是一个官方的python库,所以我想不是(。

使用doctest提供的所有好东西,但以适合我(我认为还有其他人(的方式稍微调整一下它的机制,最好的方法是什么

我遇到了同样的问题,最终编写了一个sphinx扩展来为shell命令运行doctest。它使用doctest模块来比较输出,并支持省略号等功能来指示任意输出。语法紧跟sphinx.ext.doctest扩展(除了>>>$取代以指示命令(。

例如,以下内容将验证命令的输出。

.. shtest::
$ echo "hello world"
hello ...

安装说明和示例可在此处找到。

该扩展还添加了一个.. sh::指令,该指令可用于将shell命令的输出添加到文档中,例如自动添加到文档命令行接口中。以下示例将显示pytest帮助。

.. sh:: pytest -h

最新更新