Python自动化测试遇ModuleNotFoundError: No module named 'tests'求助
问题解决:ModuleNotFoundError及XML报告生成优化
一、排查ModuleNotFoundError问题
1. 验证PYTHONPATH设置
- 确保
projectpath是项目根目录的绝对路径,比如你的项目根目录为C:\Users\VellaSR\PycharmProjects\wics-selenium-scripts - 修正PYTHONPATH设置命令:Windows下不要给路径加引号(引号会被识别为路径的一部分),执行:
set PYTHONPATH=C:\Users\VellaSR\PycharmProjects\wics-selenium-scripts - 验证生效情况:执行
echo %PYTHONPATH%,输出应显示正确的根目录
2. 确认项目结构与__init__.py配置
项目需保持如下结构,每个文件夹下都要有空白的__init__.py文件:
wics-selenium-scripts/ ├── tests/ │ ├── __init__.py │ ├── common/ │ │ ├── __init__.py │ │ ├── WICSUtils.py │ │ └── GenericUtils.py │ └── icc/ │ ├── __init__.py │ ├── High/ │ │ ├── __init__.py │ │ └── ICC_R001_Inmate_Initial_Classification.py │ └── ICC_Common_Methods.py └── test-results/
3. 优化脚本运行方式
- 直接从项目根目录运行脚本,无需手动设置PYTHONPATH:
cd C:\Users\VellaSR\PycharmProjects\wics-selenium-scripts python tests/icc/High/ICC_R001_Inmate_Initial_Classification.py - 或者在脚本开头添加自动路径配置(推荐),彻底摆脱环境变量依赖:
这段代码要放在所有import语句之前。import sys import os # 将项目根目录加入Python路径 sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../')))
二、XML报告生成优化
1. 确保依赖安装
执行以下命令安装xmlrunner:
pip install xmlrunner
2. 修复报告路径问题
原代码使用相对路径易因运行位置不同报错,改为动态生成绝对路径:
if __name__ == '__main__': import os # 动态获取项目根目录下的test-results文件夹路径 result_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../test-results')) # 自动创建文件夹(不存在则新建) os.makedirs(result_dir, exist_ok=True) report_path = os.path.join(result_dir, 'ICC_R001_Inmate_Initial_Classification.xml') with open(report_path, 'wb') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False, buffer=False, catchbreak=False)
3. 代码补全提示
脚本中setUpClass方法调用了GenericUtils.get_new_driver_instance(),但当前仅导入了该模块的部分方法,需补充模块导入:
from tests.common import GenericUtils
内容的提问来源于stack exchange,提问作者saffin
相关产品推荐
相关产品推荐

