首页 > 解决方案 > 从一个文件中对多个文件进行 Doctest

问题描述

项目结构

components/
    A.py
    B.py

run_test.py

A.py每个都有B.py一些带有 doctest 测试用例的功能。

如何运行所有测试A.pyB.py仅运行run_test.py

任何其他实现“在 A.py 和 B.py 中运行所有测试”的方法也将受到赞赏。

标签: pythontestingdoctest

解决方案


应该更详细地阅读文档。

  1. 将此答案用于使用路径导入。
  2. 使用 doctest 文档中的示例运行测试
import doctest
import importlib.util

# from link

def import_module(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    foo = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(foo)
    return foo

if __name__ == "__main__":
    test_modules = [
        ("components.A", "components/A.py"),
        ("components.B", "components/B.py")
    ]
    
    for name, path in test_modules:
        doctest.testmod(import_module(name, path)) # from document
    

推荐阅读