Skip to content

Commit

Permalink
Apply pydocstyle
Browse files Browse the repository at this point in the history
  • Loading branch information
TiagoOpenCosmos committed Jan 24, 2025
1 parent e1bee71 commit 1e40bd6
Show file tree
Hide file tree
Showing 10 changed files with 43 additions and 58 deletions.
3 changes: 2 additions & 1 deletion config/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Configuration package for the Datacosmos SDK.
This package includes modules for loading and managing authentication configurations.
This package includes modules for loading and managing authentication
configurations.
"""

# Expose Config class for easier imports
Expand Down
3 changes: 2 additions & 1 deletion config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
class Config:
"""Configuration for the Datacosmos SDK.
Contains authentication details such as client ID, secret, token URL, and audience.
Contains authentication details such as client ID, secret, token
URL, and audience.
"""

client_id: str
Expand Down
63 changes: 29 additions & 34 deletions datacosmos/client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
"""DatacosmosClient handles authenticated interactions with the Datacosmos API.
Automatically manages token refreshing and provides HTTP convenience
methods.
"""

import logging
import os
from datetime import datetime, timedelta, timezone
Expand All @@ -12,21 +18,21 @@


class DatacosmosClient:
"""
DatacosmosClient handles authenticated interactions with the Datacosmos API.
Automatically manages token refreshing and provides HTTP convenience methods.
"""DatacosmosClient handles authenticated interactions with the Datacosmos API.

Check failure on line 21 in datacosmos/client.py

View workflow job for this annotation

GitHub Actions / Flake8

datacosmos/client.py#L21

Line too long (83 > 79 characters) (E501)
Automatically manages token refreshing and provides HTTP convenience
methods.
"""

def __init__(
self,
config: Optional[Config] = None,
config_file: str = "config/config.yaml",
):
"""
Initialize the DatacosmosClient.
"""Initialize the DatacosmosClient.
If no configuration is provided, it will load from the specified YAML file
or fall back to environment variables.
If no configuration is provided, it will load from the specified
YAML file or fall back to environment variables.
"""
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
Expand All @@ -37,23 +43,23 @@ def __init__(
self._http_client = self._authenticate_and_initialize_client()

def _load_config(self, config_file: str) -> Config:
"""
Load configuration from the YAML file. Fall back to environment variables if the file is missing.
"""Load configuration from the YAML file.
Fall back to environment variables if the file is missing.
"""
try:
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}")
raise

def _authenticate_and_initialize_client(self) -> requests.Session:

Check failure on line 61 in datacosmos/client.py

View workflow job for this annotation

GitHub Actions / Black

datacosmos/client.py#L49-L61

