Skip to content

Commit

Permalink
Merge pull request #36 from devolo/session
Browse files Browse the repository at this point in the history
Use request sessions
  • Loading branch information
Markus Bong authored Dec 1, 2022
2 parents 7b09c90 + 7547d31 commit a4a5e8d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 20 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.3.1] - 2022/12/02

### Fixed

- Use request sessions to reduce overhead

## [2.3.0] - 2022/09/16

### Added
Expand Down
28 changes: 14 additions & 14 deletions adaptavist/adaptavist.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import requests
import requests_toolbelt
from requests.auth import HTTPBasicAuth

from ._helper import build_folder_names, get_executor, raise_on_kwargs_not_empty, update_field, update_multiline_field
from .const import PRIORITY_NORMAL, STATUS_APPROVED, STATUS_NOT_EXECUTED, STEP_TYPE_BY_STEP, TEST_CASE, TEST_PLAN, TEST_RUN
Expand All @@ -26,11 +27,16 @@ def __init__(self, jira_server: str, jira_username: str, jira_password: str):
self.jira_server = jira_server
self.jira_username = jira_username

self._session = requests.Session()
self._adaptavist_api_url = f"{self.jira_server}/rest/atm/1.0"
self._authentication = requests.auth.HTTPBasicAuth(self.jira_username, jira_password)
self._headers = {"Accept": "application/json", "Content-type": "application/json"}
self._session.auth = HTTPBasicAuth(self.jira_username, jira_password)
self._session.headers.update({"Accept": "application/json", "Content-type": "application/json"})
self._logger = logging.getLogger(__name__)

def __del__(self):
"""Close session."""
self._session.close()

