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 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('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_service_source_compiles(self): source = Path(__file__).with_name('greenocean.py').read_bytes() compile(source, 'greenocean.py', 'exec') if __name__ == '__main__': unittest.main()