FastAPI项目运行pytest出现ModuleNotFoundError: No module named 'main'
FastAPI项目pytest导入main.py报错问题
问题描述
在基础FastAPI项目中运行pytest时遭遇ModuleNotFoundError,测试文件test_rms.py位于tests目录下,尝试从tests目录外的main.py导入app,相关信息如下:
test_rms.py代码
from fastapi.testclient import TestClient from main import app client = TestClient(app) def test_root(): response = client.get("/test") assert response.status_code == 200 assert response.json() == {"message": "Hello World"}
项目文件夹结构

报错信息
___________________________________________________________________________________________________________________________________ ERROR collecting tests/test_rms.py ___________________________________________________________________________________________________________________________________ ImportError while importing test module 'C:\Scripting\Python\cct-api\tests\test_rms.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: C:\Users\azadmin\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests\test_rms.py:2: in <module> from main import app E ModuleNotFoundError: No module named 'main'
原因分析
报错核心是Python模块搜索路径限制:
- 运行pytest时,Python默认的模块搜索路径不包含项目根目录(
cct-api),仅会在tests目录及系统默认路径中查找模块。 test_rms.py位于tests子目录,直接执行from main import app时,Python找不到上层目录的main.py,因此抛出ModuleNotFoundError。
解决方案
需要调整导入方式或模块搜索路径来解决问题,以下是几种可行方案:
方案1:使用相对导入
修改test_rms.py的导入语句为相对路径,同时将tests目录转为Python包(添加空的__init__.py文件):
from fastapi.testclient import TestClient from ..main import app # 两个点表示向上一级目录索引 client = TestClient(app) def test_root(): response = client.get("/test") assert response.status_code == 200 assert response.json() == {"message": "Hello World"}
方案2:手动添加项目根目录到搜索路径
在test_rms.py开头添加代码,动态将项目根目录加入Python模块搜索路径:
import sys from pathlib import Path # 获取项目根目录路径并添加到搜索路径 sys.path.append(str(Path(__file__).parent.parent)) from fastapi.testclient import TestClient from main import app client = TestClient(app) def test_root(): response = client.get("/test") assert response.status_code == 200 assert response.json() == {"message": "Hello World"}
方案3:安装项目为可编辑包
在项目根目录(cct-api)下执行以下命令,将项目安装为可编辑模式:
pip install -e .
此操作会将项目根目录加入Python的site-packages路径,之后可直接使用from main import app而不会报错,这是Python项目测试的规范做法。
总结
确实需要调整from main import app这条导入逻辑(或通过其他方式扩展模块搜索路径),核心目标是让Python能够定位到项目根目录下的main.py文件。
内容的提问来源于stack exchange,提问作者configure.ng
相关产品推荐
相关产品推荐

