def empty_db_connection(): """ Connect to db, create tables and begin connection-level (outer) transaction. Will also create the database first if it does not exist. Maybe overkill, but a neat trick, cf: http://alextechrants.blogspot.co.uk/2013/08/unit-testing-sqlalchemy-apps.html We use a connection-level (non-ORM) transaction that encloses everything **including the table creation**. This ensures that the models and queries are always in sync for testing. Note that the transaction must be explicitly rolled back. An alternative approach would be to delete all tables, but presumably that would take slightly longer than a rollback (be interesting to check). """ # Could be parameterized, but then it wouldn't make sense as a session-level fixture # Unless PyTest is smart enough to maintain fixtures in parallel? # test_db_url = getattr(request.module, "test_db_url", testdb_empty_url) test_db_url = testdb_empty_url if not db_utils.check_database_exists(test_db_url): db_utils.create_empty_database(default_admin_db_url, test_db_url.database) engine = create_engine(test_db_url) connection = engine.connect() transaction = connection.begin() # Create tables (will be rolled back to clean) db_utils.create_tables_and_indexes(connection) # Return to test function yield connection # TearDown transaction.rollback() connection.close() engine.dispose()
def test_create_check_delete(self): # DB should be absent to start off with assert db_utils.check_database_exists(testdb_temp_url) == False # Now create it db_utils.create_empty_database(default_admin_db_url, testdb_temp_url.database) assert db_utils.check_database_exists(testdb_temp_url) == True # And delete it again db_utils.delete_database(default_admin_db_url, testdb_temp_url.database) assert db_utils.check_database_exists(testdb_temp_url) == False
def main(): args = handle_args() dburl = dbconfig.make_db_url(dbconfig.default_admin_db_params, args.dbname) if not db_utils.check_database_exists(dburl): db_utils.create_empty_database(dbconfig.default_admin_db_url, args.dbname) logger.info('Database "{}" created.'.format(dburl.database)) engine = create_engine(dburl) db_utils.create_tables_and_indexes(engine.connect()) return 0