|
2 | 2 | from unittest.mock import patch
|
3 | 3 | import logging
|
4 | 4 | from typing import Optional
|
| 5 | +from requests.models import Response |
5 | 6 |
|
6 | 7 | import openai
|
7 |
| -from openai import APIConnectionError, AuthenticationError |
| 8 | +from openai import APIConnectionError, AuthenticationError, APIStatusError |
8 | 9 |
|
9 | 10 | # Setup logging
|
10 | 11 | logging.basicConfig(level=logging.INFO)
|
11 | 12 | logger = logging.getLogger(__name__)
|
12 | 13 |
|
13 |
| -# Process data using AI |
| 14 | + |
14 | 15 | class AIHandler:
|
15 | 16 | """Process data using AI."""
|
16 | 17 |
|
17 |
| - MODEL = "gpt4o" |
| 18 | + MODEL = "gpt-4" |
18 | 19 |
|
19 | 20 | def __init__(self, openai_key: str) -> None:
|
20 | 21 | """
|
@@ -53,11 +54,12 @@ def query_api(self, query: str) -> Optional[str]:
|
53 | 54 | except AuthenticationError as ex:
|
54 | 55 | logger.error("Authentication error: %s", ex)
|
55 | 56 | except APIConnectionError as ex:
|
56 |
| - logger.error("APIConnection error: %s", ex) |
| 57 | + logger.error("API connection error: %s", ex) |
| 58 | + except APIStatusError as ex: |
| 59 | + logger.error("API status error: %s", ex) |
57 | 60 |
|
58 | 61 | return result
|
59 | 62 |
|
60 |
| - |
61 | 63 | # Mocking classes for testing
|
62 | 64 | class MockedChoice:
|
63 | 65 | def __init__(self, content: str) -> None:
|
@@ -87,12 +89,29 @@ def test_query_api(self, mock_create):
|
87 | 89 |
|
88 | 90 | # Check that the API was called with the correct parameters
|
89 | 91 | mock_create.assert_called_once_with(
|
90 |
| - model="gpt4o", messages=[{"role": "user", "content": "Test query"}] |
| 92 | + model="gpt-4", messages=[{"role": "user", "content": "Test query"}] |
91 | 93 | )
|
92 | 94 |
|
| 95 | + @patch('openai.ChatCompletion.create') |
| 96 | + def test_query_api_authentication_error(self, mock_create): |
| 97 | + # Create a mock response object |
| 98 | + mock_response = Response() |
| 99 | + mock_response.status_code = 401 # Unauthorized status code |
| 100 | + |
| 101 | + # Mock the error |
| 102 | + mock_create.side_effect = AuthenticationError( |
| 103 | + message="Invalid API key", |
| 104 | + response=mock_response, |
| 105 | + body={} |
| 106 | + ) |
93 | 107 |
|
| 108 | + handler = AIHandler(openai_key="fake_api_key") |
| 109 | + response = handler.query_api("Test query") |
94 | 110 |
|
95 |
| - |
| 111 | + self.assertIsNone(response) |
| 112 | + mock_create.assert_called_once_with( |
| 113 | + model="gpt-4", messages=[{"role": "user", "content": "Test query"}] |
| 114 | + ) |
96 | 115 |
|
97 | 116 |
|
98 | 117 |
|
0 commit comments