Skip to content

Commit

Permalink
feat: introduce retry mechanism for session
Browse files Browse the repository at this point in the history
  • Loading branch information
Sachin Shaji committed Apr 2, 2024
1 parent bfa224d commit 04e48d7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
15 changes: 14 additions & 1 deletion sw360/sw360_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from typing import Any, Dict, Optional

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

from .attachments import AttachmentsMixin
from .clearing import ClearingMixin
Expand All @@ -23,6 +25,17 @@
from .vendor import VendorMixin
from .vulnerabilities import VulnerabilitiesMixin

# Retry mechanism for rate limiting
adapter = HTTPAdapter(max_retries=Retry(
total=5,
status_forcelist=[429, 500, 502, 503, 504],
respect_retry_after_header=True,
backoff_factor=30,
allowed_methods=["HEAD", "GET", "OPTIONS", "POST", "PUT", "PATCH"]
))
session = requests.Session()
session.mount("http://", adapter)
session.mount("https://", adapter)

class SW360(
AttachmentsMixin,
Expand Down Expand Up @@ -75,7 +88,7 @@ def login_api(self, token: str = "") -> bool:
:raises SW360Error: if the login fails
"""
if not self.force_no_session:
self.session = requests.Session()
self.session = session
self.session.headers = self.api_headers.copy() # type: ignore

url = self.url + "resource/api/"
Expand Down
17 changes: 17 additions & 0 deletions tests/test_sw360_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,24 @@ def test_api_get_raw_error_string(self) -> None:
else:
self.assertEqual(404, context.exception.response.status_code)
self.assertEqual("Error-String", context.exception.response.text)

@responses.activate
def test_login_server_not_responding(self) -> None:
lib = SW360(self.MYURL, self.MYTOKEN, False)

responses.add(
responses.GET,
url=self.MYURL + "resource/api/",
body = '{"error": "Internal Server Error", "message": "An unexpected error occurred on the server."}',
status=500,
content_type="application/json",
adding_headers={"Authorization": "Token " + self.MYTOKEN},
)

with self.assertRaises(SW360Error) as context:
lib.login_api()

self.assertEqual(self.ERROR_MSG_NO_LOGIN, context.exception.message)

if __name__ == "__main__":
unittest.main()

0 comments on commit 04e48d7

Please sign in to comment.