"""Utility functions.""" from datetime import datetime from datetime import timedelta from availability.connectors import sql # Import all models here just to make sure SQLAlchemy finds them. from availability.models import product # noqa from availability.models import product_in_store # noqa from availability.models import store # noqa from availability.models import task # noqa from availability.models import task_log # noqa 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 init_database(): """Create all tables in the configured database. Expects that no table exist. Useful only for tests setup functions. """ sql.BaseModel.metadata.create_all(sql._db_engine) if sql._db_engine.name == 'sqlite': # pragma: no cover with sql._db_engine.begin() as sa_conn: sa_conn.connection.connection.create_function( 'SUBDATE', 2, _subdate) def db_setup_function(): """Initialize 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() def db_teardown_function(): """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. """ sql.BaseModel.metadata.drop_all(sql._db_engine)