From 8417dbf15432357b1892e13f1be320c10cba0db5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20H=C3=B6nig?= Date: Thu, 4 Jan 2018 15:28:36 +0100 Subject: [PATCH] weather bot: Quit bot on invalid API key. --- zulip_bots/zulip_bots/bots/weather/test_weather.py | 7 +++++-- zulip_bots/zulip_bots/bots/weather/weather.py | 6 +++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/zulip_bots/zulip_bots/bots/weather/test_weather.py b/zulip_bots/zulip_bots/bots/weather/test_weather.py index 7b42bb1..a338339 100644 --- a/zulip_bots/zulip_bots/bots/weather/test_weather.py +++ b/zulip_bots/zulip_bots/bots/weather/test_weather.py @@ -1,3 +1,4 @@ +from unittest.mock import patch from zulip_bots.test_lib import BotTestCase from typing import Optional @@ -25,7 +26,8 @@ class TestWeatherBot(BotTestCase): # Override default function in BotTestCase 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: @@ -46,4 +48,5 @@ class TestWeatherBot(BotTestCase): self._test('fghjklasdfgh', bot_response, 'test_city_not_found') # help message - self._test('help', self.help_content) + with patch('requests.get'): + self._test('help', self.help_content) diff --git a/zulip_bots/zulip_bots/bots/weather/weather.py b/zulip_bots/zulip_bots/bots/weather/weather.py index 4151d8c..9df10c1 100644 --- a/zulip_bots/zulip_bots/bots/weather/weather.py +++ b/zulip_bots/zulip_bots/bots/weather/weather.py @@ -9,15 +9,15 @@ class WeatherHandler(object): def initialize(self, bot_handler: Any) -> None: self.api_key = bot_handler.get_config_info('weather')['key'] 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 test_response = requests.get(url) try: test_response_data = test_response.json() 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: pass