Ejemplo n.º 1
0
    def test__language(self):
        for val in ["ru", "RU", "      en", "PT-br"]:
            instance = custom.Language(val)
            assert instance.check() and instance.cast() == val.strip().lower()
            assert instance.random_highlight
            assert instance.match("[{}] TEST TITLE".format(val.strip().upper()))

        for val in ["russian", "ID-JP", 123, "nonsense"]:
            assert not custom.Language(val).check()
            with pytest.raises(ValueError) as e:
                custom.Language(val).match("[DOES NOT] compute")
            assert "non-existent language" in str(e)
Ejemplo n.º 2
0
    async def test__wrap(self, storage):
        r = registry.Registry(storage.discord)

        for expected_error, payload in (
            ("empty sequence", []),
            ("incorrect sequence", ["test", "setting", "and-one-more"]),
            ("unknown setting", ["unknown", 1234]),
            ("unknown setting", [1234, 1234]),
            ("incorrect value abc for setting {}".format(custom.PinMessages.name), [custom.PinMessages.name, "abc"])
        ):
            with pytest.raises(ValueError) as exc:
                list(r.wrap(payload))
            assert expected_error in str(exc.value)

        payload = [
            custom.PinMessages.name, "True",
            custom.Language.name, "RU",
            custom.ReviewerRole.name, "<@&1234>",
        ]
        expected_result = [custom.PinMessages(True), custom.Language("ru"), custom.ReviewerRole(1234)]
        wrapped_payload = list(r.wrap(payload))
        assert len(wrapped_payload) == len(expected_result)
        for expected, wrapped in zip(expected_result, wrapped_payload):
            assert isinstance(wrapped, base.BaseSetting)
            assert wrapped.__class__ == expected.__class__
            assert wrapped.cast() == expected.cast()
Ejemplo n.º 3
0
    async def test__exception_handling_no_channel(self, client, storage,
                                                  existing_pulls, mocker,
                                                  codes_by_titles):
        monitor = github.MonitorPulls(client)

        p = next(
            iter(_ for _ in existing_pulls
                 if (codes_by_titles[_["title"]] and _["state"] == "open")))
        language = custom.Language(codes_by_titles[p["title"]])
        await client.settings.update(123, 1234, [language.name, language.code])
        storage.pulls.save_from_payload(p)
        pp = storage.pulls.by_number(p["number"])

        response = collections.namedtuple("Response",
                                          "status reason")(404,
                                                           "testing stuff")
        client.fetch_channel = mocker.AsyncMock(
            side_effect=discord_errors.NotFound(response, "error"))
        client.settings.reset = mocker.AsyncMock()
        client.storage.discord.delete_channel_messages = mocker.Mock()
        await monitor.sort_for_updates([pp])

        client.settings.reset.assert_called()
        client.storage.discord.delete_channel_messages.assert_called()
        args, _ = client.settings.reset.call_args
        assert args == (123, )
Ejemplo n.º 4
0
    async def __sort_for_updates_prepare(self,
                                         client,
                                         storage,
                                         existing_pulls,
                                         mocker,
                                         codes_by_titles,
                                         channel_ids,
                                         guild_id,
                                         save_pull,
                                         pull_state,
                                         raise_exc=False):
        monitor = github.MonitorPulls(client)

        def side_effect(channel_id, message_id, embed, content):
            if raise_exc:
                raise RuntimeError(self.exception_str)

            msg = mocker.Mock()
            msg.id = channel_id + 100
            msg.channel.id = channel_id
            return msg

        client.post_or_update = mocker.AsyncMock(side_effect=side_effect)
        client.pin = mocker.AsyncMock(side_effect=client.pin)
        client.unpin = mocker.AsyncMock(side_effect=client.unpin)

        monitor.update_pull_status = mocker.AsyncMock(
            side_effect=monitor.update_pull_status)

        p = next(
            iter(
                _ for _ in existing_pulls
                if (codes_by_titles[_["title"]] and _["state"] == pull_state)))
        language = custom.Language(codes_by_titles[p["title"]])

        for channel_id in channel_ids:
            await client.settings.update(channel_id, guild_id,
                                         [language.name, language.code])

        if save_pull:
            storage.pulls.save_from_payload(p)

        return p, monitor
Ejemplo n.º 5
0
    async def test__update_pull_status(self, client, existing_pulls, mocker,
                                       storage, language_code,
                                       reviewer_specified, pin_message,
                                       is_new_message, is_message_pinned,
                                       pull_state):
        monitor = github.MonitorPulls(client)
        p = pull.Pull(
            next(iter(_ for _ in existing_pulls if _["state"] == pull_state)))

        channel_id = 123
        message_id = 1234
        guild_id = 1
        reviewer_role = 12345

        if not is_new_message:
            message_model = discord.DiscordMessage(id=message_id,
                                                   channel_id=channel_id,
                                                   pull_number=p.number)
            storage.discord.save_messages(message_model)
        else:
            message_model = None

        settings = [custom.Language.name, language_code]
        if reviewer_specified:
            settings += [custom.ReviewerRole.name, reviewer_role]
        if pin_message:
            settings += [custom.PinMessages.name, pin_message]
        await client.settings.update(channel_id, guild_id, settings)

        message = mocker.Mock(
            id=message_id,
            pin=mocker.AsyncMock(),
            unpin=mocker.AsyncMock(),
            pinned=not is_new_message and is_message_pinned,
        )
        client.post_or_update = mocker.AsyncMock(return_value=message)
        client.pin = mocker.AsyncMock(side_effect=client.pin)
        client.unpin = mocker.AsyncMock(side_effect=client.unpin)

        formatters.PullFormatter.make_embed_for = mocker.Mock(
            side_effect=formatters.PullFormatter.make_embed_for)

        returned_message_model = await monitor.update_pull_status(
            p, channel_id, message_model=message_model)

        assert client.post_or_update.called
        post_kws = client.post_or_update.call_args.kwargs

        if message_model is None:
            assert post_kws["message_id"] is None

        if reviewer_specified:
            assert post_kws["content"].startswith(
                "<@&{}>, ".format(reviewer_role))

        assert any(post_kws["content"].endswith(hl)
                   for hl in custom.Language(language_code).highlights)

        assert formatters.PullFormatter.make_embed_for.called
        assert isinstance(post_kws["embed"], discord_py.Embed)

        if pull_state == formatters.PullState.OPEN.name:
            if pin_message:
                assert client.pin.called

            if message.pinned:
                assert not message.pin.called

            assert not message.unpin.called
            assert not client.unpin.called
        else:
            if pin_message:
                assert client.unpin.called
                if message.pinned:
                    assert message.unpin.called

            assert not message.pin.called
            assert not client.pin.called

        if is_new_message:
            assert isinstance(returned_message_model, discord.DiscordMessage)
            assert returned_message_model.id == message.id
        else:
            assert returned_message_model is None