def get_users(self) -> List[str]:
"""
Get a list of users known to Adaptavist/Jira.
Expand Down Expand Up @@ -990,7 +996,7 @@ def add_test_script_attachment(
def _delete(self, request_url: str) -> Optional[requests.Response]:
"""DELETE data from Jira/Adaptavist."""
try:
request = requests.delete(request_url, auth=self._authentication, headers=self._headers, timeout=60)
request = self._session.delete(request_url, timeout=60)
request.raise_for_status()
except (
requests.exceptions.ConnectionError,
Expand All @@ -1004,7 +1010,7 @@ def _delete(self, request_url: str) -> Optional[requests.Response]:
def _get(self, request_url: str) -> Optional[requests.Response]:
"""GET data from Jira/Adaptavist."""
try:
request = requests.get(request_url, auth=self._authentication, headers=self._headers, timeout=60)
request = self._session.get(request_url, timeout=60)
request.raise_for_status()
except (
requests.exceptions.ConnectionError,
Expand All @@ -1018,9 +1024,7 @@ def _get(self, request_url: str) -> Optional[requests.Response]:
def _post(self, request_url: str, data: Any) -> Optional[requests.Response]:
"""POST data to Jira/Adaptavist."""
try:
request = requests.post(
request_url, auth=self._authentication, headers=self._headers, data=json.dumps(data), timeout=60
)
request = self._session.post(request_url, data=json.dumps(data), timeout=60)
request.raise_for_status()
except requests.exceptions.HTTPError as ex:
self._logger.error("request failed. %s %s", ex, request.text)
Expand All @@ -1033,9 +1037,7 @@ def _post(self, request_url: str, data: Any) -> Optional[requests.Response]:
def _put(self, request_url: str, data: Any) -> Optional[requests.Response]:
"""PUT data to Jira/Adaptavist."""
try:
request = requests.put(
request_url, auth=self._authentication, headers=self._headers, data=json.dumps(data), timeout=60
)
request = self._session.put(request_url, data=json.dumps(data), timeout=60)
request.raise_for_status()
except requests.exceptions.HTTPError as ex:
self._logger.error("request failed. %s %s", ex, request.text)
Expand All @@ -1049,17 +1051,15 @@ def _upload_file(self, request_url: str, attachment: BinaryIO, filename: str) ->
"""Upload file to Adaptavist."""
stream = requests_toolbelt.MultipartEncoder(fields={"file": (filename, attachment, "application/octet-stream")})
headers = {
**self._headers,
**self._session.headers,
"Content-type": stream.content_type,
"X-Atlassian-Token": "nocheck",
}

filename = filename or attachment.name

try:
request = requests.post(
request_url, auth=self._authentication, headers=headers, data=stream
) # pylint: disable=missing-timeout
request = self._session.post(request_url, headers=headers, data=stream) # pylint: disable=missing-timeout
request.raise_for_status()
except (
requests.exceptions.ConnectionError,
Expand Down
12 changes: 6 additions & 6 deletions tests/test_adaptavist.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ def test_add_test_result_attachment(self):

with patch("adaptavist.Adaptavist.get_test_result", return_value={"id": 123}), patch(
"builtins.open", mock_open()
), patch("requests_toolbelt.MultipartEncoder"), patch("requests.post"):
), patch("requests_toolbelt.MultipartEncoder"), patch("requests.Session.post"):
assert adaptavist.add_test_result_attachment(
test_run_key="JQA-R123", test_case_key="JQA-T123", attachment="testfile", filename="testfile"
)
Expand All @@ -550,7 +550,7 @@ def test_add_test_result_attachment(self):
# Test that we can handle IO objects
with patch("adaptavist.Adaptavist.get_test_result", return_value={"id": 123}), patch(
"requests_toolbelt.MultipartEncoder"
), patch("requests.post"):
), patch("requests.Session.post"):
attachment = BytesIO(b"Testdata")
attachment.name = "testdata.txt"
assert adaptavist.add_test_result_attachment(
Expand All @@ -563,7 +563,7 @@ def test_add_test_run_attachment(self):

with patch("adaptavist.Adaptavist.get_test_result", return_value={"id": 123}), patch(
"builtins.open", mock_open()
), patch("requests_toolbelt.MultipartEncoder"), patch("requests.post"):
), patch("requests_toolbelt.MultipartEncoder"), patch("requests.Session.post"):
assert adaptavist.add_test_run_attachment(test_run_key="JQA-R123", attachment="testfile", filename="testfile")

# Test that a file name is needed, if no file handle is given
Expand All @@ -573,7 +573,7 @@ def test_add_test_run_attachment(self):
# Test that we can handle IO objects
with patch("adaptavist.Adaptavist.get_test_result", return_value={"id": 123}), patch(
"requests_toolbelt.MultipartEncoder"
), patch("requests.post"):
), patch("requests.Session.post"):
attachment = BytesIO(b"Testdata")
attachment.name = "testdata.txt"
assert adaptavist.add_test_run_attachment(test_run_key="JQA-R123", attachment=attachment)
Expand Down Expand Up @@ -645,7 +645,7 @@ def test_add_test_script_attachment(self):

with patch("adaptavist.Adaptavist.get_test_result", return_value={"id": 123}), patch(
"builtins.open", mock_open()
), patch("requests_toolbelt.MultipartEncoder"), patch("requests.post"):
), patch("requests_toolbelt.MultipartEncoder"), patch("requests.Session.post"):
assert adaptavist.add_test_script_attachment(
test_run_key="JQA-R123", test_case_key="JQA-T123", step=1, attachment="testfile", filename="testfile"
)
Expand All @@ -659,7 +659,7 @@ def test_add_test_script_attachment(self):
# Test that we can handle IO objects
with patch("adaptavist.Adaptavist.get_test_result", return_value={"id": 123}), patch(
"requests_toolbelt.MultipartEncoder"
), patch("requests.post"):
), patch("requests.Session.post"):
attachment = BytesIO(b"Testdata")
attachment.name = "testdata.txt"
assert adaptavist.add_test_script_attachment(
Expand Down

0 comments on commit a4a5e8d

Please sign in to comment.