Example #1
0
    def assert_bot_server_response(
        self,
        available_bots: Optional[List[str]]=None,
        bots_config: Optional[Dict[str, Dict[str, str]]]=None,
        bot_handlers: Optional[Dict[str, Any]]=None,
        payload_url: str="/bots/helloworld",
        message: Optional[Dict[str, Any]]=dict(message={'key': "test message"}),
        check_success: bool=False,
        third_party_bot_conf: Optional[configparser.ConfigParser]=None,
    ) -> None:
        if available_bots is not None and bots_config is not None:
            bots_lib_modules = server.load_lib_modules(available_bots)
            server.app.config["BOTS_LIB_MODULES"] = bots_lib_modules
            if bot_handlers is None:
                bot_handlers = server.load_bot_handlers(available_bots, bots_config, third_party_bot_conf)
            message_handlers = server.init_message_handlers(available_bots, bots_lib_modules, bot_handlers)
            server.app.config["BOT_HANDLERS"] = bot_handlers
            server.app.config["MESSAGE_HANDLERS"] = message_handlers

        response = self.app.post(payload_url, data=json.dumps(message))

        if check_success:
            assert 200 <= response.status_code < 300
        else:
            assert 400 <= response.status_code < 500
Example #2
0
    def test_load_lib_modules(self) -> None:
        # This testcase requires hardcoded paths, which here is a good thing so if we ever
        # restructure zulip_bots, this test would fail and we would also update Botserver
        # at the same time.
        helloworld = import_module(
            "zulip_bots.bots.{bot}.{bot}".format(bot="helloworld"))
        root_dir = Path(__file__).parents[2].as_posix()
        # load valid module name
        module = server.load_lib_modules(["helloworld"])["helloworld"]
        assert module == helloworld

        # load valid file path
        path = Path(
            root_dir, "zulip_bots/zulip_bots/bots/{bot}/{bot}.py".format(
                bot="helloworld")).as_posix()
        module = server.load_lib_modules([path])[path]
        assert module.__name__ == "custom_bot_module"
        assert module.__file__ == path
        assert isinstance(module, ModuleType)

        # load invalid module name
        with self.assertRaisesRegex(
                SystemExit,
                'Error: Bot "botserver-test-case-random-bot" doesn\'t exist. '
                "Please make sure you have set up the botserverrc file correctly.",
        ):
            module = server.load_lib_modules([
                "botserver-test-case-random-bot"
            ])["botserver-test-case-random-bot"]

        # load invalid file path
        with self.assertRaisesRegex(
                SystemExit,
                'Error: Bot "{}/zulip_bots/zulip_bots/bots/helloworld.py" doesn\'t exist. '
                "Please make sure you have set up the botserverrc file correctly."
                .format(root_dir),
        ):
            path = Path(
                root_dir, "zulip_bots/zulip_bots/bots/{bot}.py".format(
                    bot="helloworld")).as_posix()
            module = server.load_lib_modules([path])[path]
    def test_load_lib_modules(self) -> None:
        # This testcase requires hardcoded paths, which here is a good thing so if we ever
        # restructure zulip_bots, this test would fail and we would also update Botserver
        # at the same time.
        helloworld = import_module(
            'zulip_bots.bots.{bot}.{bot}'.format(bot='helloworld'))
        root_dir = os.path.normpath(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../'))
        # load valid module name
        module = server.load_lib_modules(['helloworld'])['helloworld']
        assert module == helloworld

        # load valid file path
        path = os.path.join(
            root_dir, 'zulip_bots/zulip_bots/bots/{bot}/{bot}.py'.format(
                bot='helloworld'))
        module = server.load_lib_modules([path])[path]
        assert module.__name__ == 'custom_bot_module'
        assert module.__file__ == path
        assert isinstance(module, ModuleType)

        # load invalid module name
        with self.assertRaisesRegexp(
                SystemExit,  # type: ignore
                'Error: Bot "botserver-test-case-random-bot" doesn\'t exist. '
                'Please make sure you have set up the botserverrc file correctly.'
        ):
            module = server.load_lib_modules([
                'botserver-test-case-random-bot'
            ])['botserver-test-case-random-bot']

        # load invalid file path
        with self.assertRaisesRegexp(
                SystemExit,  # type: ignore
                'Error: Bot "{}/zulip_bots/zulip_bots/bots/helloworld.py" doesn\'t exist. '
                'Please make sure you have set up the botserverrc file correctly.'
                .format(root_dir)):
            path = os.path.join(
                root_dir,
                'zulip_bots/zulip_bots/bots/{bot}.py'.format(bot='helloworld'))
            module = server.load_lib_modules([path])[path]
    def assert_bot_server_response(
        self,
        mock_ExternalBotHandler: mock.Mock,
        available_bots: Optional[List[str]] = None,
        bots_config: Optional[Dict[str, Dict[str, str]]] = None,
        bot_handlers: Optional[Dict[str, Any]] = None,
        event: Optional[Dict[str, Any]] = None,
        expected_response: Optional[str] = None,
        check_success: bool = False,
        third_party_bot_conf: Optional[configparser.ConfigParser] = None,
    ) -> None:
        if available_bots is not None and bots_config is not None:
            server.bots_config = bots_config
            bots_lib_modules = server.load_lib_modules(available_bots)
            server.app.config["BOTS_LIB_MODULES"] = bots_lib_modules
            if bot_handlers is None:
                bot_handlers = server.load_bot_handlers(
                    available_bots, bots_lib_modules, bots_config,
                    third_party_bot_conf)
            message_handlers = server.init_message_handlers(
                available_bots, bots_lib_modules, bot_handlers)
            server.app.config["BOT_HANDLERS"] = bot_handlers
            server.app.config["MESSAGE_HANDLERS"] = message_handlers

        mock_ExternalBotHandler.return_value.full_name = "test"
        response = self.app.post(data=json.dumps(event))

        # NOTE: Currently, assert_bot_server_response can only check the expected_response
        # for bots that use send_reply. However, the vast majority of bots use send_reply.
        # Therefore, the Botserver can be still be effectively tested.
        bot_send_reply_call = mock_ExternalBotHandler.return_value.send_reply
        if expected_response is not None:
            self.assertTrue(bot_send_reply_call.called)
            self.assertEqual(expected_response,
                             bot_send_reply_call.call_args[0][1])
        else:
            self.assertFalse(bot_send_reply_call.called)

        if check_success:
            assert 200 <= response.status_code < 300
        else:
            assert 400 <= response.status_code < 500
    def assert_bot_server_response(
        self,
        mock_ExternalBotHandler: mock.Mock,
        available_bots: Optional[List[str]]=None,
        bots_config: Optional[Dict[str, Dict[str, str]]]=None,
        bot_handlers: Optional[Dict[str, Any]]=None,
        event: Optional[Dict[str, Any]]=None,
        expected_response: Optional[str]=None,
        check_success: bool=False,
        third_party_bot_conf: Optional[configparser.ConfigParser]=None,
    ) -> None:
        if available_bots is not None and bots_config is not None:
            server.bots_config = bots_config
            bots_lib_modules = server.load_lib_modules(available_bots)
            server.app.config["BOTS_LIB_MODULES"] = bots_lib_modules
            if bot_handlers is None:
                bot_handlers = server.load_bot_handlers(available_bots, bots_config, third_party_bot_conf)
            message_handlers = server.init_message_handlers(available_bots, bots_lib_modules, bot_handlers)
            server.app.config["BOT_HANDLERS"] = bot_handlers
            server.app.config["MESSAGE_HANDLERS"] = message_handlers

        mock_ExternalBotHandler.return_value.full_name = "test"
        response = self.app.post(data=json.dumps(event))

        # NOTE: Currently, assert_bot_server_response can only check the expected_response
        # for bots that use send_reply. However, the vast majority of bots use send_reply.
        # Therefore, the Botserver can be still be effectively tested.
        bot_send_reply_call = mock_ExternalBotHandler.return_value.send_reply
        if expected_response is not None:
            self.assertTrue(bot_send_reply_call.called)
            self.assertEqual(expected_response, bot_send_reply_call.call_args[0][1])
        else:
            self.assertFalse(bot_send_reply_call.called)

        if check_success:
            assert 200 <= response.status_code < 300
        else:
            assert 400 <= response.status_code < 500