Skip to content

Commit 5ec437c

Browse files
committed
refactor(toggl): use requests.Session
pre-configure headers
1 parent 40e8be5 commit 5ec437c

File tree

2 files changed

+6
-6
lines changed

2 files changed

+6
-6
lines changed

compiler_admin/api/toggl.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ def __init__(self, api_token: str, workspace_id: int, **kwargs):
2424
self.headers = dict(Toggl.API_HEADERS)
2525
self.headers.update(self._authorization_header())
2626

27+
self.session = requests.Session()
28+
self.session.headers.update(self.headers)
2729
self.timeout = int(kwargs.get("timeout", 5))
2830

2931
@property
@@ -47,7 +49,7 @@ def _make_report_url(self, endpoint: str):
4749
"""
4850
return "/".join((Toggl.API_BASE_URL, Toggl.API_REPORTS_BASE_URL, self.workspace_url_fragment, endpoint))
4951

50-
def detailed_time_entries(self, start_date: datetime, end_date: datetime, **kwargs):
52+
def detailed_time_entries(self, start_date: datetime, end_date: datetime, **kwargs) -> requests.Response:
5153
"""Request a CSV report from Toggl of detailed time entries for the given date range.
5254
5355
Args:
@@ -104,7 +106,7 @@ def post_reports(self, endpoint: str, **kwargs) -> requests.Response:
104106
"""
105107
url = self._make_report_url(endpoint)
106108

107-
response = requests.post(url, json=kwargs, timeout=self.timeout)
109+
response = self.session.post(url, json=kwargs, timeout=self.timeout)
108110
response.raise_for_status()
109111

110112
return response

tests/api/test_toggl.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
@pytest.fixture
1111
def mock_requests(mocker):
12-
return mocker.patch(f"{MODULE}.requests")
12+
return mocker.patch(f"{MODULE}.requests.Session").return_value
1313

1414

1515
@pytest.fixture
@@ -63,9 +63,7 @@ def test_toggl_post_reports(mock_requests, toggl):
6363

6464
response.raise_for_status.assert_called_once()
6565

66-
mock_requests.post.assert_called_once_with(
67-
url, json=dict(kwarg1=1, kwarg2="two"), headers=toggl.headers, timeout=toggl.timeout
68-
)
66+
mock_requests.post.assert_called_once_with(url, json=dict(kwarg1=1, kwarg2="two"), timeout=toggl.timeout)
6967

7068

7169
def test_toggl_detailed_time_entries(toggl_mock_post_reports):

0 commit comments

Comments
 (0)