test_adapter.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. """Unit tests for the Chatto platform adapter.
  2. Covers:
  3. - Emoji shortcode conversion
  4. - Adapter instantiation and properties
  5. - Registration and requirements
  6. - Basic functionality with chattolib
  7. - Message sending and reactions
  8. - User lookup (with caching)
  9. - Presence and custom status
  10. All network calls are mocked — no real HTTP or WebSocket connections.
  11. """
  12. import asyncio
  13. import os
  14. import sys
  15. import tempfile
  16. from unittest.mock import AsyncMock, MagicMock, patch, call
  17. from collections import OrderedDict
  18. import pytest
  19. import pytest_asyncio
  20. # Import chattolib types for tests - using vendored chattolib from adapter
  21. # -- Path setup --
  22. # The Hermes agent itself is not a dependency of this plugin; point HERMES_ROOT
  23. # at a checkout to run these tests outside a deployed agent.
  24. PLUGIN_ROOT = os.path.abspath(os.path.dirname(__file__))
  25. sys.path.insert(0, PLUGIN_ROOT)
  26. sys.path.insert(0, os.environ.get("HERMES_ROOT", "/opt/hermes"))
  27. sys.path.insert(0, "/root/.hermes/plugins/platforms/chatto")
  28. from adapter import (
  29. ChattoAdapter,
  30. _capabilities,
  31. HermesChatType,
  32. chat_type_for_room_kind,
  33. hermes_check_fn as check_requirements,
  34. hermes_validate_config as validate_config,
  35. register,
  36. )
  37. from chattolib.realtime_types import ReactionPayload
  38. from chattolib.types import (
  39. Asset,
  40. AssetUpload,
  41. AssetUrl,
  42. Message,
  43. MessageAttachment,
  44. PresenceStatus,
  45. Room,
  46. RoomKind,
  47. User,
  48. )
  49. from platform_config import ChattoConstants
  50. from gateway.config import PlatformConfig
  51. from gateway.platforms.base import (
  52. BasePlatformAdapter,
  53. CachedMedia,
  54. MessageEvent,
  55. MessageType,
  56. SendResult,
  57. get_inbound_media_max_bytes,
  58. )
  59. _EMOJI_TO_SHORTCODE = ChattoConstants.EMOJI_TO_SHORTCODE
  60. _MAX_MESSAGE_LENGTH = ChattoConstants.MAX_MESSAGE_LENGTH
  61. _SEEN_CAP = ChattoConstants.SEEN_CAP
  62. # -- Helpers --
  63. class _MockPluginContext:
  64. """Minimal mock for the plugin registration context."""
  65. def __init__(self):
  66. self.registered_names = []
  67. self.registered_kwargs = None
  68. def register_platform(self, **kwargs):
  69. from gateway.platform_registry import platform_registry, PlatformEntry
  70. entry = PlatformEntry(
  71. name=kwargs["name"],
  72. label=kwargs.get("label", kwargs["name"]),
  73. adapter_factory=kwargs.get("adapter_factory"),
  74. check_fn=kwargs.get("check_fn"),
  75. validate_config=kwargs.get("validate_config"),
  76. is_connected=kwargs.get("is_connected"),
  77. required_env=kwargs.get("required_env", []),
  78. source="plugin",
  79. )
  80. platform_registry.register(entry)
  81. self.registered_names.append(kwargs["name"])
  82. self.registered_kwargs = kwargs
  83. def _ensure_chatto_registered():
  84. """Register the platform so Platform(PLATFORM_NAME) resolves."""
  85. from gateway.platform_registry import platform_registry
  86. if not platform_registry.is_registered(ChattoConstants.PLATFORM_NAME):
  87. ctx = _MockPluginContext()
  88. register(ctx)
  89. _CHATTO_ENV_KEYS = [
  90. "CHATTO_BASE_URL", "CHATTO_LOGIN", "CHATTO_PASSWORD",
  91. "CHATTO_CHANNELS", "CHATTO_HOME_CHANNEL",
  92. "CHATTO_REQUIRE_MENTION", "CHATTO_ALLOWED_USERS",
  93. "CHATTO_ALLOW_ALL_USERS", "CHATTO_AUTO_THREAD",
  94. "CHATTO_REACTIONS",
  95. ]
  96. def _clear_chatto_env(monkeypatch=None):
  97. """Remove all CHATTO_* env vars so tests start from a clean slate."""
  98. for key in _CHATTO_ENV_KEYS:
  99. if monkeypatch is not None:
  100. monkeypatch.delenv(key, raising=False)
  101. else:
  102. os.environ.pop(key, None)
  103. def _make_config(**extra_overrides):
  104. """Create a minimal PlatformConfig for testing."""
  105. _ensure_chatto_registered()
  106. extra = {"base_url": "https://chat.example.com", "channels": ["room1"]}
  107. extra.update(extra_overrides)
  108. return PlatformConfig(enabled=True, extra=extra)
  109. def _make_room(room_id, name, kind):
  110. """Build a real chattolib Room, as the client would return."""
  111. return Room(id=room_id, name=name, kind=kind, description="",
  112. archived=False, group_id="", universal=kind != RoomKind.DM)
  113. def _make_user(user_id, login):
  114. """Build a real chattolib User, as the member directory would return."""
  115. return User(id=user_id, login=login, display_name=login.replace("_", " ").title())
  116. def _make_attachment(filename, content_type, url="https://cdn.example.com/a"):
  117. """Build a real MessageAttachment carrying a (pre-signed) asset URL."""
  118. return MessageAttachment(
  119. id="asset-" + filename,
  120. filename=filename,
  121. content_type=content_type,
  122. asset_url=AssetUrl(url=url),
  123. )
  124. def _make_message(body="hi", attachments=None, message_id="msg-1", room_id="room-1"):
  125. """Build a real chattolib Message, as fetch_message() would return."""
  126. return Message(
  127. id=message_id,
  128. room_id=room_id,
  129. created_at=None,
  130. actor_id="user-1",
  131. body=body,
  132. attachments=list(attachments or []),
  133. )
  134. def _make_posted_payload(room_id="room-1", message_event_id="msg-1"):
  135. """A message_posted payload whose fetch_message() the caller stubs."""
  136. payload = MagicMock()
  137. payload.room_id = room_id
  138. payload.message_event_id = message_event_id
  139. payload.thread_root_event_id = None
  140. return payload
  141. def _cached(path, media_type, kind):
  142. """The CachedMedia that cache_media_bytes() would return for an attachment."""
  143. return CachedMedia(path=path, media_type=media_type, kind=kind, display_name="f")
  144. def _make_adapter(**extra_overrides):
  145. """Create a ChattoAdapter with mocked config."""
  146. _clear_chatto_env()
  147. cfg = _make_config(**extra_overrides)
  148. adapter = ChattoAdapter(cfg)
  149. adapter._chatto_client = MagicMock()
  150. adapter._token = "test-token"
  151. adapter._user_id = "bot-user-id"
  152. adapter._user_login = "hermes_bot"
  153. adapter._user_display = "Hermes Bot"
  154. return adapter
  155. # -- Emoji shortcode conversion --
  156. class TestEmojiShortcode:
  157. """Test emoji to shortcode mapping."""
  158. def test_emoji_to_shortcode_exists(self):
  159. assert isinstance(_EMOJI_TO_SHORTCODE, dict)
  160. assert len(_EMOJI_TO_SHORTCODE) > 0
  161. def test_emoji_to_shortcode_common_emojis(self):
  162. assert _EMOJI_TO_SHORTCODE.get("👍") == "thumbsup"
  163. assert _EMOJI_TO_SHORTCODE.get("👎") == "thumbsdown"
  164. assert _EMOJI_TO_SHORTCODE.get("❤️") == "heart"
  165. assert _EMOJI_TO_SHORTCODE.get("❤") == "heart"
  166. assert _EMOJI_TO_SHORTCODE.get("✅") == "white_check_mark"
  167. assert _EMOJI_TO_SHORTCODE.get("❌") == "x"
  168. # Sent when a message addresses someone else — without the mapping the
  169. # raw emoji would go out as a shortcode and the server would reject it.
  170. assert _EMOJI_TO_SHORTCODE.get("🫥") == "dotted_line_face"
  171. # -- Adapter instantiation and properties --
  172. class TestAdapterInstantiation:
  173. """Test ChattoAdapter creation and basic properties."""
  174. def test_adapter_creation(self):
  175. cfg = _make_config()
  176. adapter = ChattoAdapter(cfg)
  177. assert adapter is not None
  178. # Platform members created dynamically from a plugin name carry the
  179. # name upper-cased; the registered identity is the value.
  180. assert adapter.platform.value == ChattoConstants.PLATFORM_NAME
  181. def test_adapter_max_message_length(self):
  182. """The framework chunks via max_message_length_for_chat(), which reads
  183. the adapter-scalar MAX_MESSAGE_LENGTH and silently falls back to 4096
  184. when it is missing."""
  185. cfg = _make_config()
  186. adapter = ChattoAdapter(cfg)
  187. assert adapter.MAX_MESSAGE_LENGTH == _MAX_MESSAGE_LENGTH
  188. assert adapter.max_message_length_for_chat("room-1") == _MAX_MESSAGE_LENGTH
  189. def test_adapter_splits_long_messages(self):
  190. cfg = _make_config()
  191. adapter = ChattoAdapter(cfg)
  192. assert adapter.splits_long_messages is True
  193. def test_adapter_threads_enabled_by_default(self):
  194. """There is no capability flag for threads — Chatto threading is driven
  195. by the auto_thread setting, which defaults to on."""
  196. cfg = _make_config()
  197. adapter = ChattoAdapter(cfg)
  198. assert adapter.chatto_config.auto_thread.value is True
  199. # -- Registration and requirements --
  200. class TestRegistration:
  201. """Test plugin registration."""
  202. def test_register_called(self):
  203. ctx = _MockPluginContext()
  204. register(ctx)
  205. assert ChattoConstants.PLATFORM_NAME in ctx.registered_names
  206. assert ctx.registered_kwargs["name"] == ChattoConstants.PLATFORM_NAME
  207. assert ctx.registered_kwargs["label"] == ChattoConstants.PLATFORM_LABEL
  208. assert ctx.registered_kwargs["max_message_length"] == _MAX_MESSAGE_LENGTH
  209. def test_platform_hint_advertises_media_sending(self):
  210. """This hint is the only thing telling the model the channel can carry
  211. files — without it the agent has no idea it can deliver an image."""
  212. ctx = _MockPluginContext()
  213. register(ctx)
  214. assert "MEDIA:/absolute/path/to/file" in ctx.registered_kwargs["platform_hint"]
  215. def test_platform_hint_rules_out_markdown_for_local_files(self):
  216. """gateway's extract_images only matches https?:// — markdown pointing at
  217. a local file is never extracted and lands in the chat as literal text."""
  218. ctx = _MockPluginContext()
  219. register(ctx)
  220. hint = ctx.registered_kwargs["platform_hint"]
  221. assert "Do NOT use markdown image syntax for local files" in hint
  222. def test_startup_logs_the_capabilities(self, caplog):
  223. with caplog.at_level("INFO"):
  224. register(_MockPluginContext())
  225. logged = "\n".join(caplog.messages)
  226. assert "images" in logged
  227. assert "reactions" in logged
  228. def test_capabilities_skips_methods_we_do_not_override(self):
  229. """An inherited base fallback is not a capability — claiming it would
  230. promise the user something the adapter cannot actually do."""
  231. assert "video" in _capabilities()
  232. with patch.object(ChattoAdapter, "send_video", BasePlatformAdapter.send_video):
  233. assert "video" not in _capabilities()
  234. def test_check_requirements(self):
  235. assert check_requirements() is True
  236. def test_check_requirements_missing(self):
  237. with patch("builtins.__import__", side_effect=ImportError("no chattolib")):
  238. assert check_requirements() is False
  239. def test_validate_config(self):
  240. _clear_chatto_env()
  241. os.environ["CHATTO_BASE_URL"] = "https://chat.test"
  242. os.environ["CHATTO_LOGIN"] = "user"
  243. os.environ["CHATTO_PASSWORD"] = "pass"
  244. cfg = PlatformConfig(enabled=True, extra={"base_url": "https://chat.test"})
  245. assert validate_config(cfg) is True
  246. _clear_chatto_env()
  247. # -- Send functionality --
  248. class TestSend:
  249. """Test message sending functionality."""
  250. @pytest_asyncio.fixture
  251. def adapter(self):
  252. _clear_chatto_env()
  253. cfg = _make_config()
  254. adapter = ChattoAdapter(cfg)
  255. adapter._chatto_client = MagicMock()
  256. adapter._chatto_client.post_message = AsyncMock()
  257. adapter._token = "test-token"
  258. adapter._user_id = "bot-user-id"
  259. return adapter
  260. async def test_send_calls_post_message(self, adapter):
  261. mock_msg = MagicMock()
  262. mock_msg.id = "msg-123"
  263. adapter._chatto_client.post_message.return_value = mock_msg
  264. result = await adapter.send("room-1", "Hello world")
  265. assert result.success is True
  266. assert result.message_id == "msg-123"
  267. adapter._chatto_client.post_message.assert_called_once()
  268. async def test_send_with_thread(self, adapter):
  269. mock_msg = MagicMock()
  270. mock_msg.id = "msg-456"
  271. adapter._chatto_client.post_message.return_value = mock_msg
  272. result = await adapter.send("room-1", "Hello", reply_to="thread-123")
  273. assert result.success is True
  274. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  275. assert call_kwargs["thread_root_event_id"] == "thread-123"
  276. # -- Reactions --
  277. class TestReactions:
  278. """Test reaction functionality."""
  279. @pytest_asyncio.fixture
  280. def adapter(self):
  281. _clear_chatto_env()
  282. cfg = _make_config()
  283. adapter = ChattoAdapter(cfg)
  284. adapter._chatto_client = MagicMock()
  285. adapter._chatto_client.add_reaction = AsyncMock()
  286. adapter._chatto_client.remove_reaction = AsyncMock()
  287. adapter._token = "test-token"
  288. return adapter
  289. async def test_send_reaction(self, adapter):
  290. await adapter.add_reaction("room-1", "msg-1", "👍")
  291. adapter._chatto_client.add_reaction.assert_called_once()
  292. async def test_remove_reaction(self, adapter):
  293. await adapter.remove_reaction("room-1", "msg-1", "👍")
  294. adapter._chatto_client.remove_reaction.assert_called_once()
  295. async def test_on_processing_start_adds_eyes_reaction(self, adapter):
  296. """on_processing_start should call add_reaction with 👀."""
  297. event = MagicMock()
  298. event.message_id = "msg-1"
  299. event.source.chat_id = "room-1"
  300. await adapter.on_processing_start(event)
  301. adapter._chatto_client.add_reaction.assert_called_once()
  302. call_kwargs = adapter._chatto_client.add_reaction.call_args.kwargs
  303. assert call_kwargs["message_event_id"] == "msg-1"
  304. assert call_kwargs["room_id"] == "room-1"
  305. assert call_kwargs["emoji"] == "eyes"
  306. async def test_on_processing_start_empty_message_id(self, adapter):
  307. """on_processing_start should skip reaction when message_id is empty."""
  308. event = MagicMock()
  309. event.message_id = None
  310. event.source.chat_id = "room-1"
  311. await adapter.on_processing_start(event)
  312. adapter._chatto_client.add_reaction.assert_not_called()
  313. async def test_on_processing_start_reactions_disabled(self, adapter):
  314. """on_processing_start should skip when reactions config is False."""
  315. adapter.chatto_config.reactions.value = False
  316. event = MagicMock()
  317. event.message_id = "msg-1"
  318. event.source.chat_id = "room-1"
  319. await adapter.on_processing_start(event)
  320. adapter._chatto_client.add_reaction.assert_not_called()
  321. # -- Edit and Delete Messages --
  322. class TestMessageEditing:
  323. """Test message editing and deletion."""
  324. @pytest_asyncio.fixture
  325. def adapter(self):
  326. _clear_chatto_env()
  327. cfg = _make_config()
  328. adapter = ChattoAdapter(cfg)
  329. adapter._chatto_client = MagicMock()
  330. adapter._chatto_client.update_message = AsyncMock()
  331. adapter._chatto_client.delete_message = AsyncMock(return_value=True)
  332. adapter._token = "test-token"
  333. return adapter
  334. async def test_edit_message(self, adapter):
  335. result = await adapter.edit_message("room-1", "msg-1", "New content")
  336. assert result.success is True
  337. adapter._chatto_client.update_message.assert_called_once()
  338. call_kwargs = adapter._chatto_client.update_message.call_args.kwargs
  339. assert call_kwargs["room_id"] == "room-1"
  340. assert call_kwargs["event_id"] == "msg-1"
  341. assert call_kwargs["body"] == "New content"
  342. async def test_edit_message_marks_own_edit_seen(self, adapter):
  343. """The edit echoes back as message_edited — it must not look inbound."""
  344. mock_msg = MagicMock()
  345. mock_msg.id = "msg-1"
  346. adapter._chatto_client.update_message.return_value = mock_msg
  347. await adapter.edit_message("room-1", "msg-1", "New content")
  348. assert adapter._is_seen("msg-1") is True
  349. async def test_edit_message_too_long_refuses(self, adapter):
  350. """Overlong content must fall back to send() (which splits), not be
  351. silently truncated into a lossy edit."""
  352. result = await adapter.edit_message(
  353. "room-1", "msg-1", "x" * (_MAX_MESSAGE_LENGTH + 1),
  354. )
  355. assert result.success is False
  356. adapter._chatto_client.update_message.assert_not_called()
  357. async def test_edit_message_empty_content(self, adapter):
  358. result = await adapter.edit_message("room-1", "msg-1", "")
  359. assert result.success is False
  360. adapter._chatto_client.update_message.assert_not_called()
  361. async def test_edit_message_error_is_retryable(self, adapter):
  362. from chattolib.exceptions import ChattoError
  363. adapter._chatto_client.update_message.side_effect = ChattoError("boom")
  364. result = await adapter.edit_message("room-1", "msg-1", "New content")
  365. assert result.success is False
  366. assert result.retryable is True
  367. async def test_delete_message(self, adapter):
  368. result = await adapter.delete_message("room-1", "msg-1")
  369. assert result is True
  370. adapter._chatto_client.delete_message.assert_called_once()
  371. call_kwargs = adapter._chatto_client.delete_message.call_args.kwargs
  372. assert call_kwargs["room_id"] == "room-1"
  373. assert call_kwargs["event_id"] == "msg-1"
  374. async def test_delete_message_missing_ids(self, adapter):
  375. assert await adapter.delete_message("", "msg-1") is False
  376. assert await adapter.delete_message("room-1", "") is False
  377. adapter._chatto_client.delete_message.assert_not_called()
  378. async def test_delete_message_error_returns_false(self, adapter):
  379. from chattolib.exceptions import ChattoError
  380. adapter._chatto_client.delete_message.side_effect = ChattoError("nope")
  381. assert await adapter.delete_message("room-1", "msg-1") is False
  382. # -- Outgoing text formatting --
  383. class TestFormatMessage:
  384. """format_message() only fixes what renders wrong in Chatto."""
  385. def test_normalises_crlf(self):
  386. adapter = _make_adapter()
  387. assert adapter.format_message("a\r\nb\rc") == "a\nb\nc"
  388. def test_collapses_excess_blank_lines(self):
  389. adapter = _make_adapter()
  390. assert adapter.format_message("a\n\n\n\n\n\nb") == "a\n\n\nb"
  391. def test_leaves_markdown_untouched(self):
  392. adapter = _make_adapter()
  393. text = "**bold** `code`\n\n```py\nx = 1\n```\n- item"
  394. assert adapter.format_message(text) == text
  395. def test_empty_content(self):
  396. adapter = _make_adapter()
  397. assert adapter.format_message("") == ""
  398. # -- Handoff threads --
  399. class TestHandoffThread:
  400. """create_handoff_thread() anchors a handoff on a seed message."""
  401. @pytest_asyncio.fixture
  402. def adapter(self):
  403. adapter = _make_adapter()
  404. adapter._chatto_client.post_message = AsyncMock()
  405. adapter._chatto_client.follow_thread = AsyncMock()
  406. return adapter
  407. async def test_returns_seed_message_id(self, adapter):
  408. mock_msg = MagicMock()
  409. mock_msg.id = "seed-1"
  410. adapter._chatto_client.post_message.return_value = mock_msg
  411. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  412. result = await adapter.create_handoff_thread("room-1", "Refactor run")
  413. assert result == "seed-1"
  414. assert adapter._chatto_client.post_message.call_args.kwargs["room_id"] == "room-1"
  415. adapter._chatto_client.follow_thread.assert_called_once_with("room-1", "seed-1")
  416. # Our own seed must not come back in as inbound traffic.
  417. assert adapter._is_seen("seed-1") is True
  418. async def test_dm_has_no_threads(self, adapter):
  419. adapter._room_kinds["dm-1"] = RoomKind.DM
  420. assert await adapter.create_handoff_thread("dm-1", "x") is None
  421. adapter._chatto_client.post_message.assert_not_called()
  422. async def test_seed_post_failure(self, adapter):
  423. adapter._chatto_client.post_message.side_effect = RuntimeError("down")
  424. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  425. assert await adapter.create_handoff_thread("room-1", "x") is None
  426. # -- Native file / video / audio delivery --
  427. class TestUploadAsset:
  428. """Drives the real _upload_asset against real chattolib result types.
  429. The send_* tests stub _upload_asset out, so a wrong field name on the
  430. chattolib response was invisible to them until it hit a live server.
  431. """
  432. @pytest_asyncio.fixture
  433. def adapter(self, tmp_path):
  434. adapter = _make_adapter()
  435. self.path = tmp_path / "horse.jpg"
  436. self.path.write_bytes(b"\xff\xd8\xff" + b"x" * 100)
  437. upload = AssetUpload(upload_id="up-1", room_id="room-1")
  438. adapter._chatto_client.create_upload = AsyncMock(return_value=upload)
  439. adapter._chatto_client.upload_chunk = AsyncMock(return_value=upload)
  440. adapter._chatto_client.complete_upload = AsyncMock(return_value=(
  441. upload,
  442. Asset(id="asset-9", filename="horse.jpg", content_type="image/jpeg", size=103),
  443. ))
  444. return adapter
  445. async def test_returns_the_asset_id(self, adapter):
  446. assert await adapter._upload_asset("room-1", str(self.path)) == "asset-9"
  447. async def test_chunks_go_to_the_upload_id_from_create_upload(self, adapter):
  448. """AssetUpload calls it upload_id, not id — reading the wrong field made
  449. every upload fail with 'CreateUpload returned no upload ID'."""
  450. await adapter._upload_asset("room-1", str(self.path))
  451. assert adapter._chatto_client.upload_chunk.await_args.kwargs["upload_id"] == "up-1"
  452. async def test_missing_upload_id_is_reported(self, adapter):
  453. adapter._chatto_client.create_upload = AsyncMock(
  454. return_value=AssetUpload(upload_id="", room_id="room-1"))
  455. assert await adapter._upload_asset("room-1", str(self.path)) is None
  456. class TestNativeSends:
  457. """send_document/_video/_voice upload instead of apologising in text."""
  458. @pytest_asyncio.fixture
  459. def adapter(self):
  460. adapter = _make_adapter()
  461. adapter._chatto_client.post_message = AsyncMock()
  462. adapter._upload_asset = AsyncMock(return_value="asset-1")
  463. adapter.validate_media_delivery_path = MagicMock(side_effect=lambda p: p)
  464. mock_msg = MagicMock()
  465. mock_msg.id = "msg-1"
  466. adapter._chatto_client.post_message.return_value = mock_msg
  467. return adapter
  468. @pytest.mark.parametrize(
  469. "method,arg_name",
  470. [
  471. ("send_document", "file_path"),
  472. ("send_video", "video_path"),
  473. ("send_voice", "audio_path"),
  474. ("send_image_file", "image_path"),
  475. ],
  476. )
  477. async def test_uploads_and_attaches(self, adapter, method, arg_name):
  478. result = await getattr(adapter, method)(
  479. "room-1", **{arg_name: "/tmp/thing.bin"}, caption="here you go",
  480. )
  481. assert result.success is True
  482. adapter._upload_asset.assert_called_once_with("room-1", "/tmp/thing.bin")
  483. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  484. assert call_kwargs["attachment_asset_ids"] == ["asset-1"]
  485. assert call_kwargs["body"] == "here you go"
  486. async def test_unsafe_path_falls_back_to_notice(self, adapter):
  487. adapter.validate_media_delivery_path = MagicMock(return_value=None)
  488. adapter.send = AsyncMock(return_value=SendResult(success=True))
  489. await adapter.send_document("room-1", "/etc/shadow")
  490. adapter._upload_asset.assert_not_called()
  491. # Never echo the host path into chat.
  492. sent_text = adapter.send.call_args.args[1]
  493. assert "/etc/shadow" not in sent_text
  494. async def test_upload_failure_falls_back_to_notice(self, adapter):
  495. adapter._upload_asset = AsyncMock(return_value=None)
  496. adapter.send = AsyncMock(return_value=SendResult(success=True))
  497. await adapter.send_video("room-1", "/tmp/clip.mp4", caption="a clip")
  498. sent_text = adapter.send.call_args.args[1]
  499. assert sent_text.startswith("a clip\n")
  500. assert "/tmp/clip.mp4" not in sent_text
  501. # -- Batched image delivery --
  502. class TestSendMultipleImages:
  503. """A batch of images belongs in ONE Chatto message."""
  504. @pytest_asyncio.fixture
  505. def adapter(self):
  506. adapter = _make_adapter()
  507. adapter._chatto_client.post_message = AsyncMock()
  508. mock_msg = MagicMock()
  509. mock_msg.id = "msg-1"
  510. adapter._chatto_client.post_message.return_value = mock_msg
  511. adapter._upload_asset = AsyncMock(side_effect=["asset-1", "asset-2"])
  512. adapter.validate_media_delivery_path = MagicMock(side_effect=lambda p: p)
  513. return adapter
  514. async def test_bundles_into_single_message(self, adapter):
  515. await adapter.send_multiple_images(
  516. "room-1", [("/tmp/a.png", "first"), ("/tmp/b.png", "second")],
  517. )
  518. adapter._chatto_client.post_message.assert_called_once()
  519. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  520. assert call_kwargs["attachment_asset_ids"] == ["asset-1", "asset-2"]
  521. assert call_kwargs["body"] == "first\nsecond"
  522. async def test_single_image_uses_base_path(self, adapter):
  523. """One image is not a batch — leave it to the base implementation.
  524. Also pins the send_image_file signature: the base class calls it with
  525. ``image_path=`` as a keyword, so a renamed parameter degrades every
  526. native image send to a text notice.
  527. """
  528. adapter.send_image_file = AsyncMock(return_value=SendResult(success=True))
  529. await adapter.send_multiple_images("room-1", [("file:///tmp/a.png", "only")])
  530. adapter._upload_asset.assert_not_called()
  531. adapter.send_image_file.assert_called_once()
  532. assert adapter.send_image_file.call_args.kwargs["image_path"] == "/tmp/a.png"
  533. async def test_partial_upload_failure_still_sends_the_rest(self, adapter):
  534. adapter._upload_asset = AsyncMock(side_effect=["asset-1", None])
  535. await adapter.send_multiple_images(
  536. "room-1", [("/tmp/a.png", "first"), ("/tmp/b.png", "second")],
  537. )
  538. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  539. assert call_kwargs["attachment_asset_ids"] == ["asset-1"]
  540. async def test_file_uri_is_unquoted(self, adapter):
  541. await adapter.send_multiple_images(
  542. "room-1",
  543. [("file:///tmp/a%20b.png", ""), ("/tmp/c.png", "")],
  544. )
  545. first_path = adapter._upload_asset.call_args_list[0].args[1]
  546. assert first_path == "/tmp/a b.png"
  547. # -- Reaction event forwarding --
  548. class TestReactionForwarding:
  549. """Human reactions reach the gateway's reaction hook surface."""
  550. @pytest_asyncio.fixture
  551. def adapter(self):
  552. adapter = _make_adapter()
  553. adapter.me = _make_user("bot-user-id", "hermes_bot")
  554. return adapter
  555. def _event(self, kind, actor_id="human-1"):
  556. event = MagicMock()
  557. event.id = "evt-1"
  558. event.kind = kind
  559. event.actor_id = actor_id
  560. payload = ReactionPayload(
  561. room_id="room-1", message_event_id="msg-1", emoji="thumbsup",
  562. )
  563. # RealtimeEvent.get() only yields the payload for its own kind.
  564. event.get = MagicMock(side_effect=lambda k: payload if k == kind else None)
  565. return event
  566. async def test_forwards_added_reaction(self, adapter):
  567. handler = AsyncMock()
  568. adapter.set_reaction_handler(handler)
  569. await adapter._handle_realtime_event(self._event("reaction_added"))
  570. handler.assert_called_once()
  571. payload = handler.call_args.args[0]
  572. assert payload["event_name"] == "reaction:added"
  573. assert payload["reaction"] == "thumbsup"
  574. assert payload["channel_id"] == "room-1"
  575. assert payload["message_ts"] == "msg-1"
  576. assert payload["user_id"] == "human-1"
  577. assert payload["item_type"] == "message"
  578. async def test_forwards_removed_reaction(self, adapter):
  579. handler = AsyncMock()
  580. adapter.set_reaction_handler(handler)
  581. await adapter._handle_realtime_event(self._event("reaction_removed"))
  582. assert handler.call_args.args[0]["event_name"] == "reaction:removed"
  583. async def test_ignores_own_lifecycle_reactions(self, adapter):
  584. """👀/✅/❌ are ours — forwarding them would feed the agent its own markers."""
  585. handler = AsyncMock()
  586. adapter.set_reaction_handler(handler)
  587. await adapter._handle_realtime_event(
  588. self._event("reaction_added", actor_id="bot-user-id"),
  589. )
  590. handler.assert_not_called()
  591. async def test_no_handler_registered_is_harmless(self, adapter):
  592. await adapter._handle_realtime_event(self._event("reaction_added"))
  593. async def test_handler_exception_does_not_propagate(self, adapter):
  594. adapter.set_reaction_handler(AsyncMock(side_effect=RuntimeError("hook boom")))
  595. await adapter._handle_realtime_event(self._event("reaction_added"))
  596. # -- chat_type mapping --
  597. class TestChatTypeMapping:
  598. """RoomKind -> the gateway's chat_type vocabulary."""
  599. def test_maps_known_kinds(self):
  600. assert chat_type_for_room_kind(RoomKind.DM) is HermesChatType.DM
  601. assert chat_type_for_room_kind(RoomKind.CHANNEL) is HermesChatType.CHANNEL
  602. def test_unknown_kind_is_group_never_dm(self):
  603. """'dm' drives session isolation — never guess it for an unknown kind."""
  604. assert chat_type_for_room_kind(RoomKind.UNSPECIFIED) is HermesChatType.GROUP
  605. assert chat_type_for_room_kind(None) is HermesChatType.GROUP
  606. def test_values_match_the_gateway_vocabulary(self):
  607. """session.py:161 declares exactly these strings; SessionSource.description
  608. and the PII-redacted context prompt branch on them."""
  609. assert [t.value for t in HermesChatType] == ["dm", "group", "channel", "thread"]
  610. def test_is_a_plain_str_at_call_sites(self):
  611. assert HermesChatType.CHANNEL == "channel"
  612. assert f"{HermesChatType.DM}" == "dm"
  613. async def test_get_chat_info_reports_channel(self):
  614. adapter = _make_adapter()
  615. adapter._room_names["room-1"] = "Team"
  616. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  617. info = await adapter.get_chat_info("room-1")
  618. assert info == {"name": "Team", "type": "channel"}
  619. async def test_get_chat_info_reports_dm(self):
  620. adapter = _make_adapter()
  621. adapter._room_kinds["dm-1"] = RoomKind.DM
  622. assert (await adapter.get_chat_info("dm-1"))["type"] == "dm"
  623. async def test_dispatch_stamps_the_mapped_chat_type(self):
  624. """The value reaching build_source decides how the agent is told where
  625. it is — a raw RoomKind lands in SessionSource.description's else-branch."""
  626. adapter = _make_adapter()
  627. adapter.chatto_config.allow_all_users.value = True
  628. adapter.me = _make_user("bot-user-id", "hermes_bot")
  629. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  630. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  631. adapter.handle_message = AsyncMock()
  632. payload = _make_posted_payload()
  633. payload.fetch_message = AsyncMock(return_value=_make_message(body="hi"))
  634. await adapter._dispatch_message_posted(payload)
  635. event = adapter.handle_message.call_args.args[0]
  636. assert event.source.chat_type == "channel"
  637. # -- Presence --
  638. class TestPresence:
  639. """Presence is a server-side TTL: stop re-announcing and the bot goes offline."""
  640. def _adapter(self):
  641. adapter = _make_adapter()
  642. adapter._chatto_client.update_presence = AsyncMock()
  643. return adapter
  644. async def test_refresh_loop_keeps_reannouncing_online(self):
  645. """The bug: a single announce at connect lapses and never comes back."""
  646. adapter = self._adapter()
  647. adapter._closing = False
  648. with patch.object(ChattoConstants, "PRESENCE_REFRESH_INTERVAL", 0.01):
  649. task = asyncio.create_task(adapter._presence_refresh_loop())
  650. for _ in range(200):
  651. if adapter._chatto_client.update_presence.await_count >= 3:
  652. break
  653. await asyncio.sleep(0.01)
  654. adapter._closing = True
  655. task.cancel()
  656. try:
  657. await task
  658. except asyncio.CancelledError:
  659. pass
  660. assert adapter._chatto_client.update_presence.await_count >= 3
  661. for call in adapter._chatto_client.update_presence.await_args_list:
  662. assert call.kwargs["status"] == PresenceStatus.ONLINE
  663. async def test_refresh_survives_a_failing_call(self):
  664. """One bad tick must not kill the loop and strand the bot offline."""
  665. adapter = self._adapter()
  666. adapter._closing = False
  667. adapter._chatto_client.update_presence = AsyncMock(
  668. side_effect=[RuntimeError("boom"), None, None])
  669. with patch.object(ChattoConstants, "PRESENCE_REFRESH_INTERVAL", 0.01):
  670. task = asyncio.create_task(adapter._presence_refresh_loop())
  671. for _ in range(200):
  672. if adapter._chatto_client.update_presence.await_count >= 3:
  673. break
  674. await asyncio.sleep(0.01)
  675. adapter._closing = True
  676. task.cancel()
  677. try:
  678. await task
  679. except asyncio.CancelledError:
  680. pass
  681. assert adapter._chatto_client.update_presence.await_count >= 3
  682. async def test_announce_online_reports_failure(self):
  683. adapter = self._adapter()
  684. adapter._chatto_client.update_presence = AsyncMock(side_effect=RuntimeError("nope"))
  685. assert await adapter._announce_online() is False
  686. async def test_disconnect_does_not_broadcast_offline(self):
  687. """chattolib raises ValueError on OFFLINE — going offline means stopping."""
  688. adapter = self._adapter()
  689. adapter._chatto_client.close = AsyncMock()
  690. client = adapter._chatto_client # disconnect() drops the reference
  691. await adapter.disconnect()
  692. client.update_presence.assert_not_called()
  693. # -- Mentions of other people --
  694. class TestForeignMention:
  695. """With require_mention off the bot reads everything, so a message aimed at
  696. a named colleague would otherwise get an unsolicited answer. Acknowledge it
  697. with 🫥 and stay out of the conversation."""
  698. def _adapter(self, **overrides):
  699. adapter = _make_adapter()
  700. adapter.chatto_config.allow_all_users.value = True
  701. adapter.chatto_config.require_mention.value = False
  702. adapter.chatto_config.reactions.value = True
  703. for key, value in overrides.items():
  704. getattr(adapter.chatto_config, key).value = value
  705. adapter.me = _make_user("bot-user-id", "hermes_bot")
  706. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  707. adapter.handle_message = AsyncMock()
  708. adapter.add_reaction = AsyncMock(return_value=True)
  709. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  710. adapter._room_kinds["dm-1"] = RoomKind.DM
  711. return adapter
  712. async def _dispatch(self, adapter, body, room_id="room-1"):
  713. payload = _make_posted_payload(room_id=room_id)
  714. payload.fetch_message = AsyncMock(
  715. return_value=_make_message(body=body, room_id=room_id))
  716. await adapter._dispatch_message_posted(payload)
  717. async def test_message_for_someone_else_is_only_acknowledged(self):
  718. adapter = self._adapter()
  719. await self._dispatch(adapter, "@bob can you take a look?")
  720. adapter.handle_message.assert_not_called()
  721. adapter.add_reaction.assert_awaited_once()
  722. assert adapter.add_reaction.await_args.args[2] == "🫥"
  723. async def test_being_mentioned_alongside_someone_else_still_answers(self):
  724. adapter = self._adapter()
  725. await self._dispatch(adapter, "@bob and @hermes_bot, thoughts?")
  726. adapter.handle_message.assert_called_once()
  727. adapter.add_reaction.assert_not_awaited()
  728. async def test_broadcast_mentions_address_the_bot_too(self):
  729. adapter = self._adapter()
  730. for body in ("@here standup in 5", "@channel heads up", "@everyone hi"):
  731. adapter.handle_message.reset_mock()
  732. await self._dispatch(adapter, body)
  733. adapter.handle_message.assert_called_once()
  734. async def test_plain_message_is_unaffected(self):
  735. adapter = self._adapter()
  736. await self._dispatch(adapter, "how do I reset the cache?")
  737. adapter.handle_message.assert_called_once()
  738. async def test_dms_are_answered_even_when_they_name_someone_else(self):
  739. adapter = self._adapter()
  740. await self._dispatch(adapter, "@bob said the build is red", room_id="dm-1")
  741. adapter.handle_message.assert_called_once()
  742. async def test_require_mention_keeps_discarding_without_a_reaction(self):
  743. """The older gate wins: it drops the message before we get here, and it
  744. deliberately says nothing at all."""
  745. adapter = self._adapter(require_mention=True)
  746. await self._dispatch(adapter, "@bob can you take a look?")
  747. adapter.handle_message.assert_not_called()
  748. adapter.add_reaction.assert_not_awaited()
  749. async def test_silence_holds_when_reactions_are_disabled(self):
  750. adapter = self._adapter(reactions=False)
  751. await self._dispatch(adapter, "@bob can you take a look?")
  752. adapter.handle_message.assert_not_called()
  753. adapter.add_reaction.assert_not_awaited()
  754. # -- require_mention --
  755. class TestRequireMention:
  756. """require_mention gates channels only — a DM is already addressed at the bot."""
  757. def _adapter(self):
  758. adapter = _make_adapter()
  759. adapter.chatto_config.allow_all_users.value = True
  760. adapter.chatto_config.require_mention.value = True
  761. adapter.me = _make_user("bot-user-id", "hermes_bot")
  762. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  763. adapter.handle_message = AsyncMock()
  764. return adapter
  765. async def _dispatch(self, adapter, room_id, body):
  766. payload = _make_posted_payload(room_id=room_id)
  767. payload.fetch_message = AsyncMock(
  768. return_value=_make_message(body=body, room_id=room_id))
  769. await adapter._dispatch_message_posted(payload)
  770. async def test_channel_without_mention_is_discarded(self):
  771. adapter = self._adapter()
  772. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  773. await self._dispatch(adapter, "room-1", "hi there")
  774. adapter.handle_message.assert_not_called()
  775. async def test_channel_with_mention_is_answered(self):
  776. adapter = self._adapter()
  777. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  778. await self._dispatch(adapter, "room-1", "@hermes_bot hi there")
  779. adapter.handle_message.assert_called_once()
  780. async def test_dm_is_answered_without_a_mention(self):
  781. """The point of the room_kind check: require_mention must not mute DMs."""
  782. adapter = self._adapter()
  783. adapter._room_kinds["dm-1"] = RoomKind.DM
  784. await self._dispatch(adapter, "dm-1", "hi there")
  785. adapter.handle_message.assert_called_once()
  786. # -- Inbound attachments --
  787. class TestInboundAttachments:
  788. """Messages carrying files must reach the agent, body or not."""
  789. @pytest_asyncio.fixture
  790. def adapter(self):
  791. adapter = _make_adapter()
  792. adapter.chatto_config.allow_all_users.value = True
  793. adapter.me = _make_user("bot-user-id", "hermes_bot")
  794. adapter._room_kinds["room-1"] = RoomKind.DM
  795. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  796. adapter.handle_message = AsyncMock()
  797. adapter._download_attachment_bytes = AsyncMock(return_value=b"\x89PNG\r\n\x1a\nrest")
  798. return adapter
  799. async def test_image_attachment_becomes_media_url(self, adapter):
  800. payload = _make_posted_payload()
  801. adapter._chatto_client.get_room = AsyncMock()
  802. message = _make_message(
  803. body="look at this",
  804. attachments=[_make_attachment("shot.png", "image/png")],
  805. )
  806. payload.fetch_message = AsyncMock(return_value=message)
  807. with patch("adapter.cache_media_bytes", return_value=_cached("/cache/shot.png", "image/png", "image")):
  808. await adapter._dispatch_message_posted(payload)
  809. event = adapter.handle_message.call_args.args[0]
  810. assert event.media_urls == ["/cache/shot.png"]
  811. assert event.media_types == ["image/png"]
  812. assert event.message_type == MessageType.PHOTO
  813. async def test_attachment_only_message_is_not_dropped(self, adapter):
  814. """The empty-body early return is what silently ate file uploads."""
  815. payload = _make_posted_payload()
  816. message = _make_message(
  817. body="", attachments=[_make_attachment("report.pdf", "application/pdf")],
  818. )
  819. payload.fetch_message = AsyncMock(return_value=message)
  820. with patch("adapter.cache_media_bytes", return_value=_cached("/cache/report.pdf", "application/pdf", "document")):
  821. await adapter._dispatch_message_posted(payload)
  822. adapter.handle_message.assert_called_once()
  823. event = adapter.handle_message.call_args.args[0]
  824. assert event.message_type == MessageType.DOCUMENT
  825. assert event.media_urls == ["/cache/report.pdf"]
  826. async def test_empty_message_without_attachments_is_dropped(self, adapter):
  827. payload = _make_posted_payload()
  828. payload.fetch_message = AsyncMock(return_value=_make_message(body=""))
  829. await adapter._dispatch_message_posted(payload)
  830. adapter.handle_message.assert_not_called()
  831. async def test_download_failure_still_delivers_the_text(self, adapter):
  832. adapter._download_attachment_bytes = AsyncMock(side_effect=RuntimeError("404"))
  833. payload = _make_posted_payload()
  834. payload.fetch_message = AsyncMock(return_value=_make_message(
  835. body="see attached", attachments=[_make_attachment("a.png", "image/png")],
  836. ))
  837. await adapter._dispatch_message_posted(payload)
  838. event = adapter.handle_message.call_args.args[0]
  839. assert event.text == "see attached"
  840. assert event.media_urls == []
  841. assert event.message_type == MessageType.TEXT
  842. async def test_attachment_without_asset_url_is_skipped(self, adapter):
  843. """Videos are announced before transcoding finishes."""
  844. payload = _make_posted_payload()
  845. att = _make_attachment("clip.mp4", "video/mp4")
  846. att.asset_url = None
  847. payload.fetch_message = AsyncMock(return_value=_make_message(
  848. body="clip", attachments=[att],
  849. ))
  850. await adapter._dispatch_message_posted(payload)
  851. event = adapter.handle_message.call_args.args[0]
  852. assert event.media_urls == []
  853. adapter._download_attachment_bytes.assert_not_called()
  854. async def test_document_wins_over_image(self, adapter):
  855. """Mixed batches classify as DOCUMENT — that gates context injection."""
  856. assert adapter._message_type_for_media_kinds(["image", "document"]) is MessageType.DOCUMENT
  857. assert adapter._message_type_for_media_kinds(["image"]) is MessageType.PHOTO
  858. assert adapter._message_type_for_media_kinds(["video"]) is MessageType.VIDEO
  859. assert adapter._message_type_for_media_kinds(["audio"]) is MessageType.AUDIO
  860. assert adapter._message_type_for_media_kinds([]) is MessageType.TEXT
  861. async def test_oversized_attachment_is_rejected(self, adapter):
  862. """The gateway media cap must bound what a hostile upload can buffer."""
  863. import httpx
  864. big = get_inbound_media_max_bytes() + 1
  865. transport = httpx.MockTransport(lambda request: httpx.Response(
  866. 200, headers={"content-length": str(big)}, content=b"x",
  867. ))
  868. real_adapter = _make_adapter()
  869. real_client_cls = httpx.AsyncClient
  870. with patch("httpx.AsyncClient", lambda **kw: real_client_cls(transport=transport)):
  871. with pytest.raises(ValueError):
  872. await real_adapter._download_attachment_bytes("https://chat.example.com/a.png")
  873. # NOTE: there are deliberately no tests for get_user(), set_presence() or
  874. # set_custom_status() on the adapter. Those are not adapter responsibilities —
  875. # callers use the chattolib client directly, which exposes them (client.get_user,
  876. # client.update_presence, client.update_custom_status). The adapter only touches
  877. # presence in connect()/disconnect().
  878. # -- Room operations --
  879. class TestRoomOperations:
  880. """Test room creation and DM initiation."""
  881. @pytest_asyncio.fixture
  882. def adapter(self):
  883. _clear_chatto_env()
  884. cfg = _make_config()
  885. adapter = ChattoAdapter(cfg)
  886. adapter._chatto_client = MagicMock()
  887. # AsyncMock, not MagicMock: the adapter awaits these, and awaiting a
  888. # plain MagicMock raises TypeError, which create_room()/start_dm()
  889. # swallow into a None return.
  890. adapter._chatto_client.create_room = AsyncMock()
  891. adapter._chatto_client.start_dm = AsyncMock()
  892. adapter._token = "test-token"
  893. adapter._room_names = {}
  894. adapter._room_kinds = {}
  895. return adapter
  896. async def test_create_room(self, adapter):
  897. adapter._chatto_client.create_room.return_value = _make_room(
  898. "room-123", "Test Room", RoomKind.CHANNEL,
  899. )
  900. result = await adapter.create_room("Test Room", "A test room")
  901. assert result == "room-123"
  902. adapter._chatto_client.create_room.assert_called_once()
  903. assert adapter._room_names["room-123"] == "Test Room"
  904. async def test_start_dm(self, adapter):
  905. adapter._chatto_client.start_dm.return_value = _make_room(
  906. "dm-123", "DM with user", RoomKind.DM,
  907. )
  908. result = await adapter.start_dm("user-123")
  909. assert result == "dm-123"
  910. adapter._chatto_client.start_dm.assert_called_once()
  911. assert adapter._room_kinds["dm-123"] == RoomKind.DM
  912. # -- Constants --
  913. class TestConstants:
  914. """Test that constants are properly defined."""
  915. def test_max_message_length(self):
  916. assert _MAX_MESSAGE_LENGTH == 10000
  917. def test_seen_cap(self):
  918. assert _SEEN_CAP == 500