diff --git a/README.md b/README.md index d2adf90..60006b9 100644 --- a/README.md +++ b/README.md @@ -1 +1,10 @@ -# simple_api_call \ No newline at end of file +# simple_api_call + +1. Write a Function to Make an API Call: + + You have a Python module called weather.py that includes a function get_weather() that fetches weather data from a hypothetical API. Tip: To make api calls in Python. Check how to use the "requests" library in python. + +2. Write Tests and Mock the API Call: +Create a test file called test_weather.py. In this file, you’ll the "requests.get" function so that no real HTTP request is made. + +Tip: Learn how to use unittest.mock and patch. A link has been attached for your reference. \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..53217ed --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +pytest==8.3.3 +requests==2.32.3 diff --git a/test_weather.py b/test_weather.py new file mode 100644 index 0000000..6b1758e --- /dev/null +++ b/test_weather.py @@ -0,0 +1,38 @@ +import pytest +import requests +from unittest.mock import patch +from weather import get_weather + + +mock_weather_data = { + "city": "New York", + "temperature": "20°C", + "description": "Clear sky" +} + + +@patch("weather.requests.get") +def test_get_weather_success(mock_get): + # Mock the API response to return the mock_weather_data + mock_get.return_value.status_code = 200 + mock_get.return_value.json.return_value = mock_weather_data + + city_name = "New York" + + result = get_weather(city_name) + + # Assert that the result matches the mock data + assert result == mock_weather_data + + +@patch("weather.requests.get") +def test_get_weather_failure(mock_get): + # Simulate a 404 error response + mock_get.return_value.status_code = 404 + mock_get.return_value.raise_for_status.side_effect = requests.exceptions.HTTPError() + + city_name = "UnknownCity" + + # Assert that the SystemExit exception is raised due to the error + with pytest.raises(SystemExit): + get_weather(city_name) \ No newline at end of file diff --git a/weather.py b/weather.py new file mode 100644 index 0000000..66feeb8 --- /dev/null +++ b/weather.py @@ -0,0 +1,14 @@ +import requests + + +def get_weather(city_name): + + base_url = "https://api.hypotheticalweather.com/weather" + params = {"q": city_name} + + try: + response = requests.get(base_url, params=params) + response.raise_for_status() + return response.json() + except requests.exceptions.RequestException as e: + raise SystemExit(e)