Exemple #1
0
async def test_connect_clients():
    bot = MockBot()
    conn = MockConn()
    bot.connections = {"foo": conn}
    future = bot.loop.create_future()
    future.set_result(True)
    conn.try_connect.return_value = future
    bot.plugin_manager.load_all = load_mock = MagicMock()
    load_mock.return_value = future
    await CloudBot._init_routine(bot)
    assert load_mock.mock_calls == [call(str(bot.base_dir / "plugins"))]
    conn.try_connect.assert_called()
Exemple #2
0
    async def test_conn_not_ready(self, mock_db, setup_db, refresh_mods, freeze_time):
        bot = MockBot({})
        mock_conn = MagicMock()
        mock_conn.name = "test"
        mock_conn.ready = False
        bot.connections = {mock_conn.name: mock_conn}

        await self.check_reminders(mock_db, bot)

        assert mock_conn.message.mock_calls == []

        assert mock_db.get_data(remind.table) == [
            ('test', 'user', self.set_time, '#chan', 'a reminder', self.remind_time)
        ]
Exemple #3
0
    async def test_normal(self, mock_db, setup_db, refresh_mods, freeze_time):
        bot = MockBot({})
        mock_conn = MagicMock()
        mock_conn.name = "test"
        mock_conn.ready = True
        bot.connections = {mock_conn.name: mock_conn}

        await self.check_reminders(mock_db, bot)

        assert mock_conn.message.mock_calls == [
            call('user', 'user, you have a reminder from \x0260 minutes\x0f ago!'),
            call('user', '"a reminder"'),
        ]

        assert mock_db.get_data(remind.table) == []
Exemple #4
0
    async def test_command(self) -> None:
        bot = MockBot()
        conn = MockConn(nick="bot")
        event = Event(
            irc_command="PRIVMSG",
            event_type=EventType.message,
            channel="#foo",
            nick="bar",
            conn=conn,
            content=".foo bar",
        )
        event.notice = MagicMock()
        plugin = MagicMock()

        run_hooks = []

        @hook.command("foo")
        async def coro(hook):
            run_hooks.append(hook)

        full_hook = CommandHook(plugin, hook._get_hook(coro, "command"))

        for cmd in full_hook.aliases:
            bot.plugin_manager.commands[cmd] = full_hook

        await CloudBot.process(bot, event)
        assert sorted(run_hooks, key=id) == sorted(
            [
                full_hook,
            ],
            key=id,
        )
Exemple #5
0
    async def test_irc_catch_all(self) -> None:
        bot = MockBot()
        conn = MockConn(nick="bot")
        event = Event(
            irc_command="PRIVMSG",
            event_type=EventType.message,
            channel="#foo",
            nick="bar",
            conn=conn,
            content=".foo bar",
        )
        event.notice = MagicMock()
        plugin = MagicMock()

        run_hooks = []

        @hook.irc_raw("*")
        async def coro(hook):
            run_hooks.append(hook)

        full_hook = RawHook(plugin, hook._get_hook(coro, "irc_raw"))
        bot.plugin_manager.catch_all_triggers.append(full_hook)

        await CloudBot.process(bot, event)
        assert sorted(run_hooks, key=id) == sorted(
            [
                full_hook,
            ],
            key=id,
        )
Exemple #6
0
    async def test_event(self) -> None:
        bot = MockBot()
        conn = MockConn(nick="bot")
        event = Event(
            irc_command="PRIVMSG",
            event_type=EventType.message,
            channel="#foo",
            nick="bar",
            conn=conn,
            content=".foo bar",
        )
        event.notice = MagicMock()
        plugin = MagicMock()

        run_hooks = []

        @hook.event(EventType.message)
        async def coro(hook):
            run_hooks.append(hook)

        full_event_hook = EventHook(plugin, hook._get_hook(coro, "event"))
        for event_type in full_event_hook.types:
            bot.plugin_manager.event_type_hooks[event_type].append(
                full_event_hook)

        await CloudBot.process(bot, event)
        assert sorted(run_hooks, key=id) == sorted(
            [
                full_event_hook,
            ],
            key=id,
        )
