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.