|
1 | 1 | import unittest |
2 | | -from unittest.mock import patch |
| 2 | +from unittest.mock import patch, MagicMock |
3 | 3 | import common.clients as clients |
| 4 | +from common.clients import get_delta_table |
4 | 5 | import importlib |
5 | 6 |
|
6 | 7 |
|
@@ -61,3 +62,56 @@ def test_logging_initialization(self): |
61 | 62 | self.mock_logging.assert_called_once_with() |
62 | 63 | self.assertTrue(hasattr(clients, 'logger')) |
63 | 64 | clients.logger.setLevel.assert_any_call("INFO") |
| 65 | + |
| 66 | + |
| 67 | +class TestGetDeltaTable(unittest.TestCase): |
| 68 | + |
| 69 | + AWS_REGION = "eu-west-2" # Add this missing constant |
| 70 | + |
| 71 | + def setUp(self): |
| 72 | + self.boto3_client_patch = patch("boto3.client") |
| 73 | + self.mock_boto3_client = self.boto3_client_patch.start() |
| 74 | + |
| 75 | + # Mock the specific logger instance used in the module |
| 76 | + self.logger_patch = patch("common.clients.logger") |
| 77 | + self.mock_logger = self.logger_patch.start() |
| 78 | + |
| 79 | + self.getenv_patch = patch("os.getenv") |
| 80 | + self.mock_getenv = self.getenv_patch.start() |
| 81 | + self.mock_getenv.side_effect = lambda key, default=None: { |
| 82 | + "AWS_REGION": self.AWS_REGION |
| 83 | + }.get(key, default) |
| 84 | + |
| 85 | + self.mock_dynamodb_client = patch("common.clients.dynamodb_client").start() |
| 86 | + |
| 87 | + def tearDown(self): |
| 88 | + patch.stopall() |
| 89 | + |
| 90 | + def test_get_delta_table_success(self): |
| 91 | + # Create a mock table object |
| 92 | + table_name = "abc" |
| 93 | + mock_table = MagicMock() |
| 94 | + self.mock_dynamodb_client.Table.return_value = mock_table |
| 95 | + |
| 96 | + # Call the function |
| 97 | + table = get_delta_table(table_name) |
| 98 | + |
| 99 | + self.mock_dynamodb_client.Table.assert_called_once_with(table_name) |
| 100 | + self.assertEqual(table, mock_table) |
| 101 | + # Verify the success logging |
| 102 | + self.mock_logger.info.assert_called_once_with("Initializing table: %s", table_name) |
| 103 | + |
| 104 | + def test_get_delta_table_failure(self): |
| 105 | + # Simulate exception when accessing Table |
| 106 | + msg = "DynamoDB failure" |
| 107 | + self.mock_dynamodb_client.Table.side_effect = Exception(msg) |
| 108 | + table_name = "abc" |
| 109 | + |
| 110 | + with self.assertRaises(Exception) as context: |
| 111 | + get_delta_table(table_name) |
| 112 | + |
| 113 | + self.assertEqual(str(context.exception), msg) |
| 114 | + # This should now work - mocking the instance method |
| 115 | + self.mock_logger.exception.assert_called_once_with("Error initializing Delta Table") |
| 116 | + # Also verify info logging happened before the exception |
| 117 | + self.mock_logger.info.assert_called_once_with("Initializing table: %s", table_name) |
0 commit comments