Beispiel #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", (), {})]
Beispiel #2
0
class KutanaTest(unittest.TestCase):
    def setUp(self):
        self.kutana = None
        self.target = []

    @contextmanager
    def debug_controller(self, queue):
        if self.kutana is None:
            self.kutana = Kutana()

        self.controller = DebugController(*queue)

        self.kutana.add_controller(self.controller)

        self.plugin = Plugin()

        self.plugins = [self.plugin]

        try:
            yield self.plugin
        finally:
            for plugin in self.plugins:
                self.kutana.executor.register_plugins(plugin)

            self.kutana.run()

        self.assertEqual(self.target, self.controller.replies)
Beispiel #3
0
class KutanaTest(unittest.TestCase):
    def setUp(self):
        self.app = None
        self.target = []

    @contextmanager
    def debug_manager(self, queue):
        if self.app is None:
            self.app = Kutana()

        self.manager = DebugManager(*queue)

        self.app.add_manager(self.manager)

        self.plugin = Plugin()

        self.plugins = [self.plugin]

        try:
            yield self.plugin
        finally:
            for plugin in self.plugins:
                self.app.register_plugins([plugin])

            self.app.run()

        self.assertEqual(self.target, self.manager.replies)
Beispiel #4
0
def test_kutana_shutdown():
    for exception in [Exception, KeyboardInterrupt]:
        app = Kutana()

        _shutdown = app._shutdown

        async def checker():
            checker._called += 1
            await _shutdown()

        checker._called = 0

        app._main_loop = MagicMock(side_effect=exception)
        app._shutdown = checker
        app.run()

        assert checker._called == 1
Beispiel #5
0
def test_kutana_shutdown():
    app = Kutana()

    async def trigger():
        raise KeyboardInterrupt

    _shutdown = app._shutdown
    async def checker():
        checker._called = True
        await _shutdown()
    checker._called = False

    app._main_loop = trigger
    app._shutdown = checker
    app.run()

    assert checker._called == True
Beispiel #6
0
def run():
    """
    This function runs kutana application using provided
    configuration and CLI options.

    Refer to its source to create more specific starter for
    your application.
    """

    # Parse provided arguments
    args = parser.parse_args()

    # Setup logger
    if args.debug:
        logger.set_logger_level(logging.DEBUG)

    # Import configuration
    if not os.path.isfile(args.config):
        logger.logger.error(f"Couldn't open confiuration file: {args.config}")
        exit(1)

    with open(args.config) as fh:
        config = yaml.safe_load(fh)

    # Create application
    app = Kutana()

    # Update configuration
    app.config.update(config)

    # Setup i18n
    set_default_language(config.get("language", "en"))
    load_translations(args.translations)

    # Add each backend from config
    add_backends(app, config.get("backends"))

    # Add each storage from config
    add_storages(app, config.get("storages"))

    # Load and register plugins from provided path
    app.add_plugins(load_plugins(args.plugins))

    # Run application
    app.run()
Beispiel #7
0
from kutana import Kutana, VKController, load_plugins, load_configuration


# Create engine
kutana = Kutana()

# Create VKController
kutana.add_controller(
    VKController(token = "d6842a32a19fefc24f1ac19b17cba1c9243f4bf1ecdf426215d193d96135a111d0d537f6e2df8f1452482")
)

# Load and register plugins
kutana.executor.register_plugins(*load_plugins("/root/bot/example/"))

# Run engine
kutana.run()
Beispiel #8
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]
Beispiel #9
0
import json

from kutana import Kutana, VKManager, load_plugins, TGManager

# Load configuration
with open("configuration.json") as fh:
    config = json.load(fh)

# Create application
app = Kutana()

# Add manager to application
app.add_manager(VKManager(config["vk_token"]))

app.add_manager(TGManager(config["tg_token"]))

# Load and register plugins
app.register_plugins(load_plugins("plugins/"))

if __name__ == "__main__":
    # Run application
    app.run()
Beispiel #10
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")