Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,12 @@ def default_location():
If no location specified in cli, find user's location
Make a GET request to the API endpoint
"""
response = requests.get("https://ipinfo.io/json", timeout=10)
try:
response = requests.get("https://ipinfo.io/json", timeout=10)
except requests.exceptions.Timeout:
return "No data"
except requests.exceptions.RequestException:
return "No data"
Comment on lines +53 to +58
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Catching Timeout before RequestException is redundant.

Since both exceptions are handled identically, you can just catch RequestException to simplify the code.

Suggested change
try:
response = requests.get("https://ipinfo.io/json", timeout=10)
except requests.exceptions.Timeout:
return "No data"
except requests.exceptions.RequestException:
return "No data"
try:
response = requests.get("https://ipinfo.io/json", timeout=10)
except requests.exceptions.RequestException:
return "No data"


if response.status_code == HTTPStatus.OK:
data = response.json()
Expand Down
21 changes: 18 additions & 3 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import pytest
from openmeteo_requests.Client import OpenMeteoRequestsError
from requests.exceptions import RequestException, Timeout

from src.api import (
default_location,
Expand All @@ -23,20 +24,31 @@
)
from src.helper import arguments_dictionary

HTTP_TIMEOUT = 999
HTTP_REQUEST_EXCEPTION = 998


@pytest.mark.parametrize(
("status_code", "json_data", "expected_result"),
("status_code", "json_data", "expected_result", "side_effect"),
[
(
HTTPStatus.OK,
{"loc": "43.03,-72.001", "city": "New York"},
["43.03", "-72.001", "New York"],
None,
),
(HTTPStatus.BAD_REQUEST, {}, "No data", None),
(HTTP_TIMEOUT, {}, "No data", Timeout("Test Timeout")),
(
HTTP_REQUEST_EXCEPTION,
{},
"No data",
RequestException("Test RequestException"),
),
(HTTPStatus.BAD_REQUEST, {}, "No data"),
],
)
def test_default_location_mocked(
mocker, status_code, json_data, expected_result
mocker, status_code, json_data, expected_result, side_effect
):
# Arrange: Mock the response from the API
mock_response = Mock()
Expand All @@ -46,6 +58,9 @@ def test_default_location_mocked(
# Mock the 'requests.get' method
mock_requests = mocker.patch("requests.get", return_value=mock_response)

# Set side effect
mock_requests.side_effect = side_effect

# Act: Call the function
result = default_location()

Expand Down