Flask-Builder
Toolkit to create and test flask apps
Use in tests (conftest.py):
from flask_builder import create_app, create_db, drop_db, create_tables, get_config_name, db
APP_NAME = 'serializer_tests'
@pytest.fixture(scope='module')
def app(request):
"""Session-wide test `Flask` application."""
# Create DB
config = import_string(get_config_name())
dsn = config.SQLALCHEMY_DATABASE_URI
dsn = dsn[:dsn.rfind('/')] + '/%s' % APP_NAME.lower() # Change DB-name
drop_db(dsn)
create_db(dsn)
# Create app
config['TESTING'] = True
config['SQLALCHEMY_DATABASE_URI'] = dsn
config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app = create_app(name=APP_NAME, config=config)
# Establish an application context before running the tests.
ctx = app.app_context()
ctx.push()
create_tables(app) # Only after context was pushed
# Add test client
app.client = app.test_client()
def teardown():
ctx.pop()
request.addfinalizer(teardown)
return app
Use in flask-application:
from flask_builder import create_app, create_db, create_tables, is_db_exists, parse_dsn, drop_db
app = create_app()
@app.route('/')
def func():
return 'hello!'
@app.cli.command()
def init():
"""Creates all tables, admin and so on if needed"""
dsn = app.config.get('SQLALCHEMY_DATABASE_URI')
if dsn:
if not is_db_exists(dsn):
create_db(dsn)
create_tables(app)
@app.cli.command()
def drop_all():
"""Drop and recreates all tables"""
dsn = app.config.get('SQLALCHEMY_DATABASE_URI')
if dsn and input('Do you want to DROP DATABASE:%s ?!' % dsn):
drop_db(dsn)
if __name__ == '__main__':
app.run()