diff --git a/teledynmap.py b/teledynmap.py index 4169129..b59f775 100644 --- a/teledynmap.py +++ b/teledynmap.py @@ -6,7 +6,7 @@ import re import settings from telethon import TelegramClient, events -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) web = None api = lambda route: settings.DYNMAP_ADDRESS + route md5 = lambda name: int(hashlib.md5(name.encode()).hexdigest(), 16) @@ -58,9 +58,7 @@ async def new_message(event): logging.exception('Problem sending message to dynmap:') -async def main(): - global web - web = aiohttp.ClientSession() +async def bridge_loop(): last_time = 0 last_msg = '' logging.info('Bridge loaded') @@ -93,5 +91,18 @@ async def main(): await asyncio.sleep(1) -with bot: - bot.loop.run_until_complete(main()) + +async def main(): + global web + await bot.start(bot_token=settings.API_TOKEN) + try: + async with aiohttp.ClientSession() as session: + web = session + await bridge_loop() + finally: + web = None + await bot.disconnect() + + +if __name__ == '__main__': + asyncio.run(main()) diff --git a/tests.py b/tests.py index 4aef117..e16ed75 100644 --- a/tests.py +++ b/tests.py @@ -1,8 +1,10 @@ +import asyncio import importlib.util import sys import types import unittest from pathlib import Path +from unittest.mock import patch import aiohttp @@ -10,26 +12,19 @@ import aiohttp ROOT = Path(__file__).parent -class _FakeLoop: - def run_until_complete(self, coroutine): - coroutine.close() - - class _FakeBot: def __init__(self): - self.loop = _FakeLoop() + self.started_loop = None + self.disconnected_loop = None def on(self, event): return lambda callback: callback - def start(self, **kwargs): - return self + async def start(self, **kwargs): + self.started_loop = asyncio.get_running_loop() - def __enter__(self): - return self - - def __exit__(self, *args): - return False + async def disconnect(self): + self.disconnected_loop = asyncio.get_running_loop() def load_service(): @@ -91,6 +86,21 @@ class TeleDynmapUpgradeTests(unittest.TestCase): self.assertGreaterEqual(expected % len(service.emojis), 0) self.assertLess(expected % len(service.emojis), len(service.emojis)) + def test_telethon_and_http_session_share_loop_and_are_closed(self): + class StopBridge(Exception): + pass + + async def stop_bridge(): + raise StopBridge + + with patch.object(service, 'bridge_loop', stop_bridge): + with self.assertRaises(StopBridge): + asyncio.run(service.main()) + + self.assertIsNotNone(service.bot.started_loop) + self.assertIs(service.bot.disconnected_loop, service.bot.started_loop) + self.assertIsNone(service.web) + if __name__ == '__main__': unittest.main()