Exemple #7
0
    async def test_command_partial(self) -> None:
        bot = MockBot()
        conn = MockConn(nick="bot")
        event = Event(
            irc_command="PRIVMSG",
            event_type=EventType.message,
            channel="#foo",
            nick="bar",
            conn=conn,
            content=".foo bar",
        )
        event.notice = MagicMock()
        plugin = MagicMock()

        run_hooks = []

        @hook.command("foob", "fooc")
        async def coro(hook):  # pragma: no cover
            run_hooks.append(hook)

        full_hook = CommandHook(plugin, hook._get_hook(coro, "command"))

        for cmd in full_hook.aliases:
            bot.plugin_manager.commands[cmd] = full_hook

        await CloudBot.process(bot, event)
        assert sorted(run_hooks, key=id) == sorted(
            [],
            key=id,
        )

        event.notice.assert_called_once_with("Possible matches: foob or fooc")
def test_invite_join():
    bot = MockBot()
    conn = MockIrcClient(
        bot, "fooconn", "foo", {"connection": {"server": "host.invalid"}}
    )
    core_misc.invite(ParamList("foo", "#bar"), conn)

    assert conn.send.mock_calls == [call("JOIN #bar")]
Exemple #9
0
def test_save(tmp_path):
    config_file = tmp_path / "config.json"
    config_file.write_text("{}", encoding="utf-8")
    bot = MockBot()
    config = Config(bot, filename=str(config_file))
    config["foo"] = "bar"
    config.save_config()

    assert config_file.read_text(encoding="utf-8") == '{\n    "foo": "bar"\n}'
    async def test_reload_not_running(self, tmp_path):
        config_file = tmp_path / "config.json"
        config_file.touch()
        bot = MockBot()
        reloader = ConfigReloader(bot)
        bot.running = False
        with patch.object(bot, "reload_config", create=True) as mocked:
            future = bot.loop.create_future()
            future.set_result(True)

            async def coro():  # pragma: no cover
                await future

            mocked.return_value = coro()

            await bot.loop.run_in_executor(None, reloader.reload,
                                           str(config_file))

            assert mocked.mock_calls == []
def test_invite_join_disabled():
    bot = MockBot()
    conn = MockIrcClient(
        bot,
        "fooconn",
        "foo",
        {"connection": {"server": "host.invalid"}, "invite_join": False},
    )
    core_misc.invite(ParamList("foo", "#bar"), conn)

    assert conn.send.mock_calls == []
Exemple #12
0
    async def test_late(self, mock_db, setup_db, refresh_mods, freeze_time):
        bot = MockBot({})
        mock_conn = MagicMock()
        mock_conn.name = "test"
        mock_conn.ready = True
        bot.connections = {mock_conn.name: mock_conn}

        with self.set_delay(40 * minute):
            await self.check_reminders(mock_db, bot)

        assert mock_conn.message.mock_calls == [
            call('user', 'user, you have a reminder from \x0260 minutes\x0f ago!'),
            call('user', '"a reminder"'),
            call(
                'user',
                "(I'm sorry for delivering this message \x0245 minutes\x0f late, "
                "it seems I was unable to deliver it on time)",
            ),
        ]

        assert mock_db.get_data(remind.table) == []
def make_conn():
    bot = MockBot()
    conn = MockIrcClient(
        bot,
        "conn",
        "foobot",
        config={
            "connection": {
                "server": "host.invalid",
            },
        },
    )
    return conn
