Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
126 lines
5.8 KiB
Python
126 lines
5.8 KiB
Python
"""Daily HTTP boundary contracts: server-authoritative values and honest state."""
|
|
import json
|
|
import sqlite3
|
|
import unittest
|
|
from types import SimpleNamespace
|
|
from test_http_contract import namespace
|
|
|
|
|
|
class Request(dict):
|
|
def __init__(self, body=None, fail=False):
|
|
super().__init__(uid=42)
|
|
self.body = {} if body is None else body
|
|
self.fail = fail
|
|
|
|
async def json(self):
|
|
if self.fail:
|
|
raise ValueError('invalid JSON')
|
|
return self.body
|
|
|
|
|
|
def daily_namespace(payload, calls):
|
|
def status(*args, **kwargs):
|
|
calls.append(('status', args, kwargs))
|
|
return dict(payload)
|
|
def claim(*args, **kwargs):
|
|
calls.append(('claim', args, kwargs))
|
|
return dict(payload)
|
|
return namespace(['_db_busy', '_json_body', '_daily_status_sync', '_daily_claim_sync',
|
|
'_daily_http_status', 'api_bonus', 'api_daily'],
|
|
daily_checkin=SimpleNamespace(status=status, claim=claim),
|
|
quest_economy=SimpleNamespace(earned_rank=lambda *args: 2),
|
|
BADGES={}, RANK_REFS={}, REF_NEW_ID_MIN=9_000_000_000)
|
|
|
|
|
|
class DailyHTTPTests(unittest.IsolatedAsyncioTestCase):
|
|
async def test_get_only_reads_status_and_preserves_pending(self):
|
|
payload = {'ok': True, 'claimed': True, 'paid': False, 'pending': True, 'face': 3}
|
|
calls = []
|
|
env = daily_namespace(payload, calls)
|
|
response = await env['api_bonus'](Request())
|
|
self.assertEqual(response.status, 200)
|
|
self.assertEqual(json.loads(response.body), payload)
|
|
self.assertEqual([call[0] for call in calls], ['status'])
|
|
self.assertEqual(calls[0][1][2], 42)
|
|
self.assertEqual(response.headers.get('Cache-Control'), 'no-store')
|
|
|
|
async def test_post_ignores_client_uid_face_rank_and_amount(self):
|
|
payload = {'ok': True, 'claimed': True, 'paid': True, 'pending': False,
|
|
'face': 2, 'units': 12_000_000, 'usd': 24}
|
|
calls = []
|
|
env = daily_namespace(payload, calls)
|
|
response = await env['api_daily'](Request({'uid': 999, 'face': 6, 'value': 6,
|
|
'rank': 999, 'units': 999999999}))
|
|
self.assertEqual(response.status, 200)
|
|
self.assertEqual(json.loads(response.body), payload)
|
|
self.assertEqual(calls, [('claim', ('/temporary/bot.db', '/temporary/gateway.db', 42, 2),
|
|
{'source': 'miniapp'})])
|
|
|
|
async def test_repeated_paid_claim_is_200_with_original_result(self):
|
|
payload = {'ok': True, 'claimed': True, 'paid': True, 'already': True,
|
|
'pending': False, 'face': 1, 'units': 5_000_000, 'usd': 10}
|
|
calls = []
|
|
env = daily_namespace(payload, calls)
|
|
response = await env['api_daily'](Request())
|
|
self.assertEqual(response.status, 200)
|
|
self.assertEqual(json.loads(response.body), payload)
|
|
self.assertEqual(len(calls), 1)
|
|
|
|
async def test_pending_failed_credit_is_503_not_paid(self):
|
|
payload = {'ok': False, 'error': 'error', 'claimed': True, 'paid': False,
|
|
'pending': True, 'face': 4}
|
|
calls = []
|
|
env = daily_namespace(payload, calls)
|
|
response = await env['api_daily'](Request())
|
|
self.assertEqual(response.status, 503)
|
|
self.assertFalse(json.loads(response.body)['paid'])
|
|
|
|
async def test_blocked_and_no_wallet_have_distinct_failure_statuses(self):
|
|
for error, expected in [('blocked', 403), ('user', 403), ('wallet', 409)]:
|
|
calls = []
|
|
env = daily_namespace({'ok': False, 'error': error}, calls)
|
|
response = await env['api_daily'](Request())
|
|
self.assertEqual(response.status, expected, error)
|
|
|
|
async def test_malformed_json_is_rejected_before_claim(self):
|
|
calls = []
|
|
env = daily_namespace({'ok': True}, calls)
|
|
with self.assertRaises(Exception) as caught:
|
|
await env['api_daily'](Request(fail=True))
|
|
self.assertEqual(getattr(caught.exception, 'status', None), 400)
|
|
self.assertEqual(calls, [])
|
|
|
|
async def test_sqlite_failure_is_503_for_both_boundaries(self):
|
|
def busy(_uid):
|
|
raise sqlite3.OperationalError('database is locked')
|
|
for handler, worker in [('api_bonus', '_daily_status_sync'),
|
|
('api_daily', '_daily_claim_sync')]:
|
|
calls = []
|
|
env = daily_namespace({'ok': True}, calls)
|
|
env[worker] = busy
|
|
with self.assertLogs('http-contract', level='ERROR'):
|
|
response = await env[handler](Request())
|
|
self.assertEqual(response.status, 503)
|
|
self.assertEqual(json.loads(response.body)['error'], 'db_busy')
|
|
self.assertEqual(calls, [])
|
|
|
|
async def test_retired_games_stay_retired(self):
|
|
import ast
|
|
from test_http_contract import ROOT
|
|
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):
|
|
if node.func.attr.startswith('add_') and len(node.args) >= 2:
|
|
path, handler = node.args[:2]
|
|
if isinstance(path, ast.Constant) and isinstance(handler, ast.Name):
|
|
routes[(node.func.attr, path.value)] = handler.id
|
|
self.assertEqual(routes[('add_get', '/api/bonus')], 'api_bonus')
|
|
self.assertEqual(routes[('add_post', '/api/daily')], 'api_daily')
|
|
self.assertEqual(routes[('add_post', '/api/spin')], 'api_retired_bonus')
|
|
self.assertEqual(routes[('add_post', '/api/task')], 'api_retired_bonus')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main(verbosity=2)
|