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

Python项目pytest无法导入模块但Python可运行代码的问题求助

问题:Python项目测试时出现ModuleNotFoundError: No module named 'dash_cass'

错误详情

ImportError while importing test module '/Users/kenny/Documents/GitHub/dash-cass/tests/test_routes/platform_test.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/homebrew/Cellar/python@3.10/3.10.5/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
test_routes/platform_test.py:3: in <module>
    from dash_cass.main import app
E   ModuleNotFoundError: No module named 'dash_cass'

项目代码结构

dash-cass
├── src
│   └── dash_cass
│       ├── database
│       │   ├── __init__.py
│       │   └── platform_component.py
│       ├── routes
│       │   ├── __init__.py
│       │   └── platform.py
│       ├── schemas
│       │   ├── __init__.py
│       │   ├── requestschemas.py
│       │   └── tableschemas.py
│       ├── __init__.py
│       ├── conftest.py
│       └── main.py
├── tests
│   ├── test_routes
│   │   ├── platform_test.py
│   │   └── __init__.py
│   └── __init__.py
├── pytest.ini
└── .env

已尝试的操作

  • 调整__init__.py文件
  • 执行python -m pytest tests/命令
  • 在tests目录下执行poetry run pytest
  • 在.env和conftest.py中添加路径

解决建议

  • 以可编辑模式安装项目:在项目根目录(dash-cass文件夹下)执行poetry add --editable .,让Poetry自动将src/dash_cass加入Python搜索路径,确保测试时能找到模块。
  • 配置pytest.ini路径:在pytest.ini中添加pythonpath = src,让pytest默认加载src目录,配置示例:
    [pytest]
    pythonpath = src
    
  • 在conftest.py中手动添加路径:如果上述方法无效,在tests/conftest.py中加入以下代码:
    import sys
    from pathlib import Path
    
    sys.path.append(str(Path(__file__).parent.parent / "src"))
    
  • 固定测试命令的执行目录:必须在项目根目录下运行测试,不要进入tests目录执行命令,正确命令为poetry run pytest tests/或python -m pytest tests/。
  • 检查Docker容器配置:在Docker中运行时,确保容器工作目录为项目根目录,src目录被正确挂载,同时在容器内执行poetry install和poetry add --editable .完成依赖和路径配置。

内容的提问来源于stack exchange,提问作者angeloandrea.isola

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:06:29