Exemple #14
0
async def test_reload_config():
    bot = MockBot()
    conn = MockConn()
    bot.connections = {"foo": conn}
    bot.config.load_config = MagicMock()
    runs = []

    @hook.config()
    @hook.config()
    async def coro(hook):
        runs.append(hook)

    plugin = MagicMock()
    config_hook = ConfigHook(plugin, hook._get_hook(coro, "config"))

    bot.plugin_manager.config_hooks.append(config_hook)

    bot.config.load_config.assert_not_called()
    await CloudBot.reload_config(bot)
    conn.reload.assert_called()
    bot.config.load_config.assert_called()
    assert runs == [config_hook]
Exemple #15
0
def test_missing_config(tmp_path, capsys, mock_sleep):
    config_file = tmp_path / "config.json"
    bot = MockBot()
    with pytest.raises(SystemExit):
        Config(bot, filename=str(config_file))

    data = capsys.readouterr()
    assert data.out == ("No config file found! Bot shutting down in five "
                        "seconds.\n"
                        "Copy 'config.default.json' to "
                        "'config.json' for defaults.\n"
                        "For help, "
                        "see htps://github.com/TotallyNotRobots/CloudBot. "
                        "Thank you for "
                        "using CloudBot!\n")
Exemple #16
0
def test_no_results(mock_requests, unset_bot):
    from cloudbot.bot import bot

    bot.set(MockBot({"api_keys": {"brewerydb": "APIKEY"}}))
    mock_requests.add(
        'GET',
        'http://api.brewerydb.com/v2/search'
        '?format=json&key=APIKEY&type=beer&withBreweries=Y&q=some+text',
        match_querystring=True,
        json={"totalResults": 0},
    )
    from plugins import brew

    reply = MagicMock()
    result = brew.brew('some text', reply)

    reply.assert_not_called()

    assert result == 'No results found.'
    async def test_reload_no_path(self, tmp_path):
        plugin_dir = tmp_path / "plugins"
        plugin_dir.mkdir()
        plugin_file = plugin_dir / "plugin.py"
        bot = MockBot()
        reloader = PluginReloader(bot)
        with patch.object(reloader, "_reload") as mocked:
            future = bot.loop.create_future()
            future.set_result(True)

            async def coro():  # pragma: no cover
                await future

            mocked.return_value = coro()

            await bot.loop.run_in_executor(None, reloader.reload,
                                           str(plugin_file))

            assert mocked.mock_calls == []
Exemple #18
0
    async def test_irc_raw_block(self):
        bot = MockBot()
        conn = MockConn(nick="bot")
        event = Event(
            irc_command="PRIVMSG",
            event_type=EventType.message,
            channel="#foo",
            nick="bar",
            conn=conn,
            content=".foo bar",
        )
        event.notice = MagicMock()
        plugin = MagicMock()

        run_hooks = []

        @hook.irc_raw("PRIVMSG",
                      priority=Priority.HIGH,
                      action=Action.HALTTYPE)
        async def coro(hook):
            run_hooks.append(hook)

        @hook.irc_raw("PRIVMSG", priority=Priority.NORMAL)
        async def coro1(hook):  # pragma: no cover
            run_hooks.append(hook)

        full_hook = RawHook(plugin, hook._get_hook(coro, "irc_raw"))
        full_hook1 = RawHook(plugin, hook._get_hook(coro1, "irc_raw"))
        bot.plugin_manager.raw_triggers["PRIVMSG"].append(full_hook)
        bot.plugin_manager.raw_triggers["PRIVMSG"].append(full_hook1)

        await CloudBot.process(bot, event)
        assert sorted(run_hooks, key=id) == sorted(
            [
                full_hook,
            ],
            key=id,
        )
Exemple #19
0
def setup_api(unset_bot, mock_requests):
    from cloudbot.bot import bot

    bot.set(
        MockBot({
            "api_keys": {
                "spotify_client_id": "APIKEY",
                "spotify_client_secret": "APIKEY",
            }
        }))
    mock_requests.add(
        "POST",
        "https://accounts.spotify.com/api/token",
        json={
            "access_token": "foo",
            "expires_in": 3600
        },
    )
    from plugins import spotify
    importlib.reload(spotify)
    spotify.set_keys()

    yield