You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pytest --doctest-modules运行单个docstring测试?

pytest指定运行单个doctest用例的方法

pytest --doctest-modules执行docstring测试时,同样支持节点选择语法指定单个用例,但doctest的节点命名规则和普通Python测试用例不同,直接使用mymodule.py::MyClass.foo的写法无法匹配到目标用例,需要在对象路径前增加doctest-前缀标识。

标准节点写法

针对提供的mymodule.py示例,不同位置的doctest对应运行命令如下:

  • 运行MyClass.foo方法内的docstring测试:
    pytest --doctest-modules mymodule.py::doctest-mymodule.MyClass.foo
  • 运行MyClass类本身的docstring测试:
    pytest --doctest-modules mymodule.py::doctest-mymodule.MyClass
  • 运行模块顶层的docstring测试:
    pytest --doctest-modules mymodule.py::doctest-mymodule

快速获取准确节点ID

如果记不住命名规则,可以先执行用例收集命令,pytest会列出所有识别到的doctest用例标识,直接拼接使用即可:
pytest --doctest-modules mymodule.py --collect-only
针对示例代码执行上述命令,会输出如下收集结果:

collected 2 items
<Module mymodule.py>
  <DoctestItem mymodule.MyClass>
  <DoctestItem mymodule.MyClass.foo>

在文件名后拼接::doctest-加上输出中DoctestItem对应的路径,就能精准选中单个doctest用例。

简易筛选方案

不想输入完整节点ID时,也可以用-k参数按关键字模糊匹配筛选用例,比如要运行foo方法的doctest,可以执行:
pytest --doctest-modules mymodule.py -k "MyClass.foo"
注意该方式为模糊匹配,存在同名路径用例时会选中多个目标,适合临时快速筛选场景。


内容的提问来源于stack exchange,提问作者Matthew Flamm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 15:27:22