diff --git a/src/secops/auth.py b/src/secops/auth.py index c7492c7..eda2378 100644 --- a/src/secops/auth.py +++ b/src/secops/auth.py @@ -14,6 +14,7 @@ # """Authentication handling for Google SecOps SDK.""" +import logging import sys from collections.abc import Sequence from dataclasses import asdict, dataclass, field @@ -32,6 +33,8 @@ from secops.exceptions import AuthenticationError +logger = logging.getLogger(__name__) + # Use built-in HTTPMethod from http if Python 3.11+, # otherwise create a compatible version if sys.version_info >= (3, 11): @@ -128,15 +131,13 @@ def increment( Retry object with incremented retry counters. """ if response: - print( + logger.warning( # pylint: disable=logging-fstring-interpolation f"Retrying {method} {url} for {response.status} " - f"status code....", - file=sys.stderr, + f"status code...." ) else: - print( - f"Retrying {method} {url} due to error: {error}", - file=sys.stderr, + logger.warning( # pylint: disable=logging-fstring-interpolation + f"Retrying {method} {url} due to error: {error}" ) return super().increment( diff --git a/tests/test_auth.py b/tests/test_auth.py index 4164bdb..0924b66 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -13,8 +13,12 @@ # limitations under the License. # """Tests for authentication functionality.""" +import logging + import pytest -from secops.auth import SecOpsAuth +from urllib3.response import HTTPResponse + +from secops.auth import LogRetry, SecOpsAuth from secops.exceptions import AuthenticationError # Marked tests for integration as ADC and Service Account Information @@ -85,4 +89,44 @@ def test_bearer_token_credentials_accepted(): ) auth = SecOpsAuth(credentials=creds) - assert auth.credentials is creds \ No newline at end of file + assert auth.credentials is creds + + +def test_increment_response_logs_warning( + caplog: pytest.LogCaptureFixture, + capsys: pytest.CaptureFixture[str], +) -> None: + retry = LogRetry(total=1) + response = HTTPResponse(status=503) + + with caplog.at_level(logging.WARNING, logger="secops.auth"): + retry.increment(method="GET", url="/events", response=response) + + assert caplog.record_tuples == [ + ( + "secops.auth", + logging.WARNING, + "Retrying GET /events for 503 status code....", + ) + ] + assert capsys.readouterr().err == "" + + +def test_increment_error_logs_warning( + caplog: pytest.LogCaptureFixture, + capsys: pytest.CaptureFixture[str], +) -> None: + retry = LogRetry(total=1) + error = RuntimeError("connection failed") + + with caplog.at_level(logging.WARNING, logger="secops.auth"): + retry.increment(method="GET", url="/events", error=error) + + assert caplog.record_tuples == [ + ( + "secops.auth", + logging.WARNING, + "Retrying GET /events due to error: connection failed", + ) + ] + assert capsys.readouterr().err == ""