Compare commits

...
3 Commits
Author SHA1 Message Date
Tanner a52c1e57c5 Fix Telethon event loop lifecycle 2026-11-22 17:09:42 +00:00
Tanner 9bd30bbeec Upgrade to Python 3.11 2026-11-18 17:52:06 +00:00
Tanner bd84e34085 Add Python 3.11 upgrade tests 2026-11-18 17:14:24 +00:00
4 changed files with 173 additions and 35 deletions
+11 -1
View File
@@ -8,7 +8,7 @@ from telethon import TelegramClient, events
TANNER = 79316791 TANNER = 79316791
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)
routes = web.RouteTableDef() routes = web.RouteTableDef()
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
@@ -51,6 +51,16 @@ async def index(request):
else: else:
return web.Response(text=data) return web.Response(text=data)
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 = web.Application()
app.add_routes(routes) app.add_routes(routes)
app.cleanup_ctx.append(telegram_lifecycle)
web.run_app(app) web.run_app(app)
+3
View File
@@ -0,0 +1,3 @@
aiohttp
Telethon
validators
+39 -34
View File
@@ -1,35 +1,40 @@
aiohttp==3.7.3 # This file was autogenerated by uv via the following command:
appdirs==1.4.3 # uv pip compile --python-version 3.11 -o requirements.txt requirements.in
async-timeout==3.0.1 aiohappyeyeballs==2.7.1
attrs==20.3.0 # via aiohttp
CacheControl==0.12.6 aiohttp==3.14.5
certifi==2019.11.28 # via -r requirements.in
chardet==3.0.4 aiosignal==1.4.0
colorama==0.4.3 # via aiohttp
contextlib2==0.6.0 attrs==26.1.0
decorator==4.4.2 # via aiohttp
distlib==0.3.0 frozenlist==1.8.0
distro==1.4.0 # via
html5lib==1.0.1 # aiohttp
idna==2.8 # aiosignal
ipaddr==2.2.0 idna==3.20
lockfile==0.12.2 # via yarl
msgpack==0.6.2 multidict==7.2.1
multidict==5.1.0 # via
packaging==20.3 # aiohttp
pep517==0.8.2 # yarl
progress==1.5 propcache==0.5.4
# via
# aiohttp
# yarl
pyaes==1.6.1 pyaes==1.6.1
pyasn1==0.4.8 # via telethon
pyparsing==2.4.6 pyasn1==0.6.5
pytoml==0.1.21 # via rsa
requests==2.22.0 rsa==4.9.1
retrying==1.3.3 # via telethon
rsa==4.7.1 telethon==1.46.0
six==1.14.0 # via -r requirements.in
Telethon==1.19.5 typing-extensions==4.16.0
typing-extensions==3.7.4.3 # via
urllib3==1.25.8 # aiohttp
validators==0.18.2 # aiosignal
webencodings==0.5.1 validators==0.36.0
yarl==1.6.3 # via -r requirements.in
yarl==1.25.1
# via aiohttp
+120
View File
@@ -0,0 +1,120 @@
import asyncio
import importlib.util
import sys
import time
import types
import unittest
from pathlib import Path
from unittest.mock import patch
import validators
from aiohttp import web
class _FakeBot:
def __init__(self):
self.started_loop = None
self.disconnected_loop = None
self.handlers = []
def on(self, event):
def register(callback):
self.handlers.append((event, callback))
return callback
return register
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('greenocean_service_under_test', Path(__file__).with_name('greenocean.py'))
module = importlib.util.module_from_spec(spec)
with patch.object(web, 'run_app'):
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 GreenOceanUpgradeTests(unittest.TestCase):
def test_python_311_or_newer_runtime(self):
self.assertGreaterEqual(sys.version_info[:2], (3, 11))
def test_domain_and_url_inputs_keep_their_distinct_redirect_paths(self):
self.assertTrue(validators.domain('example.com'))
self.assertFalse(validators.url('example.com'))
self.assertTrue(validators.url('https://example.com/path'))
self.assertFalse(validators.domain('https://example.com'))
def test_index_redirects_domain_and_full_url_using_aiohttp_exceptions(self):
request = types.SimpleNamespace(headers={})
service.data_time = time.time()
service.data = 'example.com'
with self.assertRaises(web.HTTPFound) as domain_redirect:
asyncio.run(service.index(request))
self.assertEqual(domain_redirect.exception.location, 'http://example.com')
service.data = 'https://example.com/path'
with self.assertRaises(web.HTTPFound) as url_redirect:
asyncio.run(service.index(request))
self.assertEqual(url_redirect.exception.location, 'https://example.com/path')
def test_user_agent_filter_and_expired_data_fallback(self):
request = types.SimpleNamespace(headers={'User-Agent': 'Example Bot'})
with self.assertRaises(web.HTTPForbidden):
asyncio.run(service.index(request))
service.data_time = 0
request = types.SimpleNamespace(headers={})
response = asyncio.run(service.index(request))
self.assertIsInstance(response, web.FileResponse)
self.assertEqual(response.status, 200)
def test_aiohttp_and_telethon_apis_import(self):
from telethon import TelegramClient, events
self.assertTrue(web.Application)
self.assertTrue(TelegramClient)
self.assertTrue(events.NewMessage)
def test_telethon_starts_and_stops_on_the_aiohttp_event_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())
def test_service_compiles(self):
source = Path(__file__).with_name('greenocean.py').read_bytes()
compile(source, 'greenocean.py', 'exec')
if __name__ == '__main__':
unittest.main()