"""Utility functions.""" from datetime import datetime, timedelta from sales_goals.connectors import mysql def _subdate(date, days): """Subtract days from given date. This function is used as replacement for MySQL function SUBDATE. Since SQLite does not have such function, but it's used in application. To make tests running on SQLite in-memory database, this function is registered as user-defined. Args: date (str): Date as formatted string. This is how date is stored in SQLite by sqlalchemy. days (int): Number of days to subtract from date. Returns: str: Result date as formatted string. """ fmt = '%Y-%m-%d %H:%M:%S' date = datetime.strptime(date, fmt) new_date = date - timedelta(days=days) return new_date.strftime(fmt) def get_engine(ar): """Get either sales goals or art relations engine.""" if ar: return mysql._art_relations_engine else: return mysql._sales_goals_engine def init_database(ar): """Create all tables in the configured database. Expects that no table exist. Useful only for tests setup functions. """ engine = get_engine(ar) mysql.BaseModel.metadata.create_all(engine) if mysql._sales_goals_engine.name == ( 'sqlite'): # pragma: no cover with engine.begin() as sa_conn: sa_conn.connection.driver_connection.create_function( 'SUBDATE', 2, _subdate) def db_setup_function(ar=False): """Setup to perform before running any test function in this module. Create all tables in the test (SQLite) database. Import as 'setup_function' or use directly in test modules. """ init_database(ar) def db_teardown_function(ar=False): """Tear down to perform after running any test function in this module. Drop test (SQLite) database. Import as 'setup_function' or use directly in test modules. """ engine = get_engine(ar) mysql.BaseModel.metadata.drop_all(engine)