Passed
Push — master ( 48245f...6bb124 )
by torrua
01:22
created

get_verified_button_tuple()   A

Complexity

Conditions 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 12
nop 2
dl 0
loc 21
ccs 8
cts 8
cp 1
crap 5
rs 9.3333
c 0
b 0
f 0
1
# -*- coding:utf-8 -*-
2 1
"""
3
Module with functions for work with button data and button text
4
"""
5
6 1
from telebot.types import InlineKeyboardButton
7
8 1
from keyboa.constants import InlineButtonData, button_text_types, ButtonText
9
10
11 1
def get_text(button_data: tuple) -> str:
12
    """
13
    :param button_data:
14
    :return:
15
    """
16 1
    raw_text = button_data[0]
17 1
    if not isinstance(raw_text, button_text_types):
18 1
        type_error_message = "Button text cannot be %s. Only %s allowed." \
19
                             % (type(raw_text), ButtonText)
20 1
        raise TypeError(type_error_message)
21 1
    text = str(raw_text)
22 1
    if not text:
23 1
        raise ValueError("Button text cannot be empty.")
24 1
    return text
25
26
27 1
def get_verified_button_tuple(
28
        button_data: InlineButtonData,
29
        copy_text_to_callback: bool) -> tuple:
30
    """
31
    :param button_data:
32
    :param copy_text_to_callback:
33
    :return:
34
    """
35 1
    if not isinstance(button_data, (tuple, dict, str, int)):
36 1
        type_error_message = \
37
            "Cannot create %s from %s. Please use %s instead.\n" \
38
            "Probably you specified 'auto_alignment' or 'items_in_line' " \
39
            "parameter for StructuredSequence." \
40
            % (InlineKeyboardButton, type(button_data), InlineButtonData)
41 1
        raise TypeError(type_error_message)
42
43 1
    btn_tuple = get_raw_tuple_from_button_data(button_data, copy_text_to_callback)
44
45 1
    if len(btn_tuple) == 1 or btn_tuple[1] is None:
46 1
        btn_tuple = btn_tuple[0], btn_tuple[0] if copy_text_to_callback else str()
47 1
    return btn_tuple
48
49
50 1
def get_raw_tuple_from_button_data(button_data, copy_text_to_callback):
51
    """
52
    :param button_data:
53
    :param copy_text_to_callback:
54
    :return:
55
    """
56 1
    if isinstance(button_data, (str, int)):
57 1
        btn_tuple = button_data, button_data if copy_text_to_callback else str()
58
59 1
    elif isinstance(button_data, dict):
60 1
        if len(button_data.keys()) != 1:
61 1
            value_type_error = \
62
                "Cannot convert dictionary to InlineButtonData object. " \
63
                "You passed more than one item, but did not add 'text' key."
64 1
            raise ValueError(value_type_error)
65
66 1
        btn_tuple = next(iter(button_data.items()))
67
    else:
68 1
        btn_tuple = button_data
69
    return btn_tuple
70