weather bot: Quit bot on invalid API key.

This commit is contained in:
Robert Hönig 2018-01-04 15:28:36 +01:00 committed by showell
parent 28120784ff
commit 8417dbf154
2 changed files with 8 additions and 5 deletions

View file

@ -1,3 +1,4 @@
from unittest.mock import patch
from zulip_bots.test_lib import BotTestCase from zulip_bots.test_lib import BotTestCase
from typing import Optional from typing import Optional
@ -25,7 +26,8 @@ class TestWeatherBot(BotTestCase):
# Override default function in BotTestCase # Override default function in BotTestCase
def test_bot_responds_to_empty_message(self) -> None: def test_bot_responds_to_empty_message(self) -> None:
self._test('', self.help_content) with patch('requests.get'):
self._test('', self.help_content)
def test_bot(self) -> None: def test_bot(self) -> None:
@ -46,4 +48,5 @@ class TestWeatherBot(BotTestCase):
self._test('fghjklasdfgh', bot_response, 'test_city_not_found') self._test('fghjklasdfgh', bot_response, 'test_city_not_found')
# help message # help message
self._test('help', self.help_content) with patch('requests.get'):
self._test('help', self.help_content)

View file

@ -9,15 +9,15 @@ class WeatherHandler(object):
def initialize(self, bot_handler: Any) -> None: def initialize(self, bot_handler: Any) -> None:
self.api_key = bot_handler.get_config_info('weather')['key'] self.api_key = bot_handler.get_config_info('weather')['key']
self.response_pattern = 'Weather in {}, {}:\n{:.2f} F / {:.2f} C\n{}' self.response_pattern = 'Weather in {}, {}:\n{:.2f} F / {:.2f} C\n{}'
self.check_api_key() self.check_api_key(bot_handler)
def check_api_key(self) -> None: def check_api_key(self, bot_handler: Any) -> None:
url = 'http://api.openweathermap.org/data/2.5/weather?q=nyc&APPID=' + self.api_key url = 'http://api.openweathermap.org/data/2.5/weather?q=nyc&APPID=' + self.api_key
test_response = requests.get(url) test_response = requests.get(url)
try: try:
test_response_data = test_response.json() test_response_data = test_response.json()
if test_response_data['cod'] == 401: if test_response_data['cod'] == 401:
logging.error('API Key not valid. Please see doc.md to find out how to get it.') bot_handler.quit('API Key not valid. Please see doc.md to find out how to get it.')
except KeyError: except KeyError:
pass pass