db.create_all 没有在 pytest-flask 中创建表

db.create_all not creating tables in pytest-flask

我正在为遇到此问题的任何人自行记录 db.create_all 的解决方案。希望它能对某人有所帮助。

以下是对我没有帮助的其他话题的列表:

我尝试在 conftest.py 中为 pytest 创建和销毁 db。 Alembic autogenerate 正在为我工​​作,但由于某种原因 db.create_all 不是。在 db.create_all 之前导入模型没有任何作用。在我的 __init__.pydb = SQLAlchemy() 之后也没有导入模型(我使用的是应用程序工厂模式)。我还使用了 Declarative Base,这可能是问题的一部分。

pytest 的每个 运行 都会导致以下错误:

ERROR tests/test_main.py::test_index - sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "rule" does not exist

解决方法是将Flask-SQLAlchemy挂在db对象上的create_all方法短路

我按照实际中的模式SQLA docs:

Base.metadata.create_all(engine)

所以在我的 conftest 设置和销毁中而不是 db.create_all()db.drop_all():

@pytest.fixture
def app():
    app = create_app(TestConfig)

    with app.app_context():
        from app.models import Access, Rule, Base
        Base.metadata.drop_all(db.engine)
        Base.metadata.create_all(db.engine)
        print("Creating all")
        main(app)

    yield app

    with app.app_context():
        db.session.remove()
        Base.metadata.drop_all(db.engine)
        print("Dropping all")

这解决了问题。测试现已通过,表已创建和销毁。