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
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
# simple_api_call
# 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.
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pytest==8.3.3
requests==2.32.3
38 changes: 38 additions & 0 deletions test_weather.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 14 additions & 0 deletions weather.py
Original file line number Diff line number Diff line change
@@ -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)