"""Test DbAdapter.""" from unittest.mock import Mock from unittest.mock import patch from MySQLdb import OperationalError import pytest from accounting.adapters.db import DatabaseAdapter @patch('MySQLdb.connect') def test_db_connection(mock_connector): """Test connecting to the db.""" mock_connector.return_value = Mock() adapter = DatabaseAdapter() connection = adapter._get_connection() assert connection def test_db_connection_failure(): """Test a failing connection to the db.""" with pytest.raises(OperationalError): adapter = DatabaseAdapter() adapter._get_connection({ 'user': 'user', 'password': 'password', 'host': 'unreachable', 'database': '_' }) assert True @patch('MySQLdb.connect') def test_fetch_rows(mock_connector): """Test fetching rows.""" expected_value = [ [ 1, 2, 3 ] ] my_mock = Mock() my_mock.cursor.return_value = Mock() my_mock.cursor.return_value.fetchall.return_value = expected_value mock_connector.return_value = my_mock adapter = DatabaseAdapter() result = adapter.fetch_rows('select * from users') assert result == expected_value @patch('MySQLdb.connect') def test_db_pool(mock_connector, monkeypatch): """Test setting a connection pool size in the config.""" from accounting import config monkeypatch.setattr(config, 'DB_POOL_SIZE', 4) adapter = DatabaseAdapter() adapter.fetch_rows('foo') assert mock_connector.call_count == 1