Skip to content

Commit

Permalink
Start fixing some of the issues reported by the pipeline
Browse files Browse the repository at this point in the history
  • Loading branch information
TiagoOpenCosmos committed Jan 24, 2025
1 parent df656da commit d13ce9b
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 40 deletions.
24 changes: 17 additions & 7 deletions datacosmos/client.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import logging
import os
from datetime import datetime, timedelta, timezone
from typing import Optional, Any
from typing import Any, Optional

import requests
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
from requests.exceptions import RequestException
from requests_oauthlib import OAuth2Session

from config.config import Config

Expand All @@ -18,7 +18,9 @@ class DatacosmosClient:
"""

def __init__(
self, config: Optional[Config] = None, config_file: str = "config/config.yaml"
self,
config: Optional[Config] = None,
config_file: str = "config/config.yaml",
):
"""
Initialize the DatacosmosClient.
Expand All @@ -42,7 +44,9 @@ def _load_config(self, config_file: str) -> Config:
if os.path.exists(config_file):
self.logger.info(f"Loading configuration from {config_file}")
return Config.from_yaml(config_file)
self.logger.info("Loading configuration from environment variables")
self.logger.info(
"Loading configuration from environment variables"
)
return Config.from_env()
except Exception as e:
self.logger.error(f"Failed to load configuration: {e}")
Expand Down Expand Up @@ -73,7 +77,9 @@ def _authenticate_and_initialize_client(self) -> requests.Session:

# Initialize the HTTP session with the Authorization header
http_client = requests.Session()
http_client.headers.update({"Authorization": f"Bearer {self.token}"})
http_client.headers.update(
{"Authorization": f"Bearer {self.token}"}
)
return http_client
except RequestException as e:
self.logger.error(f"Request failed during authentication: {e}")
Expand All @@ -97,7 +103,9 @@ def get_http_client(self) -> requests.Session:
self._refresh_token_if_needed()
return self._http_client

def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> requests.Response:
def request(
self, method: str, url: str, *args: Any, **kwargs: Any
) -> requests.Response:
"""
Send an HTTP request using the authenticated session.
Logs request and response details.
Expand All @@ -107,7 +115,9 @@ def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> requests.
self.logger.info(f"Making {method.upper()} request to {url}")
response = self._http_client.request(method, url, *args, **kwargs)
response.raise_for_status()
self.logger.info(f"Request to {url} succeeded with status {response.status_code}")
self.logger.info(
f"Request to {url} succeeded with status {response.status_code}"

Check failure on line 119 in datacosmos/client.py

View workflow job for this annotation

GitHub Actions / Flake8

datacosmos/client.py#L119

Line too long (80 > 79 characters) (E501)
)
return response
except RequestException as e:
self.logger.error(f"HTTP request failed: {e}")
Expand Down
10 changes: 7 additions & 3 deletions tests/unit/datacosmos/client/test_client_authentication.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
from unittest.mock import patch, MagicMock
from datacosmos.client import DatacosmosClient
from unittest.mock import MagicMock, patch

Check failure on line 1 in tests/unit/datacosmos/client/test_client_authentication.py

View workflow job for this annotation

GitHub Actions / Flake8

tests/unit/datacosmos/client/test_client_authentication.py#L1

'unittest.mock.MagicMock' imported but unused (F401)

from config.config import Config
from datacosmos.client import DatacosmosClient


@patch("datacosmos.client.OAuth2Session.fetch_token")
@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client", autospec=True)
@patch(
"datacosmos.client.DatacosmosClient._authenticate_and_initialize_client",
autospec=True,
)
def test_client_authentication(mock_auth_client, mock_fetch_token):
"""
Test that the client correctly fetches a token during authentication.
Expand Down
12 changes: 7 additions & 5 deletions tests/unit/datacosmos/client/test_client_delete_request.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from unittest.mock import patch, MagicMock
from datacosmos.client import DatacosmosClient
from unittest.mock import MagicMock, patch

from config.config import Config
from datacosmos.client import DatacosmosClient


