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):
self.config_info = bot_handler.get_config_info('googletranslate')
self.supported_languages = get_supported_languages(self.config_info['key'])
query = {'key': self.config_info['key'],
'target': 'en'}
# Retrieving the supported languages also serves as a check whether
# the bot is properly connected to the Google Translate API.
try:
data = requests.get(api_url + '/languages', params = query)
except HTTPError as e:
if (e.response.json()['error']['errors'][0]['reason'] == 'keyInvalid'):
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')
self.supported_languages = get_supported_languages(self.config_info['key'])
except TranslateError as e:
bot_handler.quit(str(e))
def handle_message(self, message, bot_handler):
bot_response = get_translate_bot_response(message['content'],

View file

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