Files
t0sig/tests.py
T
2026-11-18 17:14:24 +00:00

108 lines
3.6 KiB
Python

import asyncio
import importlib.util
import json
import os
import sys
import tempfile
import types
import unittest
from pathlib import Path
from unittest.mock import AsyncMock, patch
from aiohttp import web
ROOT = Path(__file__).parent
class _FakeBot:
def on(self, event):
return lambda callback: callback
def start(self, **kwargs):
return self
def load_service():
settings = types.ModuleType('settings')
settings.API_ID = 1
settings.API_HASH = 'test-hash'
settings.API_TOKEN = 'test-token'
telethon = types.ModuleType('telethon')
telethon.TelegramClient = lambda *args: _FakeBot()
telethon.events = types.SimpleNamespace(NewMessage=lambda **kwargs: object())
saved = {name: sys.modules.get(name) for name in ('settings', 'telethon')}
sys.modules['settings'] = settings
sys.modules['telethon'] = telethon
try:
spec = importlib.util.spec_from_file_location('t0sig_service_under_test', ROOT / 't0sig.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
finally:
for name, previous in saved.items():
if previous is None:
sys.modules.pop(name, None)
else:
sys.modules[name] = previous
service = load_service()
class _FakeRequest:
def __init__(self, form_data):
self.form_data = form_data
async def post(self):
return self.form_data
class T0SigUpgradeTests(unittest.TestCase):
def test_suite_runs_on_supported_python(self):
self.assertEqual(sys.version_info[0], 3)
self.assertGreaterEqual(sys.version_info[:2], (3, 8))
def test_service_sources_compile_under_target_python(self):
for path in ROOT.rglob('*.py'):
if 'env' in path.parts or '.git' in path.parts or path.name == 'tests.py':
continue
with self.subTest(source=str(path.relative_to(ROOT))):
compile(path.read_bytes(), str(path), 'exec')
def test_submission_uses_aiohttp_response_and_persists_approval_record(self):
original_cwd = os.getcwd()
try:
with tempfile.TemporaryDirectory() as temp_dir:
os.chdir(temp_dir)
Path('data').mkdir()
form = {'name': 'Test User', 'message': 'A test message', 'captcha': 'tanner'}
with patch.object(service, 'message_tanner', new_callable=AsyncMock) as notify:
response = asyncio.run(service.submit(_FakeRequest(form)))
self.assertIsInstance(response, web.Response)
self.assertIn('pending approval', response.text)
notify.assert_awaited_once()
logged = json.loads(Path('data/messages.log').read_text().splitlines()[0])
self.assertEqual(logged['name'], 'Test User')
self.assertEqual(logged['message'], 'A test message')
self.assertRegex(next(reversed(service.messages)), r'^[0-9a-f]{8}$')
finally:
os.chdir(original_cwd)
def test_incomplete_submission_raises_aiohttp_bad_request(self):
with self.assertRaises(web.HTTPBadRequest):
asyncio.run(service.submit(_FakeRequest({'name': 'Test User'})))
def test_aiohttp_telethon_and_requests_apis_import(self):
import requests
from telethon import TelegramClient, events
self.assertTrue(web.Application)
self.assertTrue(requests.post)
self.assertTrue(TelegramClient)
self.assertTrue(events.NewMessage)
if __name__ == '__main__':
unittest.main()