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

如何用一条Python unittest命令运行两个项目的所有测试?

问题描述

我的项目结构如下:

├── compute_completeness_service
│   ├── __init__.py
│   ├── app.py
│   ├── tests
│   │   ├── integration
│   │   │   ├── __init__.py
│   │   │   └── test__init__.py
│   │   └── unit
│   │       ├── __init__.py
│   │       ├── __pycache__
│   │       └── test_utils.py
│   └── utils
│       ├── __init__.py
│       └── __pycache__
├── data_quality
│   ├── __init__.py
│   ├── app.py
│   ├── helpers
│   │   ├── __init__.py
│   └── tests
│       └── unit
│           ├── __init__.py
│           ├── __pycache__
│           └── test_helpers.py

我可以从项目根目录执行以下命令分别运行两个子项目的测试:

python3 -m unittest discover -v -s ./compute_completeness_service/tests  -p "test_*.py"
python3 -m unittest discover -v -s ./data_quality/tests  -p "test_*.py"

但我尝试用一条命令运行所有测试时,却没有检测到任何测试:

python3 -m unittest discover -v -t .  -p "test_*.py" 
----------------------------------------------------------------------
Ran 0 tests in 0.000s

请问有没有办法用一条命令运行所有测试?


解决方案

为什么原命令失败?

unittest discover默认从-s指定的起始目录(默认当前目录)递归查找测试文件,但你的测试文件都嵌套在两个子项目的tests目录下,根目录本身没有测试文件,且该命令不会自动识别所有名为tests的子目录作为测试根目录,因此直接在根目录执行无法找到测试用例。

方法1:合并两个discover命令(最直接)

将两个单独的测试命令用&&(执行成功则继续)或;(无论结果都继续)连接,即可一次性运行所有测试:

python3 -m unittest discover -v -s ./compute_completeness_service/tests -p "test_*.py" && python3 -m unittest discover -v -s ./data_quality/tests -p "test_*.py"

方法2:编写shell脚本(适合频繁使用)

在项目根目录创建run_all_tests.sh脚本,把测试命令整合进去:

#!/bin/bash
echo "=== 运行compute_completeness_service测试 ==="
python3 -m unittest discover -v -s ./compute_completeness_service/tests -p "test_*.py"
echo -e "\n=== 运行data_quality测试 ==="
python3 -m unittest discover -v -s ./data_quality/tests -p "test_*.py"

赋予脚本执行权限:

chmod +x run_all_tests.sh

之后只需运行脚本即可:

./run_all_tests.sh

方法3:用find命令批量定位测试文件

通过find命令自动筛选所有符合路径的测试文件,转换为Python模块格式后交给unittest运行:

python3 -m unittest $(find . -path "*/tests/*test_*.py" -type f | sed 's/\.\///; s/\.py$//' | tr '/' '.')

这个命令会自动遍历所有tests目录下的test_*.py文件,将文件路径转换为模块名(比如compute_completeness_service.tests.unit.test_utils),一次性完成所有测试的运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:10:33