从 python 中的单元测试中获取模块名称

问题描述 投票:0回答:1

使用 python unittest 时,有没有办法以编程方式从测试套件中获取测试模块名称?

Python

unittest.loader.TestLoader
有一个发现方法,可以返回所有测试模块,但我无法找到仅获取测试模块名称的方法。

我做了什么:

import TestLoader
suite = loader.discover('path/to/tests')
for test_suite in suite:
    print(test_suite.__module__)

这会导致:

unittest.suite
unittest.suite
unittest.suite
unittest.suite
python testing python-unittest
1个回答
0
投票

使用字典
sys.modules

您可以导入包

sys
并使用字典
sys.modules
,如以下代码所示。

文件

project/run_all.py

import sys
from unittest.loader import TestLoader

suite = TestLoader().discover('tests', pattern="test*.py")

for module_name in sys.modules.keys():
    if module_name.startswith("test"):
        print(module_name)

在我的示例中,我假设测试模块存储在文件夹

project/tests
中,而
run_all.py
存储在文件夹
project
中。

争论
pattern

我假设我的所有测试文件都以

test
作为前缀名称。这是因为字典
sys.modules
包含了脚本
run_all.py
可用的所有模块名称,因此建立前缀可以避免选择不是测试文件的文件。

© www.soinside.com 2019 - 2024. All rights reserved.