4

I have a Flask app created with an app factory. When testing with pytest, I want to use an in-memory sqlite database because it is much faster than using temporary files. I'm using Flask-Migrate to integrate Alembic and Flask-SQLAlchemy. Flask-Migrate uses command line commands to manage the database. How can I run migrations to set up the database from within my test code?

config.py:

class DefaultConfig(object):
    DEBUG = True
    TESTING = True

    CSRF_ENABLED = True
    SECRET_KEY = 'this-really-needs-to-change'

    SQLALCHEMY_DATABASE_URI = 'sqlite://'

__init__.py:

db = SQLAlchemy()
socketio = SocketIO()
migrate = Migrate()

def create_app(config=None):
    app = Flask(__name__)

    if config is not None:
        config_path = os.path.abspath(config)
        app.config.from_pyfile(config_path)

    elif os.path.isfile(os.path.abspath(CONFIGFILE)):
        app.config.from_pyfile(os.path.abspath(CONFIGFILE))

    else:
        app.config.from_object(DefaultConfig)

    db.init_app(app)
    socketio.init_app(app)
    migrate.init_app(app, db)

    return app

fixtures.py:

from flask.ext.migrate import upgrade

from . import create_app, db
from .models import User


class AppFixture(object):
    def __init__(self):
        self.app = create_app()
        self.db = db
        with self.app.app_context():
            upgrade()
            self.users = User.query.all()

Calling upgrade() above doesn't work, I get OperationalError: (sqlite3.OperationalError) no such table: user [SQL: u'SELECT... at the Users.query line afterwards.

davidism
  • 121,510
  • 29
  • 395
  • 339
user178921
  • 64
  • 8
  • Not enough rep to leave a comment, so I'm writing this as an answer: there seems to be an [issue](https://github.com/miguelgrinberg/Flask-Migrate/issues/153) with using `flask upgrade` in SQLLite in-memory DBs. – mcouthon Apr 24 '17 at 08:38

0 Answers0