"""Utility functions.""" from datetime import datetime from datetime import timedelta from label_copy_export.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 init_database(): """Create all tables in the configured database. Expects that no table exist. Useful only for tests setup functions. """ mysql.BaseModel.metadata.create_all( mysql._label_copy_export_history_engine) if mysql._label_copy_export_history_engine.name == ( 'sqlite'): # pragma: no cover with mysql._label_copy_export_history_engine.begin() as sa_conn: sa_conn.connection.connection.create_function( 'SUBDATE', 2, _subdate) def db_setup_function(): """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() 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. """ mysql.BaseModel.metadata.drop_all(mysql._label_copy_export_history_engine)