zulip_botserver: Don't reinstantiate ExternalBotHandlers.

Fixes #147.
This commit is contained in:
derAnfaenger 2017-11-07 12:57:47 +01:00 committed by showell
parent e05ce661c5
commit bcc8bd7d38
3 changed files with 35 additions and 20 deletions

View file

@ -14,11 +14,12 @@ class BotServerTestCase(TestCase):
available_bots=None, available_bots=None,
bots_config=None, bots_config=None,
bots_lib_module=None, bots_lib_module=None,
bot_handlers=None,
payload_url="/bots/testbot", payload_url="/bots/testbot",
message=dict(message={'key': "test message"}), message=dict(message={'key': "test message"}),
check_success=False, check_success=False,
): ):
# type: (List[str], Dict[str, Any], Dict[str, Any], str, Dict[str, Dict[str, Any]], bool) -> None # type: (List[str], Dict[str, Any], Dict[str, Any], Dict[str, Any], str, Dict[str, Dict[str, Any]], bool) -> None
if available_bots is not None: if available_bots is not None:
zulip_botserver.server.available_bots = available_bots zulip_botserver.server.available_bots = available_bots
@ -29,6 +30,9 @@ class BotServerTestCase(TestCase):
if bots_lib_module is not None: if bots_lib_module is not None:
zulip_botserver.server.bots_lib_module = bots_lib_module zulip_botserver.server.bots_lib_module = bots_lib_module
if bot_handlers is not None:
zulip_botserver.server.bot_handlers = bot_handlers
response = self.app.post(payload_url, data=json.dumps(message)) response = self.app.post(payload_url, data=json.dumps(message))
if check_success: if check_success:

View file

@ -2,6 +2,8 @@ from __future__ import absolute_import
import mock import mock
import unittest import unittest
from typing import Any from typing import Any
from werkzeug.exceptions import BadRequest
from zulip_botserver import server
from .server_test_lib import BotServerTestCase from .server_test_lib import BotServerTestCase
class BotServerTests(BotServerTestCase): class BotServerTests(BotServerTestCase):
@ -29,11 +31,14 @@ class BotServerTests(BotServerTestCase):
bots_lib_module = { bots_lib_module = {
'testbot': BotServerTests.MockLibModule() 'testbot': BotServerTests.MockLibModule()
} }
bot_handlers = {
'testbot': mock_ExternalBotHandler()
}
self.assert_bot_server_response(available_bots=available_bots, self.assert_bot_server_response(available_bots=available_bots,
bots_config=bots_config, bots_config=bots_config,
bots_lib_module=bots_lib_module, bots_lib_module=bots_lib_module,
bot_handlers=bot_handlers,
check_success=True) check_success=True)
assert mock_ExternalBotHandler.called
def test_bot_module_not_exists(self): def test_bot_module_not_exists(self):
# type: () -> None # type: () -> None
@ -41,8 +46,9 @@ class BotServerTests(BotServerTestCase):
payload_url="/bots/not_supported_bot", payload_url="/bots/not_supported_bot",
check_success=False) check_success=False)
def test_wrong_bot_credentials(self): @mock.patch('logging.error')
# type: () -> None def test_wrong_bot_credentials(self, mock_LoggingError):
# type: (mock.Mock) -> None
available_bots = ['testbot'] available_bots = ['testbot']
bots_config = { bots_config = {
'testbot': { 'testbot': {
@ -51,9 +57,10 @@ class BotServerTests(BotServerTestCase):
'site': 'http://localhost', 'site': 'http://localhost',
} }
} }
self.assert_bot_server_response(available_bots=available_bots, server.available_bots = available_bots
bots_config=bots_config, server.load_bot_handlers()
check_success=False) mock_LoggingError.assert_called_with("Cannot fetch user profile, make sure you have set up the zuliprc file correctly.")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View file

@ -17,6 +17,7 @@ from zulip_bots.lib import ExternalBotHandler, StateHandler
bots_config = {} # type: Dict[str, Mapping[str, str]] bots_config = {} # type: Dict[str, Mapping[str, str]]
available_bots = [] # type: List[str] available_bots = [] # type: List[str]
bots_lib_module = {} # type: Dict[str, Any] bots_lib_module = {} # type: Dict[str, Any]
bot_handlers = {} # type: Dict[str, ExternalBotHandler]
def read_config_file(config_file_path): def read_config_file(config_file_path):
# type: (str) -> None # type: (str) -> None
@ -44,6 +45,20 @@ def load_lib_modules():
print("\n Import Error: Bot \"{}\" doesn't exists. Please make sure you have set up the flaskbotrc " print("\n Import Error: Bot \"{}\" doesn't exists. Please make sure you have set up the flaskbotrc "
"file correctly.\n".format(bot)) "file correctly.\n".format(bot))
def load_bot_handlers():
# type: () -> Any
for bot in available_bots:
client = Client(email=bots_config[bot]["email"],
api_key=bots_config[bot]["key"],
site=bots_config[bot]["site"])
try:
bot_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'bots', bot)
bot_handlers[bot] = ExternalBotHandler(client, bot_dir)
except SystemExit:
return BadRequest("Cannot fetch user profile for bot {}, make sure you have set up the flaskbotrc "
"file correctly.".format(bot))
def get_bot_lib_module(bot): def get_bot_lib_module(bot):
# type: (str) -> Any # type: (str) -> Any
if bot in bots_lib_module.keys(): if bot in bots_lib_module.keys():
@ -60,23 +75,11 @@ def handle_bot(bot):
return BadRequest("Can't find the configuration or Bot Handler code for bot {}. " return BadRequest("Can't find the configuration or Bot Handler code for bot {}. "
"Make sure that the `zulip_bots` package is installed, and " "Make sure that the `zulip_bots` package is installed, and "
"that your flaskbotrc is set up correctly".format(bot)) "that your flaskbotrc is set up correctly".format(bot))
client = Client(email=bots_config[bot]["email"],
api_key=bots_config[bot]["key"],
site=bots_config[bot]["site"])
try:
bot_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'bots', bot)
restricted_client = ExternalBotHandler(client, bot_dir)
except SystemExit:
return BadRequest("Cannot fetch user profile for bot {}, make sure you have set up the flaskbotrc "
"file correctly.".format(bot))
message_handler = lib_module.handler_class() message_handler = lib_module.handler_class()
event = request.get_json(force=True) event = request.get_json(force=True)
message_handler.handle_message(message=event["message"], message_handler.handle_message(message=event["message"],
bot_handler=restricted_client) bot_handler=bot_handlers[bot])
return json.dumps("") return json.dumps("")
def parse_args(): def parse_args():
@ -120,6 +123,7 @@ def main():
global available_bots global available_bots
available_bots = list(bots_config.keys()) available_bots = list(bots_config.keys())
load_lib_modules() load_lib_modules()
load_bot_handlers()
app.run(host=options.hostname, port=int(options.port), debug=True) app.run(host=options.hostname, port=int(options.port), debug=True)
if __name__ == '__main__': if __name__ == '__main__':