"""Setup sqlite database which is used in testing env.""" import sys from reporting import config from reporting.connectors.mysql import db_session def _exit_if_not_test_environment(session): """For safety, only run tests in test environment pointed to sqlite. Exit immediately if not in test environment or not pointed to sqlite. """ if config.ENVIRONMENT != config.TEST_ENVIRONMENT: sys.exit( 'Environment must be set to {}.'.format(config.TEST_ENVIRONMENT) ) if 'sqlite' not in session.bind.url.drivername: sys.exit('Tests must point to sqlite database.') def populate_table(table_name, rows): """Add rows to a table.""" with db_session() as session: _exit_if_not_test_environment(session) for row in rows: columns = ', '.join(row.keys()) values = ', '.join([':%s' % key for key in row.keys()]) statement = 'INSERT INTO {} ( {} ) VALUES ( {} );'.format( table_name, columns, values ) session.execute(statement, row) def drop_report_preset_table(): """DROP report_preset table.""" DROP_TABLE_REPORT_PRESET = """ DROP TABLE IF EXISTS report_preset """ with db_session() as session: _exit_if_not_test_environment(session) session.execute(DROP_TABLE_REPORT_PRESET) def create_report_preset_table(): """CREATE report_preset table.""" CREATE_TABLE_REPORT_PRESET = """ CREATE TABLE report_preset ( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255) NOT NULL, report_id VARCHAR(255) NOT NULL, params TEXT NOT NULL, account_type VARCHAR(255) NOT NULL, account_id INT(10) NOT NULL, user_id VARCHAR(255) NOT NULL, datetime_created datetime NOT NULL, is_deleted TINYINT(1) NOT NULL DEFAULT '0' ); """ with db_session() as session: _exit_if_not_test_environment(session) drop_report_preset_table() session.execute(CREATE_TABLE_REPORT_PRESET)