Add User Friendly Type Check For Init Of {Inline, Reply}KeyboardMarkup (#2657)

This commit is contained in:
Harshil 2021-09-15 19:04:47 +04:00 committed by Hinrich Mahler
parent 8f0031e9c8
commit afcff83ebc
5 changed files with 35 additions and 1 deletions

View file

@ -48,6 +48,11 @@ class InlineKeyboardMarkup(ReplyMarkup):
__slots__ = ('inline_keyboard',)
def __init__(self, inline_keyboard: List[List[InlineKeyboardButton]], **_kwargs: Any):
if not self._check_keyboard_type(inline_keyboard):
raise ValueError(
"The parameter `inline_keyboard` should be a list of "
"list of InlineKeyboardButtons"
)
# Required
self.inline_keyboard = inline_keyboard

View file

@ -92,6 +92,12 @@ class ReplyKeyboardMarkup(ReplyMarkup):
input_field_placeholder: str = None,
**_kwargs: Any,
):
if not self._check_keyboard_type(keyboard):
raise ValueError(
"The parameter `keyboard` should be a list of list of "
"strings or KeyboardButtons"
)
# Required
self.keyboard = []
for row in keyboard:

View file

@ -17,7 +17,6 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram ReplyMarkup Objects."""
from telegram import TelegramObject
@ -31,3 +30,13 @@ class ReplyMarkup(TelegramObject):
"""
__slots__ = ()
@staticmethod
def _check_keyboard_type(keyboard: object) -> bool:
"""Checks if the keyboard provided is of the correct type - A list of lists."""
if not isinstance(keyboard, list):
return False
for row in keyboard:
if not isinstance(row, list):
return False
return True

View file

@ -81,6 +81,14 @@ class TestInlineKeyboardMarkup:
def test_expected_values(self, inline_keyboard_markup):
assert inline_keyboard_markup.inline_keyboard == self.inline_keyboard
def test_wrong_keyboard_inputs(self):
with pytest.raises(ValueError):
InlineKeyboardMarkup(
[[InlineKeyboardButton('b1', '1')], InlineKeyboardButton('b2', '2')]
)
with pytest.raises(ValueError):
InlineKeyboardMarkup(InlineKeyboardButton('b1', '1'))
def test_expected_values_empty_switch(self, inline_keyboard_markup, bot, monkeypatch):
def test(
url,

View file

@ -102,6 +102,12 @@ class TestReplyKeyboardMarkup:
assert reply_keyboard_markup.selective == self.selective
assert reply_keyboard_markup.input_field_placeholder == self.input_field_placeholder
def test_wrong_keyboard_inputs(self):
with pytest.raises(ValueError):
ReplyKeyboardMarkup([[KeyboardButton('b1')], 'b2'])
with pytest.raises(ValueError):
ReplyKeyboardMarkup(KeyboardButton('b1'))
def test_to_dict(self, reply_keyboard_markup):
reply_keyboard_markup_dict = reply_keyboard_markup.to_dict()