File: test_prefixhandler.py

package info (click to toggle)
python-telegram-bot 22.3-1
  • links: PTS
  • area: main
  • in suites: sid
  • size: 11,060 kB
  • sloc: python: 90,298; makefile: 176; sh: 4
file content (152 lines) | stat: -rw-r--r-- 6,712 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#
#  A library that provides a Python interface to the Telegram Bot API
#  Copyright (C) 2015-2025
#  Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser Public License for more details.
#
#  You should have received a copy of the GNU Lesser Public License
#  along with this program.  If not, see [http://www.gnu.org/licenses/].
import pytest

from telegram import Chat
from telegram.ext import CallbackContext, PrefixHandler, filters
from tests.auxil.build_messages import make_command_update, make_message, make_message_update
from tests.auxil.slots import mro_slots
from tests.ext.test_commandhandler import BaseTest, is_match


def combinations(prefixes, commands):
    return [prefix + command for prefix in prefixes for command in commands]


class TestPrefixHandler(BaseTest):
    # Prefixes and commands with which to test PrefixHandler:
    PREFIXES = ["!", "#", "mytrig-"]
    COMMANDS = ["help", "test"]
    COMBINATIONS = list(combinations(PREFIXES, COMMANDS))

    def test_slot_behaviour(self):
        handler = self.make_default_handler()
        for attr in handler.__slots__:
            assert getattr(handler, attr, "err") != "err", f"got extra slot '{attr}'"
        assert len(mro_slots(handler)) == len(set(mro_slots(handler))), "duplicate slot"

    @pytest.fixture(params=PREFIXES)
    def prefix(self, request):
        return request.param

    @pytest.fixture(params=[1, 2], ids=["single prefix", "multiple prefixes"])
    def prefixes(self, request):
        return TestPrefixHandler.PREFIXES[: request.param]

    @pytest.fixture(params=COMMANDS)
    def command(self, request):
        return request.param

    @pytest.fixture(params=[1, 2], ids=["single command", "multiple commands"])
    def commands(self, request):
        return TestPrefixHandler.COMMANDS[: request.param]

    @pytest.fixture
    def prefix_message_text(self, prefix, command):
        return prefix + command

    @pytest.fixture
    def prefix_message(self, prefix_message_text):
        return make_message(prefix_message_text)

    @pytest.fixture
    def prefix_message_update(self, prefix_message):
        return make_message_update(prefix_message)

    def make_default_handler(self, callback=None, **kwargs):
        callback = callback or self.callback_basic
        return PrefixHandler(self.PREFIXES, self.COMMANDS, callback, **kwargs)

    async def test_basic(self, app, prefix, command):
        """Test the basic expected response from a prefix handler"""
        handler = self.make_default_handler()
        app.add_handler(handler)
        text = prefix + command

        assert await self.response(app, make_message_update(text))
        assert not is_match(handler, make_message_update(command))
        assert not is_match(handler, make_message_update(prefix + "notacommand"))
        assert not is_match(handler, make_command_update(f"not {text} at start"))
        assert not is_match(
            handler, make_message_update(bot=app.bot, message=None, caption="caption")
        )

        handler = PrefixHandler(prefix=["!", "#"], command="cmd", callback=self.callback)
        assert isinstance(handler.commands, frozenset)
        assert handler.commands == {"!cmd", "#cmd"}

        handler = PrefixHandler(prefix="#", command={"cmd", "bmd"}, callback=self.callback)
        assert isinstance(handler.commands, frozenset)
        assert handler.commands == {"#cmd", "#bmd"}

    def test_single_multi_prefixes_commands(self, prefix_message_update):
        """Test various combinations of prefixes and commands"""
        handler = self.make_default_handler()
        result = is_match(handler, prefix_message_update)
        expected = prefix_message_update.message.text in self.COMBINATIONS
        assert result == expected

    def test_edited(self, prefix_message):
        handler_edited = self.make_default_handler()
        handler_no_edited = self.make_default_handler(filters=~filters.UpdateType.EDITED_MESSAGE)
        self._test_edited(prefix_message, handler_edited, handler_no_edited)

    def test_with_filter(self, prefix_message_text):
        handler = self.make_default_handler(filters=filters.ChatType.GROUP)
        text = prefix_message_text
        assert is_match(handler, make_message_update(text, chat=Chat(-23, Chat.GROUP)))
        assert not is_match(handler, make_message_update(text, chat=Chat(23, Chat.PRIVATE)))

    def test_other_update_types(self, false_update):
        handler = self.make_default_handler()
        assert not is_match(handler, false_update)

    def test_filters_for_wrong_command(self, mock_filter):
        """Filters should not be executed if the command does not match the handler"""
        handler = self.make_default_handler(filters=mock_filter)
        assert not is_match(handler, make_message_update("/test"))
        assert not mock_filter.tested

    async def test_context(self, app, prefix_message_update):
        handler = self.make_default_handler(self.callback)
        app.add_handler(handler)
        assert await self.response(app, prefix_message_update)

    async def test_context_args(self, app, prefix_message_text):
        handler = self.make_default_handler(self.callback_args)
        await self._test_context_args_or_regex(app, handler, prefix_message_text)

    async def test_context_regex(self, app, prefix_message_text):
        handler = self.make_default_handler(self.callback_regex1, filters=filters.Regex("one two"))
        await self._test_context_args_or_regex(app, handler, prefix_message_text)

    async def test_context_multiple_regex(self, app, prefix_message_text):
        handler = self.make_default_handler(
            self.callback_regex2, filters=filters.Regex("one") & filters.Regex("two")
        )
        await self._test_context_args_or_regex(app, handler, prefix_message_text)

    def test_collect_additional_context(self, app):
        handler = self.make_default_handler(
            self.callback_regex2, filters=filters.Regex("one") & filters.Regex("two")
        )
        context = CallbackContext(application=app)
        handler.collect_additional_context(
            context=context, update=None, application=app, check_result=None
        )
        assert context.args is None