Flask项目运行pytest时持续出现ModuleNotFoundError(找不到'app'模块)的问题求助
Flask项目运行pytest时持续出现ModuleNotFoundError(找不到'app'模块)的问题求助
大家好,我最近碰到一个卡了好久的问题,想请各位帮忙排查下。
我的Flask后端目录结构是这样的:
backend/ ├── app/ │ ├── __init__.py │ ├── routes/ │ │ ├── dev_routes.py │ │ └── ... │ └── models.py ├── tests/ │ ├── __init__.py │ └── routes/ │ └── test_dev_routes.py └── main.py |__ ...
我现在在终端的backend目录下,用命令pytest tests/routes尝试运行test_dev_routes.py,但一直弹出下面的错误:
_______ ERROR collecting tests/routes/test_dev_routes.py ________ ImportError while importing test module '/Users/name/folder/project-name/project/backend/tests/routes/test_dev_routes.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: ../../../../miniconda3/lib/python3.10/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/routes/test_dev_routes.py:3: in <module> from app.routes import dev_routes E ModuleNotFoundError: No module named 'app'
我的test_dev_routes.py代码如下:
import pytest from flask import Flask, json from app.routes import dev_routes from app import create_app, db from app.models import User, Doctor, Slot, Queue, QueueEntry @pytest.fixture def client(): app = Flask(__name__) app.register_blueprint(dev_routes.api, url_prefix='/api/dev') app.config['TESTING'] = True with app.test_client() as client: with app.app_context(): db.create_all() # Create the database tables yield client with app.app_context(): db.drop_all() # Clean up after tests
dev_routes.py里定义了api = Blueprint('dev_api', __name__),在app目录内的其他文件里引用这个变量是完全正常的。我试过把tests/routes文件夹移到app目录里,结果还是遇到同样的错误,实在搞不清哪里出问题了。
另外,我的app/__init__.py内容是这样的:
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS db = SQLAlchemy() _app_instance = None # Singleton instance def create_app(config_name: str = None): global _app_instance if _app_instance is None: _app_instance = Flask(__name__) _app_instance.config.from_object('config.Test') db.init_app(_app_instance) CORS(_app_instance) return _app_instance
我已经尝试过这些解决方法,但都没效果:
- 设置Python路径:
export PYTHONPATH=$(pwd)/backend - 把整个
tests文件夹移到app目录里 - 在
backend目录添加__init__.py,然后尝试用from backend.app.routes import dev_routes导入
备注:内容来源于stack exchange,提问作者football568
相关产品推荐
相关产品推荐

