使用pytest测试Flask应用时遭遇ModuleNotFoundError问题求助
Flask应用pytest测试报错:ModuleNotFoundError: No module named 'flask'
运行pytest tests/时触发如下导入错误,但flask --app main run可以正常启动应用:
ImportError while importing test module '****/tests/test_eventlist.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/homebrew/Cellar/python@3.10/3.10.6_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_eventlist.py:2: in <module> from app import create_app app/__init__.py:1: in <module> from flask import Flask E ModuleNotFoundError: No module named 'flask'
项目结构
- 根目录包含
app文件夹、tests文件夹与main.py文件 app文件夹下有__init__.py(用于创建Flask应用实例)tests文件夹下有test_eventlist.py测试文件
相关代码
test_eventlist.py
import pytest from app import create_app @pytest.fixture() def app(): app = create_app() app.config.update({ "TESTING": True, }) yield app @pytest.fixture() def client(app): return app.test_client() def test_eventlist_post(client): response = client.post("/", data={"filename": "sample1.txt", "from": "2000-01-01T17:25:49Z", "to": "2000-01-10T16:55:01Z"}) assert len(response) == 5
main.py
from flask import Flask from app import create_app app = create_app() if __name__ == '__main__': app.run(debug=True)
解决方案
1. 验证pytest使用的Python环境
- 执行
which pytest和which flask,检查两个命令是否指向同一个虚拟环境路径 - 若使用虚拟环境,确保先激活环境再运行pytest
- 改用
python -m pytest tests/命令执行测试,强制使用当前终端环境的Python解释器
2. 确认依赖安装状态
- 在当前环境中执行
pip list | grep -E "Flask|pytest",确认Flask和pytest已安装 - 若未安装,执行
pip install flask pytest完成依赖安装
3. 修复项目路径识别问题
- 确保在项目根目录下运行pytest命令
- 若路径仍有问题,可在
test_eventlist.py开头添加路径处理代码:import sys from pathlib import Path # 将项目根目录添加到Python路径 sys.path.append(str(Path(__file__).parent.parent))
内容的提问来源于stack exchange,提问作者Krishna Gaurav
相关产品推荐
相关产品推荐

