120 lines
6.5 KiB
Python
120 lines
6.5 KiB
Python
"""Contract checks without Telegram writes or credentials in test output."""
|
|
import importlib.util
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import unittest
|
|
import sys
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "mcp_server"))
|
|
from unittest.mock import patch
|
|
|
|
spec = importlib.util.spec_from_file_location("telegram_server", Path(__file__).resolve().parents[1] / "mcp_server" / "server.py")
|
|
server = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(server)
|
|
|
|
|
|
class TelegramContracts(unittest.TestCase):
|
|
def test_story_validation_and_dispatch(self):
|
|
with patch.object(server, "_stories_call", return_value={"ok": True}) as call:
|
|
self.assertTrue(server.telegram_list_stories("https://t.me/example_channel", limit=5, account="main")["ok"])
|
|
self.assertEqual(call.call_args.args[0]["chat"], "example_channel")
|
|
self.assertEqual(call.call_args.args[1], "main")
|
|
call.reset_mock()
|
|
for kwargs in [{"chat": "--help"}, {"chat": "example_channel", "kind": "active", "offset_id": 1},
|
|
{"chat": "example_channel", "limit": 101}]:
|
|
self.assertFalse(server.telegram_list_stories(**kwargs)["ok"])
|
|
self.assertFalse(server.telegram_get_story("example_channel", 0)["ok"])
|
|
self.assertFalse(server.telegram_download_story_media("example_channel", -1)["ok"])
|
|
call.assert_not_called()
|
|
|
|
def test_story_worker_uses_owning_daemon(self):
|
|
with patch.object(server, "_run", return_value={"ok": True, "data": {"stories": []}}) as call:
|
|
self.assertTrue(server._stories_call({"action": "list"}, "main")["ok"])
|
|
self.assertEqual(call.call_args.args[0][:3], ["bridge", "call", "stories"])
|
|
self.assertEqual(call.call_args.args[1], "main")
|
|
|
|
def test_html_and_schedule_keep_account_and_single_run(self):
|
|
with patch.object(server, "_run", return_value={"ok": False, "code": "TIMEOUT"}) as call:
|
|
self.assertFalse(server.telegram_send_html("me", "<b>Test</b>", "main")["ok"])
|
|
call.assert_called_once()
|
|
call.reset_mock()
|
|
self.assertFalse(server.telegram_schedule_message("me", "fixture", "2030-01-01T00:00:00Z", "reserve")["ok"])
|
|
call.assert_called_once()
|
|
self.assertEqual(call.call_args.args[1], "reserve")
|
|
|
|
def test_post_links(self):
|
|
for link, expected in [
|
|
("https://t.me/example_channel/475", ("example_channel", "475")),
|
|
("https://t.me/s/example_channel/475?single", ("example_channel", "475")),
|
|
("https://t.me/c/12345/99", ("-10012345", "99")),
|
|
("https://t.me/c/12345/7/99", ("-10012345", "99")),
|
|
("https://t.me/forum/7/99", ("forum", "99")),
|
|
]:
|
|
self.assertEqual(server._message_target(link, None), expected)
|
|
|
|
def test_bad_targets_never_connect(self):
|
|
with patch.object(server, "_run") as run:
|
|
for chat, ids in [("https://evil.test/a/1", None), ("https://t.me/a", None),
|
|
("--help", "1"), ("example_channel", "0"), ("example_channel", "1,abc"),
|
|
("https://t.me/a/1", "2")]:
|
|
self.assertFalse(server.telegram_get_messages(chat, ids)["ok"])
|
|
run.assert_not_called()
|
|
|
|
def test_partial_failure_keeps_successes(self):
|
|
body = {"ok": True, "data": {"messages": [{"id": 1}], "partial": True,
|
|
"errors": [{"input": "2", "code": "NOT_FOUND"}]}}
|
|
with patch.object(server, "_tg_env", return_value={"TG_SESSION": "test"}), \
|
|
patch.object(server.subprocess, "run", return_value=subprocess.CompletedProcess([], 1, json.dumps(body), "")):
|
|
result = server._invoke(["message", "get", "me", "1,2"], "main")
|
|
self.assertFalse(result["ok"])
|
|
self.assertEqual(result["code"], "PARTIAL_FAILURE")
|
|
self.assertEqual(result["data"], body["data"])
|
|
|
|
def test_send_timeout_is_never_replayed(self):
|
|
with patch.object(server, "_ensure_daemon", return_value={"ok": True}), \
|
|
patch.object(server, "_tg_env", return_value={"TG_SESSION": "test"}), \
|
|
patch.object(server.subprocess, "run", side_effect=subprocess.TimeoutExpired("tg", 1)) as run:
|
|
result = server.telegram_send_message("me", "synthetic", account="main")
|
|
self.assertEqual(result["code"], "TIMEOUT")
|
|
self.assertEqual(run.call_count, 1)
|
|
self.assertIn("--daemon", run.call_args.args[0])
|
|
|
|
def test_dead_daemon_does_not_send(self):
|
|
with patch.object(server, "_ensure_daemon", return_value={"ok": False, "code": "DAEMON_NOT_READY"}), \
|
|
patch.object(server, "_invoke", return_value={"ok": False, "code": "DAEMON_NOT_RUNNING"}) as invoke:
|
|
self.assertFalse(server.telegram_send_message("me", "synthetic", "main")["ok"])
|
|
self.assertEqual(invoke.call_count, 1)
|
|
|
|
def test_only_proven_nondispatch_starts_daemon(self):
|
|
with patch.object(server, "_ensure_daemon", return_value={"ok": True}) as ensure, \
|
|
patch.object(server, "_invoke", side_effect=[
|
|
{"ok": False, "code": "DAEMON_NOT_RUNNING"}, {"ok": True, "data": {"id": 1}},
|
|
]) as invoke:
|
|
self.assertTrue(server.telegram_send_message("me", "synthetic", "main")["ok"])
|
|
self.assertEqual(invoke.call_count, 2)
|
|
ensure.assert_called_once_with("main")
|
|
|
|
def test_daemon_start_race_rechecks_status(self):
|
|
ready = {"ok": True, "data": {"running": True, "connected": True, "capabilities": ["execute"]}}
|
|
with patch.object(server, "_invoke", side_effect=[
|
|
{"ok": True, "data": {"running": False}},
|
|
{"ok": False, "code": "DAEMON_ALREADY_RUNNING"}, ready,
|
|
]):
|
|
self.assertEqual(server._ensure_daemon("main"), ready)
|
|
|
|
def test_fields_validation_before_network(self):
|
|
with patch.object(server, "_run") as run:
|
|
self.assertFalse(server.telegram_read_history("me", fields="id;rm")["ok"])
|
|
self.assertFalse(server.telegram_read_history("me", output_format="xml")["ok"])
|
|
run.assert_not_called()
|
|
|
|
def test_no_unstructured_output_leak(self):
|
|
with patch.object(server, "_tg_env", return_value={"TG_SESSION": "test"}), \
|
|
patch.object(server.subprocess, "run", return_value=subprocess.CompletedProcess([], 1, "private payload", "private error")):
|
|
result = server._invoke(["daemon", "status"], "main")
|
|
self.assertNotIn("private", json.dumps(result))
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|