From e17c84144dc4097c799b35a10e914929ca502173 Mon Sep 17 00:00:00 2001 From: "Oleg A." Date: Sun, 16 Feb 2025 23:39:51 +0300 Subject: [PATCH] Prevent endless loop with buttons (#1626) * fix: prevent endless loop with buttons * test: added test for add w/o max width * docs: added changelog record * chore: explicit set max_width 0 --- CHANGES/1595.bugfix.rst | 1 + aiogram/utils/keyboard.py | 9 ++++++--- tests/test_utils/test_keyboard.py | 10 ++++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 CHANGES/1595.bugfix.rst diff --git a/CHANGES/1595.bugfix.rst b/CHANGES/1595.bugfix.rst new file mode 100644 index 00000000..f56d8b2a --- /dev/null +++ b/CHANGES/1595.bugfix.rst @@ -0,0 +1 @@ +Fixed endless loop while adding buttons to the :code:`KeyboardBuilder`. diff --git a/aiogram/utils/keyboard.py b/aiogram/utils/keyboard.py index 23659b8f..fe806f7a 100644 --- a/aiogram/utils/keyboard.py +++ b/aiogram/utils/keyboard.py @@ -179,9 +179,12 @@ class KeyboardBuilder(Generic[ButtonType], ABC): last_row.extend(head) # Separate buttons to exclusive rows with max possible row width - while buttons: - row, buttons = buttons[: self.max_width], buttons[self.max_width :] - markup.append(list(row)) + if self.max_width > 0: + while buttons: + row, buttons = buttons[: self.max_width], buttons[self.max_width :] + markup.append(list(row)) + else: + markup.append(list(buttons)) self._markup = markup return self diff --git a/tests/test_utils/test_keyboard.py b/tests/test_utils/test_keyboard.py index 27aeb1ac..1bc7063a 100644 --- a/tests/test_utils/test_keyboard.py +++ b/tests/test_utils/test_keyboard.py @@ -170,6 +170,16 @@ class TestKeyboardBuilder: if last_columns: assert len(markup[-1]) == last_columns + def test_add_wo_max_width(self): + builder = KeyboardBuilder(button_type=KeyboardButton) + builder.max_width = 0 + count = 42 + + for index in range(count): + builder.add(KeyboardButton(text=f"btn-{index}")) + + assert len(list(builder.buttons)) == count + def test_row( self, ):