google_translate bot: Simplify API key check.

This commit is contained in:
Robert Hönig 2018-01-04 15:08:06 +01:00 committed by showell
parent b19c0f6e29
commit d11d31d795
3 changed files with 9 additions and 17 deletions

View file

@ -19,20 +19,12 @@ class GoogleTranslateHandler(object):
def initialize(self, bot_handler): def initialize(self, bot_handler):
self.config_info = bot_handler.get_config_info('googletranslate') self.config_info = bot_handler.get_config_info('googletranslate')
self.supported_languages = get_supported_languages(self.config_info['key']) # Retrieving the supported languages also serves as a check whether
query = {'key': self.config_info['key'], # the bot is properly connected to the Google Translate API.
'target': 'en'}
try: try:
data = requests.get(api_url + '/languages', params = query) self.supported_languages = get_supported_languages(self.config_info['key'])
except HTTPError as e: except TranslateError as e:
if (e.response.json()['error']['errors'][0]['reason'] == 'keyInvalid'): bot_handler.quit(str(e))
logging.error('Invalid key.'
'Follow the instructions in doc.md for setting API key.')
sys.exit(1)
else:
raise
except ConnectionError:
logging.warning('Bad connection')
def handle_message(self, message, bot_handler): def handle_message(self, message, bot_handler):
bot_response = get_translate_bot_response(message['content'], bot_response = get_translate_bot_response(message['content'],

View file

@ -1,7 +1,7 @@
from unittest.mock import patch from unittest.mock import patch
from requests.exceptions import ConnectionError from requests.exceptions import ConnectionError
from zulip_bots.test_lib import BotTestCase from zulip_bots.test_lib import BotTestCase, StubBotHandler
from zulip_bots.bots.google_translate.google_translate import TranslateError from zulip_bots.bots.google_translate.google_translate import TranslateError
help_text = ''' help_text = '''
@ -66,9 +66,9 @@ class TestGoogleTranslateBot(BotTestCase):
side_effect=Exception): side_effect=Exception):
self._test('"hello" de', 'Error. .', 'test_languages') self._test('"hello" de', 'Error. .', 'test_languages')
def test_get_language_403(self): def test_api_access_not_configured(self):
with self.assertRaises(TranslateError): with self.assertRaises(StubBotHandler.BotQuitException):
self._test(None, None, 'test_language_403') self._test(None, None, 'test_api_access_not_configured')
def test_connection_error(self): def test_connection_error(self):
with patch('requests.post', side_effect=ConnectionError()), \ with patch('requests.post', side_effect=ConnectionError()), \