"""Misc utilities for testing.""" from functools import wraps import sys from oto import response from conflict_manager import config from conflict_manager.connectors import snowflake from conflict_manager.utils import service_utils def wrap_api_results(data_list, total_records=0, offset=0, limit=50): """Wrap list of data into standard API message.""" return { 'items': data_list, 'pagination': { 'type': 'standard', 'offset': offset, 'limit': limit, 'total_records': total_records or len(data_list) } } def patch_get_from_ows_service(mocker, mock_response): """Patch get_from_ows_service with required response. Args: mocker (unittest.mock): pytest Mock helper mock_response (response.Response): patched response object Returns: MagicMock: mock object """ if isinstance(mock_response, list): mock_response = wrap_api_results(mock_response) if isinstance(mock_response, dict): mock_response = response.Response(mock_response) method_mock = mocker.patch.object( service_utils, 'get_from_ows_service', return_value=mock_response) return method_mock def test_schema_no_seed(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() try: function_return = function(*args, **kwargs) finally: drop_tables() return function_return return call_function_within_db_context def create_tables(): """Create table schemas after testing.""" with snowflake.db_session() as session: exit_if_not_test_environment(session) snowflake.BaseModel.metadata.create_all( snowflake._snowflake_db_engine) def drop_tables(): """Drop table schemas after testing.""" with snowflake.db_session() as session: exit_if_not_test_environment(session) snowflake.BaseModel.metadata.drop_all( snowflake._snowflake_db_engine) 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. Args: session (object): sqlalchemy session """ 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.')