diff --git a/netboxlabs/diode/sdk/client.py b/netboxlabs/diode/sdk/client.py index 429cab5..f9f94b1 100644 --- a/netboxlabs/diode/sdk/client.py +++ b/netboxlabs/diode/sdk/client.py @@ -237,7 +237,7 @@ def ingest( self._authenticate() continue raise DiodeClientError(err) from err - return RuntimeError("Max retries exceeded") + raise RuntimeError("Max retries exceeded") def _setup_sentry(self, dsn: str, traces_sample_rate: float, profiles_sample_rate: float): sentry_sdk.init( @@ -289,8 +289,11 @@ def authenticate(self) -> str: } ) url = self._get_auth_url() - conn.request("POST", url, data, headers) - response = conn.getresponse() + try: + conn.request("POST", url, data, headers) + response = conn.getresponse() + except Exception as e: + raise DiodeConfigError(f"Failed to obtain access token: {e}") if response.status != 200: raise DiodeConfigError(f"Failed to obtain access token: {response.reason}") token_info = json.loads(response.read().decode()) diff --git a/tests/test_client.py b/tests/test_client.py index 4cc510e..e8383eb 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -588,6 +588,7 @@ def test_diode_authentication_failure(mock_diode_authentication): auth.authenticate() assert "Failed to obtain access token" in str(excinfo.value) + @pytest.mark.parametrize("path", [ "/diode", "", @@ -612,3 +613,21 @@ def test_diode_authentication_url_with_path(mock_diode_authentication, path): auth.authenticate() mock_conn_instance.request.assert_called_once_with("POST", f"{(path or '').rstrip('/')}/auth/token", mock.ANY, mock.ANY) + +def test_diode_authentication_request_exception(mock_diode_authentication): + """Test that an exception during the request raises a DiodeConfigError.""" + auth = _DiodeAuthentication( + target="localhost:8081", + path="/diode", + tls_verify=False, + client_id="test_client_id", + client_secret="test_client_secret", + ) + with mock.patch("http.client.HTTPConnection") as mock_http_conn: + mock_conn_instance = mock_http_conn.return_value + mock_conn_instance.request.side_effect = Exception("Connection error") + + with pytest.raises(DiodeConfigError) as excinfo: + auth.authenticate() + assert "Failed to obtain access token: Connection error" in str(excinfo.value) +