File size: 6,203 Bytes
c0e9d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""Fork-parity coverage for the agent's Telegram read/write surface.

The pinned Telethon fork hands back more than one shape for a message, and the
two configured clients disagree. These tests pin every observed shape so a
prompt can never receive ``"('hi', [...])"``.
"""

from __future__ import annotations

import asyncio
from io import BytesIO
from types import SimpleNamespace

import pytest
from telethon.tl import types
from telethon.tl.custom import Button

from pyUltroid.agent._telegram import (
    BUTTON_STYLES,
    entities_of,
    inline_rows,
    raw_message,
    text_of,
    unwrap_pair,
)

BOLD = types.MessageEntityBold(0, 4)


# ── the shapes a message can be ─────────────────────────────────────────────


def test_plain_string_passes_through():
    assert text_of("hello") == "hello"
    assert unwrap_pair("hello") == ("hello", [])


def test_fork_parse_mode_pair_is_unwrapped():
    """RICH_MD.parse returns ``(text, entities)``; the agent must see text."""
    pair = ("bold text", [BOLD])
    assert unwrap_pair(pair) == ("bold text", [BOLD])
    assert text_of(pair) == "bold text"
    assert entities_of(pair) == [BOLD]


def test_pair_without_entities():
    assert unwrap_pair(("just text",)) == ("just text", [])
    assert text_of(("just text", None)) == "just text"


def test_pair_with_none_entities_is_list_not_none():
    _, entities = unwrap_pair(("t", None))
    assert entities == []


def test_empty_and_none():
    assert unwrap_pair(None) == ("", [])
    assert unwrap_pair(None, fallback="fb") == ("fb", [])
    assert unwrap_pair(()) == ("", [])
    assert text_of(None) == ""


def test_non_string_head_degrades_to_fallback():
    """A pair whose head is not a str must not leak the repr into a prompt."""
    assert unwrap_pair((123, [BOLD])) == ("", [BOLD])
    assert unwrap_pair((None, None), fallback="?") == ("?", [])


def test_entities_are_filtered_of_none():
    _, entities = unwrap_pair(("t", [BOLD, None, BOLD]))
    assert entities == [BOLD, BOLD]


def test_message_object_prefers_raw_body():
    msg = SimpleNamespace(message="raw body", entities=[BOLD], text=("formatted", []))
    assert text_of(msg) == "raw body"
    assert entities_of(msg) == [BOLD]
    assert raw_message(msg) == "raw body"


def test_message_object_without_raw_body():
    msg = SimpleNamespace(text=("only formatted", [BOLD]))
    assert text_of(msg) == "only formatted"


def test_message_service_is_none():
    assert text_of(SimpleNamespace(message=None, entities=None, text=None)) == ""


def test_int_id_is_not_mistaken_for_a_message():
    """A peer id must come back empty, not as ``"12345"``."""
    assert text_of(12345) == ""


# ── the fork's coloured buttons ─────────────────────────────────────────────


def test_fork_supports_colour_styles():
    """Guards the premise: the pinned fork styles every Button.*."""
    for style in sorted(BUTTON_STYLES):
        button = Button.inline("x", b"d", style=style, icon=123)
        assert isinstance(button.style, types.KeyboardButtonStyle)


def test_rows_build_styled_callback_buttons():
    rows = inline_rows([[{"text": "Yes", "data": "y", "style": "success"}]])
    button = rows[0][0]
    assert button.text == "Yes"
    assert button.style.bg_success is True


def test_rows_default_style_applies_only_when_absent():
    rows = inline_rows(
        [[{"text": "A", "data": "a"}, {"text": "B", "data": "b", "style": "danger"}]],
        default_style="primary",
    )
    assert rows[0][0].style.bg_primary is True
    assert rows[0][1].style.bg_danger is True


def test_rows_accept_ikm_tuple_shapes():
    rows = inline_rows([[("Docs", "url", "https://example.com", "primary", "L")]])
    assert isinstance(rows[0][0], types.KeyboardInlineButton)
    assert isinstance(rows[0][0].type, types.InlineButtonTypeUrl)


def test_rows_accept_bare_string_cells():
    rows = inline_rows(["Yes", "No"])
    assert len(rows) == 1 and len(rows[0]) == 2


def test_rows_pass_prebuilt_buttons_through_untouched():
    original = Button.inline("Pre", b"p", style="danger")
    rows = inline_rows([[original]])
    assert rows[0][0] is original


def test_prebuilt_button_is_not_mangled_by_tuple_handling():
    """A built button is not a sequence; detection must precede len()/index."""
    original = Button.url("Site", "https://example.com")
    rows = inline_rows([[original, Button.inline("B", b"b")]])
    assert rows[0][0] is original
    assert rows[0][1].text == "B"


def test_send_file_bridge_uses_current_chat_and_plain_caption(monkeypatch):
    import pyUltroid

    from pyUltroid.agent._tgbridge import send_file_via_master

    captured = {}

    async def send_file(entity, file_obj, **kwargs):
        captured.update(entity=entity, file=file_obj, kwargs=kwargs)
        return SimpleNamespace(id=77)

    client = SimpleNamespace(send_file=send_file)
    master = SimpleNamespace(route=lambda: client)
    monkeypatch.setattr(pyUltroid, "master", master, raising=False)
    attachment = BytesIO(b"A short poem.\n")
    attachment.name = "poem.txt"

    result = asyncio.run(
        send_file_via_master(
            attachment,
            "-10042",
            caption="A short poem",
        )
    )

    assert result == {"ok": True, "route": "auto", "message_id": 77}
    assert captured["entity"] == -10042
    assert captured["file"] is attachment
    assert captured["kwargs"] == {
        "caption": "A short poem",
        "parse_mode": None,
    }


def test_unknown_style_is_rejected_with_a_useful_message():
    with pytest.raises(ValueError, match="unknown button style"):
        inline_rows([[{"text": "X", "data": "x", "style": "neon"}]])


def test_empty_rows_are_dropped():
    assert inline_rows([[], [{"text": "A", "data": "a"}]]) == [
        [Button.inline("A", b"a")]
    ] or len(inline_rows([[], [{"text": "A", "data": "a"}]])) == 1


def test_row_of_helper():
    rows = inline_rows([list(({"text": "A", "data": "a"}, {"text": "B", "data": "b"}))])
    assert len(rows[0]) == 2