使用Pytest时遇ModuleNotFoundError:找不到'application'模块求助
解决Pytest导入Flask应用时的ModuleNotFoundError问题
一、修复模块路径问题
出现ModuleNotFoundError: No module named 'application'的核心原因是Python无法识别application模块的所在路径,可通过以下方式解决:
1. 从项目根目录运行pytest
假设你的项目结构为:
项目根目录/ ├── application/ │ ├── __init__.py │ └── ... ├── tests/ │ └── 你的测试文件.py └── wsgi.py
直接在项目根目录下执行命令:
pytest tests/
这样Python会自动将当前目录(项目根)加入模块搜索路径,就能找到application模块。
2. 在测试文件中手动添加路径
如果习惯在其他目录运行pytest,可在测试文件开头添加代码,手动将项目根目录加入Python搜索路径:
import sys from pathlib import Path # 假设测试文件在tests目录下,上级目录就是项目根 sys.path.append(str(Path(__file__).parent.parent))
3. 设置PYTHONPATH环境变量
先配置环境变量再运行pytest:
# Linux/macOS export PYTHONPATH=/你的项目根目录绝对路径 pytest # Windows(PowerShell) $env:PYTHONPATH="你的项目根目录绝对路径" pytest
二、修复Flask应用的导入与初始化逻辑
除了路径问题,你的代码还有两处需要调整:
1. 完善application/init.py中的init_app函数
当前init_app函数未返回app实例,也未初始化Flask扩展,修改如下:
from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_bcrypt import Bcrypt from flask_jwt_extended import JWTManager from flask_migrate import Migrate from flask_mail import Mail from flask_cors import CORS # 全局扩展实例 db = SQLAlchemy() ma = Marshmallow() bcrypt = Bcrypt() jwt = JWTManager() # 变量名避免与类名重复 migrate = Migrate() mail = Mail() cors = CORS() def init_app(): app = Flask(__name__, instance_relative_config=False) app.config.from_object(Config) # 初始化所有扩展 db.init_app(app) ma.init_app(app) bcrypt.init_app(app) jwt.init_app(app) migrate.init_app(app, db) mail.init_app(app) cors.init_app(app) # 注册蓝图(如果有) # from application.views import assets_bp # app.register_blueprint(assets_bp) return app # 必须返回app实例
2. 调整测试文件的导入逻辑
application模块没有直接暴露app变量,需通过init_app函数创建实例,修改测试文件如下:
import pytest from application import init_app @pytest.fixture def app(): app = init_app() # 配置测试环境参数 app.config.update({ "TESTING": True, # 可选:使用内存数据库作为测试库 # "SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:" }) yield app @pytest.fixture def client(app): return app.test_client() def test_get_assets(client): response = client.get('/assets/get') assert response.status_code == 200
内容的提问来源于stack exchange,提问作者Graham Patrick
相关产品推荐
相关产品推荐

