Skip to content

feat: wrap exceptions thrown while authenticating #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions netboxlabs/diode/sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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())
Expand Down
19 changes: 19 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
"",
Expand All @@ -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)