telegram-mcp/tests/test_portable.py
2026-11-05 14:26:28 +03:00

58 lines
3.1 KiB
Python

"""Regression tests for portable account isolation and command boundaries."""
from pathlib import Path
import os
import sys
import subprocess
import tempfile
import unittest
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'mcp_server'))
import runtime
import server
class PortableContracts(unittest.TestCase):
def test_no_credentials_leak_from_parent(self):
with patch.dict(os.environ, {'TG_SESSION': 'synthetic', 'TG_API_HASH': 'synthetic',
'TG_MAIN_SESSION': 'synthetic', 'TG_DAEMON_PROFILE': 'other'}):
env = runtime.child_environment('main')
self.assertFalse(any(k.startswith('TG_') for k in env))
def test_profile_and_config_are_explicit(self):
with tempfile.TemporaryDirectory(prefix='profile test ') as state:
with patch.dict(os.environ, {'TG_MCP_STATE_DIR': state}):
for account in ['main', 'reserve']:
cmd = runtime.cli_command(account)
self.assertEqual(cmd[cmd.index('--profile') + 1], account)
self.assertEqual(cmd[cmd.index('--config') + 1], str(Path(state) / 'config.json'))
self.assertTrue(Path(cmd[1]).is_absolute())
with patch.dict(os.environ, {'TG_MCP_STATE_DIR': 'relative'}):
with self.assertRaises(ValueError): runtime.cli_command('main')
with self.assertRaises(ValueError): runtime.cli_command('unknown')
def test_server_import_does_not_load_dotenv(self):
with tempfile.TemporaryDirectory() as directory:
Path(directory, '.env').write_text('TG_SESSION=should-not-load\n')
env = {k: v for k, v in os.environ.items() if not k.startswith('TG_')}
env['PYTHONPATH'] = str(runtime.ROOT / 'mcp_server')
result = subprocess.run([sys.executable, '-c',
'import server, os; assert "TG_SESSION" not in os.environ'], cwd=directory,
env=env, capture_output=True)
self.assertEqual(result.returncode, 0)
def test_self_identity_failure_stops_wait(self):
with patch.object(server, '_run', return_value={'ok': False}) as run:
result = server.telegram_wait_for_reply('me', 1, timeout=1, account='main')
self.assertEqual(result['code'], 'AUTH_CHECK_FAILED')
self.assertEqual(run.call_count, 1)
def test_send_text_cannot_become_cli_option(self):
with patch.object(server, '_run', return_value={'ok': True}) as run:
server.telegram_send_message('me', '--schedule=tomorrow', account='main')
self.assertEqual(run.call_args.args[0], ['message', 'send', '--', 'me', '--schedule=tomorrow'])
def test_file_caption_is_option_value_and_targets_are_positional(self):
with tempfile.NamedTemporaryFile() as f:
with patch.object(server, '_run', return_value={'ok': True}) as run:
server.telegram_send_file('me', f.name, '--help', account='main')
self.assertEqual(run.call_args.args[0], ['media', 'send', '--caption=--help', '--', 'me', f.name])