|
| 1 | +import os |
| 2 | +import unittest |
| 3 | +from unittest.mock import patch, MagicMock |
| 4 | +from datetime import datetime, timezone |
| 5 | + |
| 6 | +from cyborgdb.demo import get_demo_api_key |
| 7 | + |
| 8 | + |
| 9 | +class TestGetDemoApiKey(unittest.TestCase): |
| 10 | + """Unit tests for the get_demo_api_key function.""" |
| 11 | + |
| 12 | + def setUp(self): |
| 13 | + """Set up test environment.""" |
| 14 | + # Store original env var to restore later |
| 15 | + self.original_env = os.environ.get("CYBORGDB_DEMO_ENDPOINT") |
| 16 | + |
| 17 | + def tearDown(self): |
| 18 | + """Clean up test environment.""" |
| 19 | + # Restore original env var |
| 20 | + if self.original_env is not None: |
| 21 | + os.environ["CYBORGDB_DEMO_ENDPOINT"] = self.original_env |
| 22 | + elif "CYBORGDB_DEMO_ENDPOINT" in os.environ: |
| 23 | + del os.environ["CYBORGDB_DEMO_ENDPOINT"] |
| 24 | + |
| 25 | + @patch("cyborgdb.demo.requests.post") |
| 26 | + def test_get_demo_api_key_success(self, mock_post): |
| 27 | + """Test successful demo API key generation.""" |
| 28 | + # Mock successful response |
| 29 | + mock_response = MagicMock() |
| 30 | + mock_response.status_code = 200 |
| 31 | + mock_response.json.return_value = { |
| 32 | + "apiKey": "demo_test_key_12345", |
| 33 | + "expiresAt": datetime.now(timezone.utc).timestamp() + 3600, |
| 34 | + } |
| 35 | + mock_post.return_value = mock_response |
| 36 | + |
| 37 | + # Call the function |
| 38 | + api_key = get_demo_api_key() |
| 39 | + |
| 40 | + # Verify the result |
| 41 | + self.assertEqual(api_key, "demo_test_key_12345") |
| 42 | + |
| 43 | + # Verify the request was made correctly |
| 44 | + mock_post.assert_called_once() |
| 45 | + call_args = mock_post.call_args |
| 46 | + self.assertEqual( |
| 47 | + call_args.kwargs["json"], {"description": "Temporary demo API key"} |
| 48 | + ) |
| 49 | + self.assertEqual( |
| 50 | + call_args.kwargs["headers"], |
| 51 | + {"Content-Type": "application/json", "Accept": "application/json"}, |
| 52 | + ) |
| 53 | + |
| 54 | + @patch("cyborgdb.demo.requests.post") |
| 55 | + def test_get_demo_api_key_with_custom_description(self, mock_post): |
| 56 | + """Test demo API key generation with custom description.""" |
| 57 | + # Mock successful response |
| 58 | + mock_response = MagicMock() |
| 59 | + mock_response.status_code = 200 |
| 60 | + mock_response.json.return_value = { |
| 61 | + "apiKey": "demo_test_key_67890", |
| 62 | + } |
| 63 | + mock_post.return_value = mock_response |
| 64 | + |
| 65 | + # Call the function with custom description |
| 66 | + custom_description = "My custom demo key" |
| 67 | + api_key = get_demo_api_key(description=custom_description) |
| 68 | + |
| 69 | + # Verify the result |
| 70 | + self.assertEqual(api_key, "demo_test_key_67890") |
| 71 | + |
| 72 | + # Verify the custom description was used |
| 73 | + call_args = mock_post.call_args |
| 74 | + self.assertEqual(call_args.kwargs["json"], {"description": custom_description}) |
| 75 | + |
| 76 | + @patch("cyborgdb.demo.requests.post") |
| 77 | + def test_get_demo_api_key_uses_default_endpoint(self, mock_post): |
| 78 | + """Test that default endpoint is used when env var is not set.""" |
| 79 | + # Ensure env var is not set |
| 80 | + if "CYBORGDB_DEMO_ENDPOINT" in os.environ: |
| 81 | + del os.environ["CYBORGDB_DEMO_ENDPOINT"] |
| 82 | + |
| 83 | + # Mock successful response |
| 84 | + mock_response = MagicMock() |
| 85 | + mock_response.status_code = 200 |
| 86 | + mock_response.json.return_value = { |
| 87 | + "apiKey": "demo_test_key_default", |
| 88 | + } |
| 89 | + mock_post.return_value = mock_response |
| 90 | + |
| 91 | + # Call the function |
| 92 | + api_key = get_demo_api_key() |
| 93 | + |
| 94 | + # Verify default endpoint was used |
| 95 | + call_args = mock_post.call_args |
| 96 | + self.assertEqual( |
| 97 | + call_args.args[0], |
| 98 | + "https://api.cyborgdb.co/v1/api-key/manage/create-demo-key", |
| 99 | + ) |
| 100 | + self.assertEqual(api_key, "demo_test_key_default") |
| 101 | + |
| 102 | + @patch("cyborgdb.demo.requests.post") |
| 103 | + def test_get_demo_api_key_uses_env_endpoint(self, mock_post): |
| 104 | + """Test that custom endpoint from env var is used.""" |
| 105 | + # Set custom endpoint |
| 106 | + custom_endpoint = "https://custom.api.example.com/demo-key" |
| 107 | + os.environ["CYBORGDB_DEMO_ENDPOINT"] = custom_endpoint |
| 108 | + |
| 109 | + # Mock successful response |
| 110 | + mock_response = MagicMock() |
| 111 | + mock_response.status_code = 200 |
| 112 | + mock_response.json.return_value = { |
| 113 | + "apiKey": "demo_test_key_custom", |
| 114 | + } |
| 115 | + mock_post.return_value = mock_response |
| 116 | + |
| 117 | + # Call the function |
| 118 | + api_key = get_demo_api_key() |
| 119 | + |
| 120 | + # Verify custom endpoint was used |
| 121 | + call_args = mock_post.call_args |
| 122 | + self.assertEqual(call_args.args[0], custom_endpoint) |
| 123 | + self.assertEqual(api_key, "demo_test_key_custom") |
| 124 | + |
| 125 | + @patch("cyborgdb.demo.requests.post") |
| 126 | + def test_get_demo_api_key_missing_api_key_in_response(self, mock_post): |
| 127 | + """Test handling of response missing apiKey field.""" |
| 128 | + # Mock response without apiKey |
| 129 | + mock_response = MagicMock() |
| 130 | + mock_response.status_code = 200 |
| 131 | + mock_response.json.return_value = { |
| 132 | + "success": True, |
| 133 | + } |
| 134 | + mock_post.return_value = mock_response |
| 135 | + |
| 136 | + # Call the function and expect ValueError |
| 137 | + with self.assertRaises(ValueError) as context: |
| 138 | + get_demo_api_key() |
| 139 | + |
| 140 | + self.assertIn("Demo API key not found in response", str(context.exception)) |
| 141 | + |
| 142 | + @patch("cyborgdb.demo.requests.post") |
| 143 | + def test_get_demo_api_key_http_error(self, mock_post): |
| 144 | + """Test handling of HTTP errors.""" |
| 145 | + # Mock HTTP error |
| 146 | + import requests |
| 147 | + |
| 148 | + mock_post.side_effect = requests.exceptions.HTTPError("404 Not Found") |
| 149 | + |
| 150 | + # Call the function and expect ValueError |
| 151 | + with self.assertRaises(ValueError) as context: |
| 152 | + get_demo_api_key() |
| 153 | + |
| 154 | + self.assertIn("Failed to generate demo API key", str(context.exception)) |
| 155 | + |
| 156 | + @patch("cyborgdb.demo.requests.post") |
| 157 | + def test_get_demo_api_key_connection_error(self, mock_post): |
| 158 | + """Test handling of connection errors.""" |
| 159 | + # Mock connection error |
| 160 | + import requests |
| 161 | + |
| 162 | + mock_post.side_effect = requests.exceptions.ConnectionError( |
| 163 | + "Failed to connect" |
| 164 | + ) |
| 165 | + |
| 166 | + # Call the function and expect ValueError |
| 167 | + with self.assertRaises(ValueError) as context: |
| 168 | + get_demo_api_key() |
| 169 | + |
| 170 | + self.assertIn("Failed to generate demo API key", str(context.exception)) |
| 171 | + |
| 172 | + @patch("cyborgdb.demo.requests.post") |
| 173 | + def test_get_demo_api_key_timeout_error(self, mock_post): |
| 174 | + """Test handling of timeout errors.""" |
| 175 | + # Mock timeout error |
| 176 | + import requests |
| 177 | + |
| 178 | + mock_post.side_effect = requests.exceptions.Timeout("Request timed out") |
| 179 | + |
| 180 | + # Call the function and expect ValueError |
| 181 | + with self.assertRaises(ValueError) as context: |
| 182 | + get_demo_api_key() |
| 183 | + |
| 184 | + self.assertIn("Failed to generate demo API key", str(context.exception)) |
| 185 | + |
| 186 | + @patch("cyborgdb.demo.requests.post") |
| 187 | + def test_get_demo_api_key_with_expiration_info(self, mock_post): |
| 188 | + """Test that expiration info is logged correctly.""" |
| 189 | + # Mock successful response with expiration |
| 190 | + mock_response = MagicMock() |
| 191 | + mock_response.status_code = 200 |
| 192 | + future_timestamp = datetime.now(timezone.utc).timestamp() + 7200 # 2 hours |
| 193 | + mock_response.json.return_value = { |
| 194 | + "apiKey": "demo_test_key_expires", |
| 195 | + "expiresAt": future_timestamp, |
| 196 | + } |
| 197 | + mock_post.return_value = mock_response |
| 198 | + |
| 199 | + # Call the function |
| 200 | + with self.assertLogs("cyborgdb.demo", level="INFO") as log_context: |
| 201 | + api_key = get_demo_api_key() |
| 202 | + |
| 203 | + # Verify the result |
| 204 | + self.assertEqual(api_key, "demo_test_key_expires") |
| 205 | + |
| 206 | + # Verify expiration was logged |
| 207 | + self.assertTrue( |
| 208 | + any("Demo API key will expire in" in log for log in log_context.output) |
| 209 | + ) |
| 210 | + |
| 211 | + |
| 212 | +if __name__ == "__main__": |
| 213 | + unittest.main() |
0 commit comments