Skip to content

Commit

Permalink
update httpClient and tests for it
Browse files Browse the repository at this point in the history
  • Loading branch information
Fernando Aureliano da Silva Maia committed Oct 20, 2023
1 parent f588bd4 commit 6b8711e
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# vim: set filetype=python ts=4 sw=4
# -*- coding: utf-8 -*-
import pytest
from requests import RequestException
from tokendito import __title__
from tokendito import __version__
from tokendito.http_client import HTTPClient
Expand Down Expand Up @@ -58,3 +59,32 @@ def test_custom_header(client):

# Assert that the custom header was correctly sent
assert json_data["headers"]["X-Test-Header"] == "TestValue"


def test_bad_get_request(client, mocker):
"""Test GET request failure scenario."""
mocker.patch("requests.Session.get", side_effect=RequestException("An error occurred"))
with pytest.raises(SystemExit):
client.get("https://httpbin.org/get")


def test_bad_post_request(client, mocker):
"""Test POST request failure scenario."""
mocker.patch("requests.Session.post", side_effect=RequestException("An error occurred"))
with pytest.raises(SystemExit):
client.post("https://httpbin.org/post", json={"key": "value"})


def test_reset_session(client):
"""Test the reset method to ensure session is reset."""
# Set a test cookie for the client
client.set_cookies({"test_cookie": "cookie_value"})
# Reset the session
client.reset()

# Make a request to the /cookies endpoint of httpbin which returns set cookies
response = client.get("https://httpbin.org/cookies")
json_data = response.json()

# Assert that the cookies have been cleared
assert json_data["cookies"] == {}
42 changes: 42 additions & 0 deletions tests/unit/test_http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,45 @@ def test_post(client, mocker):
# Check if the response status code and text match the expected values
assert response.status_code == 201
assert response.text == "Created"


def test_get_failure(client, mocker):
"""Test GET request failure scenario."""
mock_get = mocker.patch("requests.Session.get")
mock_get.side_effect = requests.RequestException("Failed to connect")

with pytest.raises(SystemExit):
client.get("http://test.com")


def test_post_failure(client, mocker):
"""Test POST request failure scenario."""
mock_post = mocker.patch("requests.Session.post")
mock_post.side_effect = requests.RequestException("Failed to connect")

with pytest.raises(SystemExit):
client.post("http://test.com", json={"key": "value"})


def test_post_with_return_json(client, mocker):
"""Test POST request with return_json=True."""
mock_post = mocker.patch("requests.Session.post")
mock_resp = mocker.Mock()
mock_resp.status_code = 201
mock_resp.json.return_value = {"status": "Created"}
mock_post.return_value = mock_resp

response = client.post("http://test.com", json={"key": "value"}, return_json=True)
assert response == {"status": "Created"}


def test_reset(client):
"""Test the reset method."""
# Updating the session headers to check if they are reset later
client.session.headers.update({"Test-Header": "Test-Value"})

client.reset()

expected_user_agent = f"{__title__}/{__version__}"
assert "Test-Header" not in client.session.headers
assert client.session.headers["User-Agent"] == expected_user_agent
20 changes: 16 additions & 4 deletions tokendito/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def set_cookies(self, cookies):

def get(self, url, params=None, headers=None):
"""Perform a GET request."""
response = None
try:
logger.debug(f"Sending cookies: {self.session.cookies}")
logger.debug(f"Sending headers: {self.session.headers}")
Expand All @@ -36,19 +37,30 @@ def get(self, url, params=None, headers=None):
return response
except requests.RequestException as e:
logger.error(f"Error during GET request to {url}. Error: {e}")
logger.debug(f"Response Headers: {response.headers}")
logger.debug(f"Response Content: {response.content}")
if response:
logger.debug(f"Response Headers: {response.headers}")
logger.debug(f"Response Content: {response.content}")
else:
logger.debug("No response received")
sys.exit(1)

except Exception as err:
logger.error(f"The get request to {url} failed with {err}")
sys.exit(1)

def post(self, url, data=None, json=None, headers=None):
def post(self, url, data=None, json=None, headers=None, return_json=False):
"""Perform a POST request."""
try:
response = self.session.post(url, data=data, json=json, headers=headers)
response.raise_for_status()
return response
if return_json is True:
try:
return response.json()
except Exception as err:
logger.error(f"Problem with json response {err}")
sys.exit(1)
else:
return response
except requests.RequestException as e:
logger.error(f"Error during POST request to {url}. Error: {e}")
sys.exit(1)
Expand Down

0 comments on commit 6b8711e

Please sign in to comment.