diff --git a/src/api.py b/src/api.py index 955f80d..34183a4 100644 --- a/src/api.py +++ b/src/api.py @@ -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" if response.status_code == HTTPStatus.OK: data = response.json() diff --git a/tests/test_api.py b/tests/test_api.py index b63d842..85d6132 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -9,6 +9,7 @@ import pytest from openmeteo_requests.Client import OpenMeteoRequestsError +from requests.exceptions import RequestException, Timeout from src.api import ( default_location, @@ -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() @@ -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()