From ee8e457c5fe79ee85422915713d86fcd3fc51518 Mon Sep 17 00:00:00 2001 From: Alex Root Junior Date: Sat, 26 Aug 2023 22:33:32 +0300 Subject: [PATCH] #1281 Fix magic operation .as_ for values interpreted as False (#1283) Modified the ".as_" method in the magic filter class to correctly handle values that are interpreted as `False` such as `0`. Previously, the method incorrectly dismissed these valid values. The issue was identified and fixed to ensure correct handling of all valid data inputs. --- CHANGES/1281.bugfix.rst | 1 + aiogram/utils/magic_filter.py | 4 ++-- tests/test_utils/test_magic_filter.py | 14 ++++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) create mode 100644 CHANGES/1281.bugfix.rst diff --git a/CHANGES/1281.bugfix.rst b/CHANGES/1281.bugfix.rst new file mode 100644 index 00000000..285b180d --- /dev/null +++ b/CHANGES/1281.bugfix.rst @@ -0,0 +1 @@ +Fixed magic :code:`.as_(...)` operation for values that can be interpreted as `False` (e.g. `0`). diff --git a/aiogram/utils/magic_filter.py b/aiogram/utils/magic_filter.py index fed406a7..94c92079 100644 --- a/aiogram/utils/magic_filter.py +++ b/aiogram/utils/magic_filter.py @@ -1,4 +1,4 @@ -from typing import Any +from typing import Any, Iterable from magic_filter import MagicFilter as _MagicFilter from magic_filter import MagicT as _MagicT @@ -12,7 +12,7 @@ class AsFilterResultOperation(BaseOperation): self.name = name def resolve(self, value: Any, initial_value: Any) -> Any: - if not value: + if value is None or (isinstance(value, Iterable) and not value): return None return {self.name: value} diff --git a/tests/test_utils/test_magic_filter.py b/tests/test_utils/test_magic_filter.py index 4a1d05f3..097c8365 100644 --- a/tests/test_utils/test_magic_filter.py +++ b/tests/test_utils/test_magic_filter.py @@ -19,3 +19,17 @@ class TestMagicFilter: result = magic.resolve(MyObject(text="123")) assert isinstance(result, dict) assert isinstance(result["match"], Match) + + def test_operation_as_not_none(self): + # Issue: https://github.com/aiogram/aiogram/issues/1281 + magic = F.cast(int).as_("value") + + result = magic.resolve("0") + assert result == {"value": 0} + + def test_operation_as_not_none_iterable(self): + # Issue: https://github.com/aiogram/aiogram/issues/1281 + magic = F.as_("value") + + result = magic.resolve([]) + assert result is None