from unittest.mock import MagicMock from garcon.contrib import util_snowflake as python_connector import pytest from snowflake import connector def test_connect(mocker): """Test connection factory. """ connector = mocker.patch('snowflake.connector.connect') with python_connector.connect( user='user', password='password', account='account') as conn: assert conn assert connector.called assert conn.close.called def test_cursor(monkeypatch): """Test cursor context manager""" mock_cursor = MagicMock() monkeypatch.setattr( mock_cursor, 'close', MagicMock(return_value=None)) mock_connection = MagicMock() mock_connection.close = lambda: None monkeypatch.setattr( mock_connection, 'cursor', MagicMock(return_value=mock_cursor)) monkeypatch.setattr( connector, 'connect', MagicMock(return_value=mock_connection)) with python_connector.connect( user='user', password='password', account='account') as conn: with python_connector.cursor(conn) as cur: assert cur == mock_cursor assert cur.close.called sf_cfg = python_connector.DEFAULT_DB_CONFIG @pytest.fixture(params=[ python_connector.FetchEnum.ALL, python_connector.FetchEnum.ONE ]) def fetch_action(request): """ Fixture returns list of test parameters for execute_with_py_conn """ return request.param def test_execute_with_py_conn( monkeypatch, fetch_action, sql_statement='test', config=sf_cfg, result_key='key'): mock_cursor = MagicMock() monkeypatch.setattr( mock_cursor, 'fetchall', MagicMock(return_value=(('test', 'test'), ('test', 'test')))) monkeypatch.setattr( mock_cursor, 'fetchone', MagicMock(return_value=('test', 'test'))) mock_connection = MagicMock() monkeypatch.setattr( mock_connection, 'cursor', MagicMock(return_value=mock_cursor)) monkeypatch.setattr( connector, 'connect', MagicMock(return_value=mock_connection)) res = python_connector.execute_with_py_conn( sql_statement, fetch_action, config, result_key) if fetch_action == python_connector.FetchEnum.ALL: assert mock_cursor.fetchall.called elif fetch_action == python_connector.FetchEnum.ONE: assert mock_cursor.fetchone.called assert isinstance(res, dict) assert res.get(result_key) def test_table_exists(monkeypatch, table='notable'): execute_with_py_conn_mock = MagicMock( return_value=dict(exists=('test', 'test'))) monkeypatch.setattr( python_connector, 'execute_with_py_conn', execute_with_py_conn_mock) exists = python_connector.table_exists(table) expected_sql = python_connector.TABLE_EXISTS_SQL.format( db=sf_cfg.get('db'), schema=sf_cfg.get('schema'), table=table) execute_with_py_conn_mock.assert_called_with( expected_sql, python_connector.FetchEnum.ONE, sf_cfg, 'exists') assert exists