mirror of
https://github.com/aiogram/aiogram.git
synced 2026-04-08 16:37:47 +00:00
Merge 599f00d728 into ab32296d07
This commit is contained in:
commit
7c6f06f600
3 changed files with 22 additions and 14 deletions
1
CHANGES/1668.feature.rst
Normal file
1
CHANGES/1668.feature.rst
Normal file
|
|
@ -0,0 +1 @@
|
|||
Feature: Make CallbackData prefix optional and default to class name
|
||||
|
|
@ -47,24 +47,26 @@ class CallbackData(BaseModel):
|
|||
|
||||
This class should be used as super-class of user-defined callbacks.
|
||||
|
||||
The class-keyword :code:`prefix` is required to define prefix
|
||||
and also the argument :code:`sep` can be passed to define separator (default is :code:`:`).
|
||||
An optional class-keyword :code:`prefix` can be passed to define prefix.
|
||||
If no prefix is provided, the class name will be used as the prefix.
|
||||
|
||||
An optional argument :code:`sep` can be passed to define the separator
|
||||
(default is :code:`:`).
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING:
|
||||
__separator__: ClassVar[str]
|
||||
"""Data separator (default is :code:`:`)"""
|
||||
__prefix__: ClassVar[str]
|
||||
"""Callback prefix"""
|
||||
"""Callback prefix (default is class name)"""
|
||||
|
||||
def __init_subclass__(cls, **kwargs: Any) -> None:
|
||||
if "prefix" not in kwargs:
|
||||
raise ValueError(
|
||||
f"prefix required, usage example: "
|
||||
f"`class {cls.__name__}(CallbackData, prefix='my_callback'): ...`"
|
||||
)
|
||||
# If no prefix is provided explicitly, default to the class name
|
||||
prefix = kwargs.pop("prefix", None)
|
||||
if prefix is None:
|
||||
prefix = cls.__name__
|
||||
cls.__separator__ = kwargs.pop("sep", ":")
|
||||
cls.__prefix__ = kwargs.pop("prefix")
|
||||
cls.__prefix__ = prefix
|
||||
if cls.__separator__ in cls.__prefix__:
|
||||
raise ValueError(
|
||||
f"Separator symbol {cls.__separator__!r} can not be used "
|
||||
|
|
|
|||
|
|
@ -28,13 +28,18 @@ class MyCallback(CallbackData, prefix="test"):
|
|||
|
||||
|
||||
class TestCallbackData:
|
||||
def test_init_subclass_prefix_required(self):
|
||||
assert MyCallback.__prefix__ == "test"
|
||||
def test_init_subclass_prefix_optional(self):
|
||||
# Case 1: Explicitly provided prefix
|
||||
class ExplicitCallbackData(CallbackData, prefix="explicit"):
|
||||
pass
|
||||
|
||||
with pytest.raises(ValueError, match="prefix required.+"):
|
||||
assert ExplicitCallbackData.__prefix__ == "explicit"
|
||||
|
||||
class MyInvalidCallback(CallbackData):
|
||||
pass
|
||||
# Case 2: No prefix provided; should default to class name
|
||||
class DefaultCallbackData(CallbackData):
|
||||
pass
|
||||
|
||||
assert DefaultCallbackData.__prefix__ == "DefaultCallbackData"
|
||||
|
||||
def test_init_subclass_sep_validation(self):
|
||||
assert MyCallback.__separator__ == ":"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue