flask-sqlalchemy-lite icon indicating copy to clipboard operation
flask-sqlalchemy-lite copied to clipboard

Workflow question related to tests

Open thomthom opened this issue 11 months ago • 1 comments

I have setup my app with:

  • flask-sqlalchemy-lite
  • flask-alembic

I have setup flask-alemic similar to: https://flask-sqlalchemy-lite.readthedocs.io/en/latest/alembic/

Then I'm trying to follow the testing article, but got stomped on the "Avoid Writing Data" section: https://flask-sqlalchemy-lite.readthedocs.io/en/latest/testing/#avoid-writing-data

I created a separate test database for testing that is separate from my local dev.

However, using the app fixture from "Avoid Writing Data" will lead to errors when running my tests because there are no tables in the test database. So for that workflow I assume that one is suppose to migrate the test database manually. But how does that workflow work?

And I'm a little confused to use the setup from "Use a Test Database" (that creates and drops the database) vs "Avoid Writing Data"?

If this is not the place for such questions, can anyone suggest an alternative?

thomthom avatar Jan 03 '25 18:01 thomthom

I tried by calling alembic.upgrade() in conftest.py - which does seem to run the migration using the test-config.

However, the tests still leave data in the database. Not sure what I'm missing here...

    app = create_app(config)

    # https://flask-login.readthedocs.io/en/latest/#automated-testing
    app.test_client_class = FlaskLoginClient

    with app.app_context():
        alembic.upgrade()
        engines = db.engines

    cleanup = []

    for key, engine in engines.items():
        connection = engine.connect()
        transaction = connection.begin()
        engines[key] = connection
        cleanup.append((key, engine, connection, transaction))

    yield app

    for key, engine, connection, transaction in cleanup:
        transaction.rollback()
        connection.close()
        engines[key] = engine

thomthom avatar Jan 03 '25 18:01 thomthom

Update the docs with a more complete pattern in #26

davidism avatar Nov 01 '25 02:11 davidism

#32 adds a context manager to do this instead of needing to copy all that code from the docs. It will be part of 0.2.

davidism avatar Nov 06 '25 18:11 davidism