"""Execute actual HTTP handlers, without production startup side effects.""" import ast import asyncio import json import logging import sqlite3 import threading import unittest from pathlib import Path from types import SimpleNamespace from aiohttp import web ROOT = Path(__file__).resolve().parents[1] def namespace(names, **dependencies): tree = ast.parse((ROOT / 'bot' / 'webapp' / 'server.py').read_text(encoding='utf-8')) found = {node.name: node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))} body = [] for name in names: node = found[name] node.decorator_list = [] body.append(node) env = {'asyncio': asyncio, 'sqlite3': sqlite3, 'web': web, 'log': logging.getLogger('http-contract'), 'BOT_DB': '/temporary/bot.db', 'NEWAPI_DB': '/temporary/gateway.db', **dependencies} exec(compile(ast.fix_missing_locations(ast.Module(body=body, type_ignores=[])), '', 'exec'), env) return env class RankingHTTPTests(unittest.IsolatedAsyncioTestCase): async def test_all_kinds_forward_query_and_execute_off_event_loop(self): loop_thread = threading.get_ident() for kind in ('referrals', 'requests', 'tokens', 'models'): calls = [] def top(*args): calls.append((args, threading.get_ident())) return {'top': [{'pos': 1, 'value': 123}], 'kind': kind} env = namespace(['_db_busy', 'api_top'], rankings=SimpleNamespace(top=top)) response = await env['api_top'](SimpleNamespace(query={ 'kind': kind, 'period': 'week', 'limit': '12'})) self.assertEqual(response.status, 200) self.assertEqual(json.loads(response.body)['kind'], kind) self.assertEqual(calls[0][0], ('/temporary/bot.db', '/temporary/gateway.db', kind, 'week', None, '12')) self.assertNotEqual(calls[0][1], loop_thread) async def test_legacy_default_is_not_replaced_with_other_metric(self): calls = [] def top(*args): calls.append(args) return {'top': [], 'kind': 'referrals', 'period': 'all'} env = namespace(['_db_busy', 'api_top'], rankings=SimpleNamespace(top=top)) response = await env['api_top'](SimpleNamespace(query={})) self.assertEqual(response.status, 200) self.assertEqual(calls[0][2:], (None, None, None, None)) async def test_bad_parameter_is_400(self): def top(*_args): raise ValueError('invalid kind') env = namespace(['_db_busy', 'api_top'], rankings=SimpleNamespace(top=top)) response = await env['api_top'](SimpleNamespace(query={'kind': 'malformed'})) self.assertEqual(response.status, 400) self.assertEqual(json.loads(response.body)['error'], 'bad_request') async def test_busy_is_503_not_success_with_empty_leaderboard(self): def top(*_args): raise sqlite3.OperationalError('database is locked') env = namespace(['_db_busy', 'api_top'], rankings=SimpleNamespace(top=top)) with self.assertLogs('http-contract', level='ERROR'): response = await env['api_top'](SimpleNamespace(query={'kind': 'tokens'})) self.assertEqual(response.status, 503) data = json.loads(response.body) self.assertEqual(data['error'], 'db_busy') self.assertNotIn('top', data) async def test_live_routes_point_to_active_handlers(self): tree = ast.parse((ROOT / 'bot/webapp/server.py').read_text(encoding='utf-8')) routes = {} for node in ast.walk(tree): if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in ('add_get', 'add_post') and len(node.args) >= 2 and isinstance(node.args[0], ast.Constant) and isinstance(node.args[1], ast.Name)): routes[(node.func.attr, node.args[0].value)] = node.args[1].id self.assertEqual(routes[('add_get', '/api/top')], 'api_top') self.assertEqual(routes[('add_get', '/api/bonus')], 'api_bonus') self.assertEqual(routes[('add_post', '/api/daily')], 'api_daily') if __name__ == '__main__': unittest.main(verbosity=2)