@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")
@patch(
"datacosmos.client.DatacosmosClient._authenticate_and_initialize_client"
)
def test_delete_request(mock_auth_client):
"""
Test that the client performs a DELETE request correctly.
Expand All @@ -27,7 +30,6 @@ def test_delete_request(mock_auth_client):
# Assertions
assert response.status_code == 204
mock_http_client.request.assert_called_once_with(
"DELETE",
"https://mock.api/some-endpoint"
"DELETE", "https://mock.api/some-endpoint"
)
mock_auth_client.call_count == 2
12 changes: 7 additions & 5 deletions tests/unit/datacosmos/client/test_client_get_request.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from unittest.mock import patch, MagicMock
from datacosmos.client import DatacosmosClient
from unittest.mock import MagicMock, patch

from config.config import Config
from datacosmos.client import DatacosmosClient


@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")
@patch(
"datacosmos.client.DatacosmosClient._authenticate_and_initialize_client"
)
def test_client_get_request(mock_auth_client):
"""
Test that the client performs a GET request correctly.
Expand All @@ -29,7 +32,6 @@ def test_client_get_request(mock_auth_client):
assert response.status_code == 200
assert response.json() == {"message": "success"}
mock_http_client.request.assert_called_once_with(
"GET",
"https://mock.api/some-endpoint"
"GET", "https://mock.api/some-endpoint"
)
mock_auth_client.call_count == 2
9 changes: 6 additions & 3 deletions tests/unit/datacosmos/client/test_client_initialization.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from unittest.mock import patch, MagicMock
from datacosmos.client import DatacosmosClient
from unittest.mock import MagicMock, patch

from config.config import Config
from datacosmos.client import DatacosmosClient


@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")
@patch(
"datacosmos.client.DatacosmosClient._authenticate_and_initialize_client"
)
@patch("os.path.exists", return_value=False)
@patch("config.Config.from_env")
def test_client_initialization(mock_from_env, mock_exists, mock_auth_client):
Expand Down
13 changes: 7 additions & 6 deletions tests/unit/datacosmos/client/test_client_post_request.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from unittest.mock import patch, MagicMock
from datacosmos.client import DatacosmosClient
from unittest.mock import MagicMock, patch

from config.config import Config
from datacosmos.client import DatacosmosClient


@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")
@patch(
"datacosmos.client.DatacosmosClient._authenticate_and_initialize_client"
)
def test_post_request(mock_auth_client):
"""
Test that the client performs a POST request correctly.
Expand Down Expand Up @@ -31,8 +34,6 @@ def test_post_request(mock_auth_client):
assert response.status_code == 201
assert response.json() == {"message": "created"}
mock_http_client.request.assert_called_once_with(
"POST",
"https://mock.api/some-endpoint",
json={"key": "value"}
"POST", "https://mock.api/some-endpoint", json={"key": "value"}

Check failure on line 37 in tests/unit/datacosmos/client/test_client_post_request.py

View workflow job for this annotation

GitHub Actions / Black

tests/unit/datacosmos/client/test_client_post_request.py#L24-L37

client_secret="test-client-secret", token_url="https://mock.token.url/oauth/token", audience="https://mock.audience", ) client = DatacosmosClient(config=config) - response = client.post( - "https://mock.api/some-endpoint", json={"key": "value"} - ) + response = client.post("https://mock.api/some-endpoint", json={"key": "value"}) # Assertions assert response.status_code == 201 assert response.json() == {"message": "created"} mock_http_client.request.assert_called_once_with(
)
mock_auth_client.call_count == 2
13 changes: 7 additions & 6 deletions tests/unit/datacosmos/client/test_client_put_request.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from unittest.mock import patch, MagicMock
from datacosmos.client import DatacosmosClient
from unittest.mock import MagicMock, patch

from config.config import Config
from datacosmos.client import DatacosmosClient


@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")
@patch(
"datacosmos.client.DatacosmosClient._authenticate_and_initialize_client"
)
def test_put_request(mock_auth_client):
"""
Test that the client performs a PUT request correctly.
Expand Down Expand Up @@ -31,8 +34,6 @@ def test_put_request(mock_auth_client):
assert response.status_code == 200
assert response.json() == {"message": "updated"}
mock_http_client.request.assert_called_once_with(
"PUT",
"https://mock.api/some-endpoint",
json={"key": "updated-value"}
"PUT", "https://mock.api/some-endpoint", json={"key": "updated-value"}
)
mock_auth_client.call_count == 2
12 changes: 7 additions & 5 deletions tests/unit/datacosmos/client/test_client_token_refreshing.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from unittest.mock import patch, MagicMock
from datetime import datetime, timedelta, timezone
from datacosmos.client import DatacosmosClient
from unittest.mock import MagicMock, patch

from config.config import Config
from datacosmos.client import DatacosmosClient


@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")
@patch(
"datacosmos.client.DatacosmosClient._authenticate_and_initialize_client"
)
def test_client_token_refreshing(mock_auth_client):
"""
Test that the client refreshes the token when it expires.
Expand Down Expand Up @@ -44,6 +47,5 @@ def test_client_token_refreshing(mock_auth_client):

# Verify the request was made correctly
mock_http_client.request.assert_called_once_with(
"GET",
"https://mock.api/some-endpoint"
"GET", "https://mock.api/some-endpoint"
)

0 comments on commit d13ce9b

Please sign in to comment.