|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# pylint: disable=wrong-import-position |
| 3 | +# pylint: disable=R0801,W0613,W0719,W0718 |
| 4 | +"""Test database connectivity.""" |
| 5 | + |
| 6 | +# python stuff |
| 7 | +import os |
| 8 | +import sys |
| 9 | +import unittest |
| 10 | +from pathlib import Path |
| 11 | +from unittest.mock import MagicMock, patch |
| 12 | + |
| 13 | +import pymysql |
| 14 | + |
| 15 | +from app.database import ConfigurationException, DatabaseConnection |
| 16 | +from app.logging_config import get_logger |
| 17 | + |
| 18 | + |
| 19 | +HERE = os.path.abspath(os.path.dirname(__file__)) |
| 20 | +PROJECT_ROOT = str(Path(HERE).parent.parent) |
| 21 | +PYTHON_ROOT = str(Path(PROJECT_ROOT).parent) |
| 22 | +if PYTHON_ROOT not in sys.path: |
| 23 | + sys.path.append(PYTHON_ROOT) # noqa: E402 |
| 24 | + |
| 25 | + |
| 26 | +logger = get_logger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +class TestDatabase(unittest.TestCase): |
| 30 | + """Test database.""" |
| 31 | + |
| 32 | + def test_connection_string(self): |
| 33 | + """Test that the connection string is formed correctly.""" |
| 34 | + db = DatabaseConnection() |
| 35 | + conn_str = db.connection_string |
| 36 | + self.assertIn("@", conn_str) |
| 37 | + self.assertIn("/", conn_str) |
| 38 | + |
| 39 | + @patch("app.database.pymysql.connect") |
| 40 | + def test_get_connection_success(self, mock_connect): |
| 41 | + """Test that a connection is returned on success.""" |
| 42 | + db = DatabaseConnection() |
| 43 | + mock_connect.return_value = MagicMock() |
| 44 | + conn = db.get_connection() |
| 45 | + self.assertIsNotNone(conn) |
| 46 | + mock_connect.assert_called_once() |
| 47 | + |
| 48 | + @patch("app.database.pymysql.connect", side_effect=Exception("fail")) |
| 49 | + def test_get_connection_failure(self, mock_connect): |
| 50 | + """Test that an exception is raised on connection failure.""" |
| 51 | + db = DatabaseConnection() |
| 52 | + with self.assertRaises(Exception): |
| 53 | + db.get_connection() |
| 54 | + |
| 55 | + @patch("app.database.DatabaseConnection.get_connection") |
| 56 | + def test_get_cursor_success(self, mock_get_conn): |
| 57 | + """Test that a cursor is returned on success.""" |
| 58 | + db = DatabaseConnection() |
| 59 | + mock_conn = MagicMock() |
| 60 | + mock_cursor = MagicMock() |
| 61 | + mock_conn.cursor.return_value = mock_cursor |
| 62 | + mock_get_conn.return_value = mock_conn |
| 63 | + with db.get_cursor() as cursor: |
| 64 | + self.assertEqual(cursor, mock_cursor) |
| 65 | + mock_conn.commit.assert_called_once() |
| 66 | + mock_conn.close.assert_called_once() |
| 67 | + |
| 68 | + @patch("app.database.DatabaseConnection.get_connection") |
| 69 | + def test_get_cursor_exception(self, mock_get_conn): |
| 70 | + """Test that an exception during cursor usage rolls back and closes.""" |
| 71 | + db = DatabaseConnection() |
| 72 | + mock_conn = MagicMock() |
| 73 | + mock_cursor = MagicMock() |
| 74 | + mock_conn.cursor.return_value = mock_cursor |
| 75 | + mock_get_conn.return_value = mock_conn |
| 76 | + |
| 77 | + def raise_exc(*args, **kwargs): |
| 78 | + raise Exception("fail") |
| 79 | + |
| 80 | + mock_cursor.execute.side_effect = raise_exc |
| 81 | + try: |
| 82 | + with db.get_cursor() as cursor: |
| 83 | + cursor.execute("SELECT 1") |
| 84 | + except Exception: |
| 85 | + mock_conn.rollback.assert_called_once() |
| 86 | + mock_conn.close.assert_called_once() |
| 87 | + |
| 88 | + @patch("app.database.DatabaseConnection.get_cursor") |
| 89 | + def test_execute_query(self, mock_get_cursor): |
| 90 | + """Test that a query returns results.""" |
| 91 | + db = DatabaseConnection() |
| 92 | + mock_cursor = MagicMock() |
| 93 | + mock_cursor.fetchall.return_value = [{"a": 1}] |
| 94 | + mock_get_cursor.return_value.__enter__.return_value = mock_cursor |
| 95 | + result = db.execute_query("SELECT * FROM test") |
| 96 | + self.assertEqual(result, [{"a": 1}]) |
| 97 | + |
| 98 | + @patch("app.database.DatabaseConnection.get_cursor") |
| 99 | + def test_execute_update(self, mock_get_cursor): |
| 100 | + """Test that an update returns affected row count.""" |
| 101 | + db = DatabaseConnection() |
| 102 | + mock_cursor = MagicMock() |
| 103 | + mock_cursor.rowcount = 2 |
| 104 | + mock_get_cursor.return_value.__enter__.return_value = mock_cursor |
| 105 | + result = db.execute_update("UPDATE test SET a=1") |
| 106 | + self.assertEqual(result, 2) |
| 107 | + |
| 108 | + @patch("app.database.DatabaseConnection.get_cursor") |
| 109 | + def test_test_connection_success(self, mock_get_cursor): |
| 110 | + """Test that the database connection is successful.""" |
| 111 | + db = DatabaseConnection() |
| 112 | + mock_cursor = MagicMock() |
| 113 | + mock_get_cursor.return_value.__enter__.return_value = mock_cursor |
| 114 | + mock_cursor.execute.return_value = None |
| 115 | + self.assertTrue(db.test_connection()) |
| 116 | + |
| 117 | + @patch("app.database.DatabaseConnection.get_cursor", side_effect=Exception("fail")) |
| 118 | + def test_test_connection_failure(self, mock_get_cursor): |
| 119 | + """Test that the database connection failure is handled.""" |
| 120 | + db = DatabaseConnection() |
| 121 | + self.assertFalse(db.test_connection()) |
| 122 | + |
| 123 | + def test_missing_config_raises(self): |
| 124 | + """Test that missing configuration raises ConfigurationException.""" |
| 125 | + with ( |
| 126 | + patch("app.database.MYSQL_HOST", ""), |
| 127 | + patch("app.database.MYSQL_USER", ""), |
| 128 | + patch("app.database.MYSQL_PASSWORD", ""), |
| 129 | + patch("app.database.MYSQL_DATABASE", ""), |
| 130 | + ): |
| 131 | + with self.assertRaises(ConfigurationException): |
| 132 | + DatabaseConnection() |
| 133 | + |
| 134 | + @patch("app.database.pymysql.connect", side_effect=pymysql.Error("connection failed")) |
| 135 | + def test_get_connection_raises(self, mock_connect): |
| 136 | + """Test that a pymysql.Error during connection raises the appropriate exception.""" |
| 137 | + db = DatabaseConnection() |
| 138 | + with self.assertRaises(pymysql.Error) as ctx: |
| 139 | + db.get_connection() |
| 140 | + self.assertIn("Failed to connect to MySQL database", str(ctx.exception)) |
0 commit comments