"""Utility functions to support database interactions in tests.""" from functools import wraps import sys from backend import config from backend.connectors import mysql from backend.models.vendor import Vendor from tests.testutils.seed.vendor_seed import vendor_seed_data def create_tables(): """Create the vendor and related tables.""" with mysql.db_session() as session: exit_if_not_test_environment(session) mysql.BaseModel.metadata.create_all(mysql.db_engine) def seed_tables(): """Seed the vendor and related tables.""" with mysql.db_session() as session: exit_if_not_test_environment(session) session.bulk_insert_mappings(Vendor, vendor_seed_data) def drop_tables(): """Drop vendor and related tables.""" with mysql.db_session() as session: exit_if_not_test_environment(session) mysql.BaseModel.metadata.drop_all(mysql.db_engine) def test_schema(function): """Create and tear down the test DB schema around a function call. Args: Function (func): the function to be called after creating the test schema. Returns: Function: The decorated function. """ @wraps(function) def call_function_within_db_context(*args, **kwargs): create_tables() seed_tables() try: function_return = function(*args, **kwargs) finally: drop_tables() return function_return return call_function_within_db_context 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.')