Flask pytest 无法找到模块

问题描述 投票:0回答:1

我已经浏览了过去有关 Flask 导入问题的帖子,但我正在努力在我的特定案例中实施它们。本质上,

pytest
无法识别我在路由文件甚至我的
main.py

中所做的任何相对导入

这是我的文件结构

backend 
  | src / routes / budget_routes.py
  | src / routes / __init__.py

  | src / database.py
  | src / __init__.py
  | src / main.py

  | tests / test_budget_routes.py

最初我的测试都通过了占位符测试,并且

budget_routes.py
文件中没有额外的文件导入

budget_routes.py
sys.path
现在已被注释掉,并且测试通过)


import sys, os
from flask import Blueprint, jsonify, request
import sqlite3

# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'database')))
# from database import get_db


budget_routes = Blueprint('budget_routes', __name__)

@budget_routes.route('/get_budgets')
def get_budgets():
    return jsonify({'message': 'This is a placeholder response for get_budgets'})

test_budget_routes.py

import pytest
from src.main import app

@pytest.fixture
def client():
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

def test_get_budgets(client):
    response = client.get('/get_budgets')
    assert response.status_code == 200
    assert b'This is a placeholder response for get_budgets' in response.data

但是,当我取消注释

sys.path
等以尝试将数据库拉入budget_routes.py 文件时,测试会抛出此错误

============================= ERRORS =============================
__________ ERROR collecting tests/test_budget_routes.py __________
ImportError while importing test module '/Users/sidraiqbal/flask_expense_apr24/backend/tests/test_budget_routes.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_budget_routes.py:2: in <module>
    from src.main import app
src/main.py:2: in <module>
    from src.routes.budget_routes import budget_routes
src/routes/budget_routes.py:6: in <module>
    from database import get_db
E   ModuleNotFoundError: No module named 'database'

这也是我的

main.py
供参考

from flask import Flask
from src.routes.budget_routes import budget_routes
from src.database import get_db

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['DATABASE'] = 'budget.db'

# Create SQLite database and table
def create_table():
    with app.app_context():
        db = get_db()
        c = db.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS budget
                    (id INTEGER PRIMARY KEY AUTOINCREMENT,
                    category TEXT,
                    amount REAL,
                    date DATETIME NOT NULL DEFAULT(datetime('now'))
                    )''')
        db.commit()

def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

# Route for homepage
@app.route('/')
def home():
    return "<p>Hello</p>"

app.register_blueprint(budget_routes)

if __name__ == '__main__':
    create_table()  # Create the table when the app starts
    app.run()
  • 我期待 Pytest 找到我的数据库模块
  • 我尝试使用 .. 符号调整数据库导入,因为我在某处看到了这一点,但它没有帮助
  • 我还尝试查看问题是否出在通过
    main.py
    而不是仅
    from src.routes.budget_routes
    导入路线的
    from routes.budget_routes
    文件上,但是当我删除
    src
    时,它会失败,无法找到路线文件夹。老实说,我也很困惑为什么它要与附加的
    src.
    一起使用,因为我认为它需要从 src 移出并进入路由,但我是 Flask 的新手
python flask import pytest
1个回答
0
投票

from database import get_db
假设
database
routes.budget_routes
处于同一水平。我认为情况并非如此。我想如果你使用
from src.database import get_db
应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.