Exemple #1
0
def test_happy_path():
    app = Kutana()

    # Simple echo plugin
    pl = Plugin("")

    @pl.on_messages()
    async def __(message, ctx):
        await ctx.reply(message.text)

    app.add_plugin(pl)

    # Simple debug backend
    debug = Debug(
        messages=[("message 1", 1), ("message 2", 2)],
        on_complete=app.stop,
    )

    app.add_backend(debug)

    # Run application
    app.run()

    # Check replies
    assert debug.answers[1] == [("message 1", (), {})]
    assert debug.answers[2] == [("message 2", (), {})]
Exemple #2
0
def test_incorrect_values():
    app = Kutana()

    with pytest.raises(ValueError):
        app.add_backend(None)

    with pytest.raises(ValueError):
        app.set_storage('permanent', None)

    with pytest.raises(ValueError):
        app.add_plugin(None)
Exemple #3
0
def test_same_plugins_and_backends():
    app = Kutana()

    plugin = Plugin("")
    backend = Debug([])

    app.add_plugin(plugin)
    with pytest.raises(RuntimeError):
        app.add_plugin(plugin)

    app.add_backend(backend)
    with pytest.raises(RuntimeError):
        app.add_backend(backend)

    assert app.get_backends() == [backend]
Exemple #4
0
def test_add_plugins():
    added = []

    app = Kutana()
    assert app.get_plugins() == []

    app.add_plugin = lambda pl: added.append(pl)
    app.add_plugins(["a", "b", "c"])
    assert added == ["a", "b", "c"]
Exemple #5
0
def test_happy_path(mock_post):
    group_change_settings_update = {
        "type": "group_change_settings",
        "object": {
            "changes": {
                "screen_name": {"old_value": "", "new_value": "sdffff23f23"},
                "title": {"old_value": "Спасибо", "new_value": "Спасибо 2"}
            }
        }
    }

    raw_updates = [
        {},
        {"type": "present"},
        group_change_settings_update,
        MESSAGES["not_message"],
        MESSAGES["message"],
        MESSAGES[".echo"],
        MESSAGES[".echo chat"],
        MESSAGES[".echo wa"],
    ]

    answers = []
    updated_longpoll = []

    def acquire_updates(content_type=None):
        if not raw_updates:
            return {"updates": [], "ts": "100"}
        if updated_longpoll == [1]:
            return {"failed": 3}
        return {"updates": [raw_updates.pop(0)], "ts": "0"}

    mock_post.return_value.__aenter__.return_value.json = CoroutineMock(
        side_effect=acquire_updates
    )

    class _VkontakteLongpoll(VkontakteLongpoll):
        async def _get_response(self, method, kwargs={}):
            if method == "groups.setLongPollSettings":
                return {"response": 1}

            if method == "groups.getById":
                return {
                    "response": [
                        {"id": 1, "name": "group", "screen_name": "grp"},
                    ],
                }

            if method == "groups.getLongPollServer":
                updated_longpoll.append(1)
                return {
                    "response": {
                        "server": "s",
                        "key": "k",
                        "ts": "1",
                    },
                }

            if method == "execute":
                answers.extend(kwargs["code"].split("API.")[1:])
                return {
                    "response": [1] * kwargs["code"].count("API."),
                }

            print(method, kwargs)

    app = Kutana()

    vkontakte = _VkontakteLongpoll(token="token")

    app.add_backend(vkontakte)

    echo_plugin = Plugin("echo")

    @echo_plugin.on_commands(["echo", "ec"])
    async def __(message, ctx):
        assert ctx.resolve_screen_name
        assert ctx.reply

        await ctx.reply(message.text, attachments=message.attachments)

    app.add_plugin(echo_plugin)

    app.get_loop().call_later(
        delay=vkontakte.api_request_pause * 4,
        callback=app.stop,
    )

    app.run()

    assert vkontakte.group_name == "Спасибо 2"
    assert vkontakte.group_screen_name == "sdffff23f23"

    assert len(updated_longpoll) == 2

    answers.sort()
    assert len(answers) == 3
    assert '{"message": ".echo chat [michaelkrukov|Михаил]",' in answers[0]
    assert '{"message": ".echo wa",' in answers[1]
    assert 'attachment": ""' not in answers[1]
    assert '{"message": ".echo",' in answers[2]
Exemple #6
0
def test_happy_path():
    updates = [
        MESSAGES["not_message"],
        MESSAGES["message"],
        MESSAGES[".echo"],
        MESSAGES[".echo chat"],
        MESSAGES["/echo@bot chat"],
        MESSAGES["/echo chat"],
        MESSAGES[".echo@bot chat"],
        MESSAGES["_image"],
    ]

    answers = []

    class _Telegram(Telegram):
        async def _request(self, method, kwargs={}):
            if method == "getMe":
                return {
                    "first_name": "te",
                    "last_name": "st",
                    "username": "******"
                }

            if method == "getUpdates":
                if not updates:
                    return []
                return [updates.pop(0)]

            if method == "sendMessage":
                answers.append(("msg", kwargs["text"]))
                return 1

            if method == "sendPhoto":
                answers.append(("image", kwargs["photo"]))
                return 1

            print(method, kwargs)

    app = Kutana()

    telegram = _Telegram(token="token")

    app.add_backend(telegram)

    echo_plugin = Plugin("echo")

    @echo_plugin.on_commands(["echo", "ec"])
    async def _(message, ctx):
        await ctx.reply(message.text)

    @echo_plugin.on_attachments(["image"])
    async def _(message, ctx):
        await ctx.reply(message.text, attachments=message.attachments[0])

    app.add_plugin(echo_plugin)

    app.get_loop().call_later(
        delay=0.5,
        callback=app.stop,
    )

    app.run()

    answers.sort()
    assert len(answers) == 5
    assert answers[0][0] == "image"
    assert answers[1] == ("msg", ".echo")
    assert answers[2] == ("msg", ".echo chat")
    assert answers[3] == ("msg", "/echo chat")
    assert answers[4] == ("msg", "/echo chat")