File size: 7,675 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""Tests for the DM session key fix and threaded delivery.

Covers the production failure:

    ValueError: invalid literal for int() with base 10: 'dm:6802929470:305'
    at .../_agent.py:628 in chat_system

The DM flow now builds its history key with :class:`DmSessionKey` instead of a
bare string, and ``chat_system``/``set_chat_system``/``reset_chat_system``
normalize through :class:`ChatKey` so string and numeric ids live in distinct
slots. Delivery is threaded to the user's triggering message; a failed edit
does not create a duplicate fallback answer.
"""

from __future__ import annotations

import asyncio

import pytest

from pyUltroid.agent._agent import UltroidAgent
from pyUltroid.agent._chatkey import (
    CATEGORY_SESSION,
    DmSessionKey,
    NumericChatKey,
    normalize_chat_id,
)
from pyUltroid.agent._delivery import DeliveryError as _DeliveryError
from pyUltroid.agent._delivery import DeliveryStrategy as _SessionDelivery


def _run(coro):
    """Run a coroutine to completion in a fresh event loop.

    Isolated from pytest-asyncio so the suite does not pay for the plugin on
    this repo. A dedicated loop is used because some Telethon test doubles
    bind to the running loop at import time.
    """
    loop = asyncio.new_event_loop()
    try:
        return loop.run_until_complete(coro)
    finally:
        loop.close()


# ── key construction ┧────────────────────────────────────────────────────────


def test_dm_session_key_is_stable_and_categorised():
    key = DmSessionKey(6802929470, 305)
    assert key.is_session()
    assert key.category == CATEGORY_SESSION
    assert key.value == "dm:6802929470:305"
    assert key.user_id == 6802929470
    assert key.anchor == 305


def test_normalize_chat_id_accepts_both_forms():
    assert normalize_chat_id("dm:6802929470:305") == "dm:6802929470:305"
    assert normalize_chat_id(8402929470) == "8402929470"


# ── the crash that broke .aichat ────────────────────────────────────────────


def test_chat_system_does_not_int_coerce_a_dm_key():
    """The exact call stack from the production traceback, now safe."""
    agent = UltroidAgent()
    agent.set_chat_system("dm:6802929470:305", "session prompt")

    assert agent.chat_system("dm:6802929470:305") == "session prompt"


def test_numeric_and_dm_keys_never_collide():
    """The original bug: int("dm:...") raised; the latent bug was collision."""
    agent = UltroidAgent()
    agent.set_chat_system("dm:6802929470:305", "session")
    agent.set_chat_system(6802929470, "numeric")

    assert agent.chat_system("dm:6802929470:305") == "session"
    assert agent.chat_system(6802929470) == "numeric"


def test_reset_chat_system_handles_dm_key():
    agent = UltroidAgent()
    agent.set_chat_system("dm:6802929470:305", "session")
    agent.reset_chat_system("dm:6802929470:305")
    assert agent.chat_system("dm:6802929470:305") == ""


def test_chat_system_accepts_a_numeric_int():
    agent = UltroidAgent()
    agent.set_chat_system(42, "group")
    assert agent.chat_system(42) == "group"
    assert normalize_chat_id(42) == "42"
    assert isinstance(
        __import__(
            "pyUltroid.agent._chatkey", fromlist=["build_chat_key"]
        ).build_chat_key(42),
        NumericChatKey,
    )


# ── persistence format ┧─────────────────────────────────────────────────────


def test_chat_systems_store_canonical_strings():
    """In-memory and persisted forms agree on canonical keys."""
    agent = UltroidAgent()
    agent.set_chat_system("dm:6802929470:305", "session")
    agent.set_chat_system(7, "group")

    assert agent._chat_systems == {
        "dm:6802929470:305": "session",
        "7": "group",
    }
    # The raw integer must NOT shadow the session string.
    assert "6802929470" not in agent._chat_systems


# ── _SessionDelivery threading ┧─────────────────────────────────────────────


class _FakeMessage:
    """A minimal message double: tracks reply and edit calls."""

    def __init__(self) -> None:
        self.edited: list[str] = []
        self.replied_to: list[str] = []

    async def reply(self, text: str, **kwargs) -> "_FakeMessage":
        self.replied_to.append(text)
        return self

    async def edit(self, text: str, **kwargs) -> None:
        self.edited.append(text)


class _BrokenEditMessage(_FakeMessage):
    async def edit(self, text: str, **kwargs) -> None:
        raise PermissionError("cannot edit")


class _BrokenReplyMessage(_FakeMessage):
    async def reply(self, text: str, **kwargs):
        raise PermissionError("cannot reply")


def test_delivery_holds_the_triggering_message():

    trigger = _FakeMessage()
    delivery = _SessionDelivery(trigger)
    assert delivery._trigger is trigger


def test_delivery_render_edits_in_place_when_possible():

    trigger = _FakeMessage()
    placeholder = _FakeMessage()
    delivery = _SessionDelivery(trigger)

    result = _run(delivery.render(placeholder, "the answer"))
    assert placeholder.edited == ["the answer"]
    assert trigger.replied_to == []  # no fallback fired
    assert result is placeholder


def test_delivery_edit_failure_does_not_duplicate_answer_as_reply():
    """A failed edit is reported instead of sending a second attached answer."""

    trigger = _FakeMessage()
    placeholder = _BrokenEditMessage()
    delivery = _SessionDelivery(trigger)

    with pytest.raises(_DeliveryError) as ei:
        _run(delivery.render(placeholder, "the answer"))
    assert placeholder.edited == []
    assert trigger.replied_to == []
    assert ei.value.phase == "plain_edit"


def test_delivery_edit_and_trigger_reply_failures_remain_structured():
    """A failed placeholder edit stays a structured delivery error."""

    trigger = _BrokenReplyMessage()
    placeholder = _BrokenEditMessage()
    delivery = _SessionDelivery(trigger)

    with pytest.raises(_DeliveryError) as ei:
        _run(delivery.render(placeholder, "the answer"))
    assert ei.value.phase == "plain_edit"


def test_bot_rich_edit_failure_never_sends_a_second_reply(monkeypatch):
    from types import SimpleNamespace

    from pyUltroid._core import richmsg

    trigger = _FakeMessage()
    trigger.client = SimpleNamespace(_bot=True)
    trigger.chat_id = -10055
    trigger.id = 7
    placeholder = _FakeMessage()
    delivery = _SessionDelivery(trigger)

    async def fail_edit(*_args, **_kwargs):
        raise RuntimeError("native RichMessage edit rejected")

    monkeypatch.setattr(richmsg, "edit_rich", fail_edit)

    with pytest.raises(_DeliveryError) as ei:
        _run(delivery.render(placeholder, "rich answer"))
    assert ei.value.phase == "rich_edit"
    assert trigger.replied_to == []


def test_delivery_placeholder_failure_is_reported():
    """If even the typing indicator cannot send, the phase is reported."""

    trigger = _BrokenReplyMessage()
    delivery = _SessionDelivery(trigger)

    with pytest.raises(_DeliveryError) as ei:
        _run(delivery.placeholder())
    assert ei.value.phase == "placeholder"


def test_delivery_error_carries_phase_and_cause():
    err = _DeliveryError("placeholder", PermissionError("nope"))
    assert err.phase == "placeholder"
    assert "placeholder" in str(err)
    assert isinstance(err.__cause__, PermissionError)