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

如何使用Twisted Trial运行mathematics包中addition.py的doctests?

用Twisted Trial运行addition.py中的doctests

嘿,这个问题我熟!Twisted Trial完全支持运行模块里的doctests,针对你这种在mathematics包下addition.py里的场景,有几个实用的方法,给你一一拆解:

方法一:命令行直接指定模块运行

最简单的方式就是直接用Trial的--doctest参数指定你的模块,在终端里执行:

trial --doctest mathematics.addition

这个命令会让Trial自动扫描mathematics/addition.py里所有标准格式的doctest(就是那些以>>>开头的代码块)并运行它们。记得要确保mathematics包所在的目录在Python的搜索路径里——比如你可以直接在包的上层目录运行这个命令,或者已经把包安装到了Python的site-packages中。

方法二:集成到现有测试套件

如果你已经在用Trial运行其他测试,想把doctests和现有单元测试一起跑,可以在你的测试文件(比如tests/test_addition.py)里加一段代码,把doctests封装成Trial能识别的测试用例:

from twisted.trial import unittest
from twisted.python import modules
import mathematics.addition

class TestAdditionDoctests(unittest.TestCase):
    def test_addition_doctests(self):
        # 加载addition模块的doctests
        module = modules.getModule(mathematics.addition.__name__)
        doctest_suite = module.loadDoctests()
        # 运行这个doctest套件
        self.runTestCase(doctest_suite)

之后你运行trial mathematics.tests.test_addition的时候,就会同时执行你的常规单元测试和这些doctests了。

方法三:让模块自身支持Trial运行

如果你想直接运行addition.py就能执行doctests,同时让Trial命令也能识别到它,可以在addition.py的末尾加上这段代码:

if __name__ == '__main__':
    from twisted.trial import runner
    from twisted.python import modules
    current_module = modules.getModule(__name__)
    doctest_suite = current_module.loadDoctests()
    trial_runner = runner.TrialRunner()
    trial_runner.run(doctest_suite)

这样一来,你既可以用python mathematics/addition.py直接跑doctests,也能继续用trial mathematics.addition命令来执行它。

小提醒

  • 确保你的doctests是标准格式:代码块以>>>开头,预期结果紧跟在后面,符合Python doctest的规范。
  • 如果你的项目结构是嵌套的,记得让包的根目录在Python路径里,不然Trial可能找不到你的模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:55:20