Compare commits

...
3 Commits
Author SHA1 Message Date
Tanner ffd46f9d66 Fix Telethon event loop lifecycle 2026-11-22 17:32:13 +00:00
Tanner 38265f6201 Upgrade to Python 3.11 2026-11-18 17:52:06 +00:00
Tanner 940080106c Add Python 3.11 upgrade tests 2026-11-18 17:14:24 +00:00
4 changed files with 190 additions and 21 deletions
+3
View File
@@ -0,0 +1,3 @@
aiohttp
requests
Telethon
+47 -16
View File
@@ -1,17 +1,48 @@
aiohttp==3.6.3
async-timeout==3.0.1
attrs==21.2.0
certifi==2021.10.8
chardet==3.0.4
idna==2.10
idna-ssl==1.1.0
multidict==4.7.6
pkg-resources==0.0.0
# This file was autogenerated by uv via the following command:
# uv pip compile --python-version 3.11 -o requirements.txt requirements.in
aiohappyeyeballs==2.7.1
# via aiohttp
aiohttp==3.14.5
# via -r requirements.in
aiosignal==1.4.0
# via aiohttp
attrs==26.1.0
# via aiohttp
certifi==2026.10.23
# via requests
charset-normalizer==3.5.2
# via requests
frozenlist==1.8.0
# via
# aiohttp
# aiosignal
idna==3.20
# via
# requests
# yarl
multidict==7.2.1
# via
# aiohttp
# yarl
propcache==0.5.4
# via
# aiohttp
# yarl
pyaes==1.6.1
pyasn1==0.4.8
requests==2.25.1
rsa==4.7.2
Telethon==1.23.0
typing-extensions==3.10.0.0
urllib3==1.26.8
yarl==1.5.1
# via telethon
pyasn1==0.6.5
# via rsa
requests==2.34.2
# via -r requirements.in
rsa==4.9.1
# via telethon
telethon==1.46.0
# via -r requirements.in
typing-extensions==4.16.0
# via
# aiohttp
# aiosignal
urllib3==2.8.0
# via requests
yarl==1.25.1
# via aiohttp
+14 -5
View File
@@ -5,7 +5,6 @@ logging.basicConfig(
level=logging.DEBUG if os.environ.get('DEBUG') else logging.INFO)
import settings
import asyncio
import json
import requests
from datetime import datetime
@@ -14,7 +13,7 @@ from telethon import TelegramClient, events
from aiohttp import web
bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH).start(bot_token=settings.API_TOKEN)
bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH)
TANNER = 79316791
messages = {}
@@ -126,8 +125,18 @@ async def submit(request):
return web.Response(text='Thanks! Your message is pending approval.')
async def telegram_lifecycle(app):
# Connect Telethon on aiohttp's event loop and disconnect before it closes.
await bot.start(bot_token=settings.API_TOKEN)
try:
yield
finally:
await bot.disconnect()
app = web.Application()
app.router.add_post('/', submit)
app.cleanup_ctx.append(telegram_lifecycle)
if __name__ == '__main__':
bot.start()
app = web.Application()
app.router.add_post('/', submit)
web.run_app(app, port=8123)
+126
View File
@@ -0,0 +1,126 @@
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 __init__(self):
self.started_loop = None
self.disconnected_loop = None
def on(self, event):
return lambda callback: callback
async def start(self, **kwargs):
self.started_loop = asyncio.get_running_loop()
async def disconnect(self):
self.disconnected_loop = asyncio.get_running_loop()
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, 11))
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)
def test_telethon_starts_and_stops_on_aiohttp_lifecycle_loop(self):
async def exercise_lifecycle():
loop = asyncio.get_running_loop()
self.assertIsNone(service.bot.started_loop)
lifecycle = service.telegram_lifecycle(service.app)
await lifecycle.__anext__()
self.assertIs(service.bot.started_loop, loop)
await lifecycle.aclose()
self.assertIs(service.bot.disconnected_loop, loop)
asyncio.run(exercise_lifecycle())
if __name__ == '__main__':
unittest.main()