Skip to content

Commit

Permalink
Merge d17133a into ad79a5a
Browse files Browse the repository at this point in the history
  • Loading branch information
Hhamid1991 committed Sep 18, 2020
2 parents ad79a5a + d17133a commit 770fd30
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
39 changes: 39 additions & 0 deletions sunrise/actions.py
@@ -1,5 +1,7 @@
import re
import abc
import requests
import json


class Action(metaclass=abc.ABCMeta):
Expand All @@ -26,6 +28,37 @@ def execute(self):
return str(eval(self.operator.join(self.numbers)))


class Weather(Action):
parameters = ['temp', 'humidity', 'pressure']

def __init__(self, parameter, city):
self.parameter = {
'temperture': 'temp',
}[parameter] if parameter not in self.parameters else parameter
self.city = city

def execute(self):
# Enter your API key here
api_key = "fa313a7fbbcd1bc409691eed433355a9"
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = self.city
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
# get method of requests module
# return response object
weather_request = requests.get(complete_url)
weather_response = weather_request.json()
# Now weather_response contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if weather_response["cod"] != "404":
main_data = weather_response["main"]
return main_data[self.parameter]
else:
return 'city not found'


patterns = [
(
re.compile(r'(?P<a>\d+)\s*(?P<operator>[-+/*])\s*(?P<b>\d+)'),
Expand Down Expand Up @@ -55,6 +88,12 @@ def execute(self):
),
Calculator
),
(
re.compile(
r'.*(?P<parameter>temp|humidity|pressure).*(?P<city>tehran).*'
),
Weather
),
]


Expand Down
Binary file added tests/.test_weather.py.swn
Binary file not shown.
29 changes: 29 additions & 0 deletions tests/test_weather.py
@@ -0,0 +1,29 @@
from sunrise import do
import requests, json
import pytest


@pytest.fixture
def weather_fixture():
api_key = "fa313a7fbbcd1bc409691eed433355a9"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = "tehran"
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
weather_request = requests.get(complete_url)
weather_response = weather_request.json()
if weather_response["cod"] != "404":
main_data = weather_response["main"]
return [
main_data["temp"],
main_data["humidity"],
main_data["pressure"],
]
else:
return "City not found."


def test_weather(weather_fixture):
assert weather_fixture[0] == do('temp of tehran')
assert weather_fixture[1] == do('humidity of tehran')
assert weather_fixture[2] == do('pressure of tehran')

0 comments on commit 770fd30

Please sign in to comment.