""" try: 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}") raise
"""
Authenticate and initialize the HTTP client with a valid token.
"""
"""Authenticate and initialize the HTTP client with a valid token."""
try:
self.logger.info("Authenticating with the token endpoint")
client = BackendApplicationClient(client_id=self.config.client_id)
Expand All @@ -75,7 +81,8 @@ 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 @@ -85,25 +92,21 @@ def _authenticate_and_initialize_client(self) -> requests.Session:
raise

def _refresh_token_if_needed(self):
"""
Refresh the token if it has expired.
"""
"""Refresh the token if it has expired."""
if not self.token or self.token_expiry <= datetime.now(timezone.utc):
self.logger.info("Token expired or missing, refreshing token")
self._http_client = self._authenticate_and_initialize_client()

def get_http_client(self) -> requests.Session:
"""
Return the authenticated HTTP client, refreshing the token if necessary.
"""
"""Return the authenticated HTTP client, refreshing the token if necessary."""

Check failure on line 101 in datacosmos/client.py

View workflow job for this annotation

GitHub Actions / Flake8

datacosmos/client.py#L101

Line too long (86 > 79 characters) (E501)
self._refresh_token_if_needed()
return self._http_client

def request(
self, method: str, url: str, *args: Any, **kwargs: Any
) -> requests.Response:
"""
Send an HTTP request using the authenticated session.
"""Send an HTTP request using the authenticated session.
Logs request and response details.
"""
self._refresh_token_if_needed()
Expand All @@ -123,25 +126,17 @@ def request(
raise

def get(self, url: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Send a GET request using the authenticated session.
"""
"""Send a GET request using the authenticated session."""
return self.request("GET", url, *args, **kwargs)

def post(self, url: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Send a POST request using the authenticated session.
"""
"""Send a POST request using the authenticated session."""
return self.request("POST", url, *args, **kwargs)

def put(self, url: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Send a PUT request using the authenticated session.
"""
"""Send a PUT request using the authenticated session."""
return self.request("PUT", url, *args, **kwargs)

def delete(self, url: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Send a DELETE request using the authenticated session.
"""
"""Send a DELETE request using the authenticated session."""
return self.request("DELETE", url, *args, **kwargs)
4 changes: 1 addition & 3 deletions tests/unit/datacosmos/client/test_client_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
autospec=True,
)
def test_client_authentication(mock_auth_client, mock_fetch_token):
"""
Test that the client correctly fetches a token during authentication.
"""
"""Test that the client correctly fetches a token during authentication."""
# Mock the token response from OAuth2Session
mock_fetch_token.return_value = {
"access_token": "mock-access-token",
Expand Down
4 changes: 1 addition & 3 deletions tests/unit/datacosmos/client/test_client_delete_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@

@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")

Check failure on line 7 in tests/unit/datacosmos/client/test_client_delete_request.py

View workflow job for this annotation

GitHub Actions / Flake8

tests/unit/datacosmos/client/test_client_delete_request.py#L7

Line too long (80 > 79 characters) (E501)
def test_delete_request(mock_auth_client):
"""
Test that the client performs a DELETE request correctly.
"""
"""Test that the client performs a DELETE request correctly."""
# Mock the HTTP client
mock_http_client = MagicMock()
mock_response = MagicMock()
Expand Down
4 changes: 1 addition & 3 deletions tests/unit/datacosmos/client/test_client_get_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@

@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")

Check failure on line 7 in tests/unit/datacosmos/client/test_client_get_request.py

View workflow job for this annotation

GitHub Actions / Flake8

tests/unit/datacosmos/client/test_client_get_request.py#L7

Line too long (80 > 79 characters) (E501)
def test_client_get_request(mock_auth_client):
"""
Test that the client performs a GET request correctly.
"""
"""Test that the client performs a GET request correctly."""
# Mock the HTTP client
mock_http_client = MagicMock()
mock_response = MagicMock()
Expand Down
5 changes: 2 additions & 3 deletions tests/unit/datacosmos/client/test_client_initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@
@patch("os.path.exists", return_value=False)
@patch("config.Config.from_env")
def test_client_initialization(mock_from_env, mock_exists, mock_auth_client):
"""
Test that the client initializes correctly with environment variables and mocks the HTTP client.
"""
"""Test that the client initializes correctly with environment variables
and mocks the HTTP client."""
mock_config = Config(
client_id="test-client-id",
client_secret="test-client-secret",
Expand Down
7 changes: 3 additions & 4 deletions tests/unit/datacosmos/client/test_client_post_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@

@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")

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

View workflow job for this annotation

GitHub Actions / Flake8

tests/unit/datacosmos/client/test_client_post_request.py#L7

Line too long (80 > 79 characters) (E501)
def test_post_request(mock_auth_client):
"""
Test that the client performs a POST request correctly.
"""
"""Test that the client performs a POST request correctly."""
# Mock the HTTP client
mock_http_client = MagicMock()
mock_response = MagicMock()
Expand All @@ -24,7 +22,8 @@ def test_post_request(mock_auth_client):
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
Expand Down
4 changes: 1 addition & 3 deletions tests/unit/datacosmos/client/test_client_put_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@

@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")

Check failure on line 7 in tests/unit/datacosmos/client/test_client_put_request.py

View workflow job for this annotation

GitHub Actions / Flake8

tests/unit/datacosmos/client/test_client_put_request.py#L7

Line too long (80 > 79 characters) (E501)
def test_put_request(mock_auth_client):
"""
Test that the client performs a PUT request correctly.
"""
"""Test that the client performs a PUT request correctly."""
# Mock the HTTP client
mock_http_client = MagicMock()
mock_response = MagicMock()
Expand Down
4 changes: 1 addition & 3 deletions tests/unit/datacosmos/client/test_client_token_refreshing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@

@patch("datacosmos.client.DatacosmosClient._authenticate_and_initialize_client")

Check failure on line 8 in tests/unit/datacosmos/client/test_client_token_refreshing.py

View workflow job for this annotation

GitHub Actions / Flake8

tests/unit/datacosmos/client/test_client_token_refreshing.py#L8

Line too long (80 > 79 characters) (E501)
def test_client_token_refreshing(mock_auth_client):
"""
Test that the client refreshes the token when it expires.
"""
"""Test that the client refreshes the token when it expires."""
# Mock the HTTP client returned by _authenticate_and_initialize_client
mock_http_client = MagicMock()
mock_response = MagicMock()
Expand Down

0 comments on commit 1e40bd6

Please sign in to comment.