#!/usr/bin/env python3 """Isolated end-to-end API tests. No changes to the application's real database.""" import concurrent.futures import os import signal import http.cookiejar import json from pathlib import Path import shutil import socket import sqlite3 import subprocess import tempfile import time import urllib.request import urllib.error WEB = Path(__file__).resolve().parents[1] ARTIFACTS = WEB / 'tests/artifacts' ARTIFACTS.mkdir(exist_ok=True) checks = 0 def check(value, label): global checks checks += 1 assert value, label with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp: root = Path(tmp) for name in ['api.php', 'index.php', 'auth.php', 'callback.php', 'router.php']: shutil.copy(WEB / name, root / name) shutil.copytree(WEB / 'lib', root / 'lib', ignore=shutil.ignore_patterns('tablebase')) push_file=root/'lib/Push.php' push_file.write_text(push_file.read_text().replace(' $jobs=[];', " file_put_contents(dirname(__DIR__).'/data/push-events.jsonl',json_encode(array_values($events)).PHP_EOL,FILE_APPEND|LOCK_EX); return;\n $jobs=[];")) def push_events(): path=root/'data/push-events.jsonl' return [event for line in path.read_text().splitlines() for event in json.loads(line)] if path.exists() else [] shutil.copytree(WEB / 'assets/avatars', root / 'assets/avatars') (root / 'data').mkdir() with socket.socket() as sock: sock.bind(('127.0.0.1', 0)) port = sock.getsockname()[1] base = f'http://127.0.0.1:{port}' log = (root / 'server.log').open('w') process = subprocess.Popen(['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{port}', '-t', str(root), str(root / 'router.php')], stdout=log, stderr=log, env={**os.environ, 'PHP_CLI_SERVER_WORKERS':'4'}, start_new_session=True) class Client: def __init__(self): self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) self.csrf = None def get(self, path='/api.php'): with self.opener.open(base + path) as r: return json.load(r) def state(self): state = self.get() self.csrf = state['csrf'] return state def post(self, action, expected=200, **fields): req = urllib.request.Request(base + '/api.php', data=json.dumps({'action':action, **fields}).encode(), headers={'Content-Type':'application/json', 'X-CSRF-Token':self.csrf or ''}) try: response = self.opener.open(req) except urllib.error.HTTPError as error: response = error with response: check(response.status == expected, f'{action}: expected {expected}, got {response.status}') return json.load(response) def game(self, id): return next(g for g in self.state()['games'] if g['id'] == id) def game_action(self, action, id, **fields): g = self.game(id) return self.post(action, game=id, version=g['version'], **fields) try: for _ in range(100): try: urllib.request.urlopen(base + '/index.php').close() break except urllib.error.URLError: time.sleep(.05) config_path=root/'data/config.php' check(config_path.is_file(),'First page request creates config.php') generated=config_path.read_text() check(all(f"'{key}' => ''" in generated for key in ['base_url','client_id','client_secret']),'Generated config fields are empty') configured=generated.replace("'client_id' => ''", "'client_id' => 'fixture-client'")+'\n// Keep this server-specific comment.\n' config_path.write_text(configured) a, b = Client(), Client() check(a.state()['user']['name'] == 'test_user_1', 'Local autologin') check(config_path.read_text()==configured,'Existing configuration preserved byte-for-byte') loaded=subprocess.check_output(['php','-r', 'require $argv[1]; echo json_encode(config());',str(root/'lib/bootstrap.php')], env={**os.environ,'SYNHEX_BASE_URL':'https://example.test','SYNHEX_CLIENT_ID':'environment-client','SYNHEX_CLIENT_SECRET':'fixture-secret'},text=True) check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence') b.state(); b.post('switch_user', user='test_user_2'); b.state() check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions') check(a.state()['notificationIntroSeen'] is False,'New account has not seen notification introduction') csrf=a.csrf;a.csrf='wrong';a.post('claim_notification_intro',expected=403);a.csrf=csrf check(a.state()['notificationIntroSeen'] is False,'Invalid CSRF cannot consume introduction') same_user=Client();same_user.state() with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: claims=list(executor.map(lambda client:client.post('claim_notification_intro'),[a,same_user])) check(sum(claim['show'] for claim in claims)==1,'Exactly one concurrent session claims the introduction') check(a.state()['notificationIntroSeen'] is True and same_user.state()['notificationIntroSeen'] is True,'Seen state persists across sessions') check(a.post('claim_notification_intro')['show'] is False,'Introduction cannot be shown again') check(b.state()['notificationIntroSeen'] is False,'Introduction state belongs to the account') check(b.post('claim_notification_intro')['show'] is True,'Another account gets its own introduction') public_key=a.get('/api.php?action=push_config')['publicKey'] check(public_key==b.get('/api.php?action=push_config')['publicKey'],'Persistent server public key across sessions') subscription={'endpoint':'https://fcm.googleapis.com/fcm/send/api-fixture','keys':{'p256dh':public_key,'auth':'AAAAAAAAAAAAAAAAAAAAAA'}} a.post('push_subscribe',subscription=subscription) a.post('push_subscribe',subscription=subscription) with sqlite3.connect(root/'data/synhex.sqlite') as push_db: check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Repeated device registration does not duplicate') old_csrf=a.csrf;a.csrf='wrong';a.post('push_subscribe',subscription=subscription,expected=403);a.csrf=old_csrf a.post('push_subscribe',subscription={**subscription,'endpoint':'https://127.0.0.1/private'},expected=409) b.post('push_unsubscribe',endpoint=subscription['endpoint']) with sqlite3.connect(root/'data/synhex.sqlite') as push_db: check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Unsubscribe requires owning account') a.post('push_unsubscribe',endpoint=subscription['endpoint']) check(a.state()['user']['rating']==b.state()['user']['rating']==1200, 'Accounts start at 1200 Elo') avatars=json.loads((root/'assets/avatars/catalog.json').read_text()) check(len(avatars)==103 and sum(v['group']=='fairy' for v in avatars)==67 and sum(v['group']=='standard' for v in avatars)==36,'Retained fairy and standard avatars including White/Black') check(len({Path(v['file']).stem.casefold() for v in avatars})==len(avatars),'PNG and SVG versions of a piece appear only once') check(len({v['id'] for v in avatars})==len(avatars),'Avatar IDs are unique') check(all((root/'assets/avatars'/v['file']).read_bytes().startswith(b'\x89PNG\r\n\x1a\n') for v in avatars),'Every selectable avatar has a local PNG') initial_avatar=b.state()['user']['avatar'] check(initial_avatar in {v['id'] for v in json.loads((root/'assets/avatars/catalog.json').read_text())},'Random default avatar') a.post('set_avatar',avatar='blue-knight') check(a.state()['user']['avatar']=='blue-knight','Avatar persists across requests') check(b.state()['user']['avatar']==initial_avatar,'Avatar change affects only the signed-in user') a.post('set_avatar',avatar='../../data/config.php',expected=409) a.post('set_avatar',avatar='not-a-piece',expected=409) a.post('set_avatar',avatar=['blue-knight'],expected=409) b.post('set_avatar',avatar='purple-elephant') check(b.state()['user']['avatar']=='purple-elephant','Fairy avatar can be selected') b.post('set_avatar',avatar=None) check(b.state()['user']['avatar'] is not None,'Random avatar reset') check(any(v['id']=='white-king' for v in avatars) and any(v['id']=='black-king' for v in avatars),'White/Black standard avatars catalogued') a.post('set_avatar',avatar='white-king') check(a.state()['user']['avatar']=='white-king','White king avatar selectable') a.post('set_avatar',avatar='blue-knight') check(a.state()['user']['avatar']=='blue-knight','Restore blue knight avatar for later checks') a.post('set_piece_colors',colorMode='custom',preferredColor='Red',alternativeColor='Blue') user=a.state()['user'] check(user['colorMode']=='custom' and user['preferredColor']=='Red' and user['alternativeColor']=='Blue','Colour preference persists') a.post('set_piece_colors',colorMode='custom',preferredColor='Red',alternativeColor='Red',expected=409) a.post('set_piece_colors',colorMode='custom',preferredColor='Purple',alternativeColor='Blue',expected=409) # Conflict: a custom White vs b default — skins assigned when challenge accepted below a.post('set_piece_colors',colorMode='custom',preferredColor='White',alternativeColor='Red') b.post('set_piece_colors',colorMode='default',preferredColor='White',alternativeColor='Black') a.post('switch_user', user='admin', expected=409) old = a.csrf; a.csrf = 'wrong'; a.post('create_link', kind='match', expected=403); a.csrf = old token = a.post('create_link', kind='friend')['url'].split('=')[1] check(b.get('/api.php?invite='+token)['invite']['kind'] == 'friend', 'Friend request preview') a.post('accept_link', token=token, expected=409) b.post('accept_link', token=token) check(len(a.state()['friends']) == len(b.state()['friends']) == 1, 'Mutual friendship') check(b.state()['friends'][0]['avatar']=='blue-knight','Friends see selected avatar') b.post('accept_link', token=token, expected=409) a.post('challenge', friend='local:test_user_2') g = b.state()['games'][0]; id = g['id'] check(g['incoming'] and g['status']=='pending', 'Incoming challenge') check(push_events()[-1]['kind']=='challenge' and push_events()[-1]['user']=='local:test_user_2','Challenge notification targets recipient') notification_count=len(push_events()) a.post('challenge', friend='local:test_user_2', expected=409) a.game_action('accept', id, expected=409) check(len(push_events())==notification_count,'Rejected actions never notify') b.game_action('reject', id) check(not a.state()['games'] and not b.state()['games'], 'Reject removes both tiles') a.post('challenge', friend='local:test_user_2'); id = b.state()['games'][0]['id']; b.game_action('accept', id) ga, gb = a.game(id), b.game(id) check(gb['opponentAvatar']=='blue-knight','Game tile includes opponent avatar') check(ga.get('pieceSkinWhite') in {'White','Black','Red','Blue','Green','Yellow'} and ga.get('pieceSkinBlack') in {'White','Black','Red','Blue','Green','Yellow'},'Game stores piece skins') check(ga['pieceSkinWhite']==gb['pieceSkinWhite'] and ga['pieceSkinBlack']==gb['pieceSkinBlack'],'Both players see the same skins') check(ga['displayColor']==(ga['pieceSkinWhite'] if ga['color']=='w' else ga['pieceSkinBlack']),'displayColor matches rules side skin') # a prefers White (custom), b is default. Whichever side a is on: if a is white rules -> skins White vs Black; if a is black rules and wants White while b(default white) wants White -> conflict, a uses Red. if ga['color']=='w': check(ga['pieceSkinWhite']=='White' and ga['pieceSkinBlack']=='Black','Custom White as white rules keeps White; default black stays Black') else: check(ga['pieceSkinWhite']=='White' and ga['pieceSkinBlack']=='Red','Custom White as black rules yields to Red vs default White') a.post('set_piece_colors',colorMode='default',preferredColor='White',alternativeColor='Black') b.post('set_piece_colors',colorMode='default',preferredColor='White',alternativeColor='Black') turn_events=[e for e in push_events() if e['kind']=='turn' and e['game']==id] check(len(turn_events)==2,'Acceptance notifies both players to plan') check(ga['color'] != gb['color'] and ga['yourTurn'] and gb['yourTurn'], 'Opposite colors and simultaneous planning') check(ga['state']['phase']=='planning' and ga['state']['grid']['cols']==17,'Hex board is the playable tile') check(len(ga['state']['units'])>=4,'Each viewer sees their operatives') white, black = (a,b) if ga['color']=='w' else (b,a) black.game_action('ack_playback', id, expected=409) current = white.game(id) white.post('commit_plan', game=id, version=current['version']-1, plan={'units':{}}, expected=409) check('analysis' not in current, 'Polling carries no obsolete evaluation data') white.game_action('commit_plan', id, plan={'units':{}}) check(not white.game(id)['yourTurn'] and black.game(id)['yourTurn'], 'First lock waits for opponent') notification_count=len(push_events()) white.game_action('commit_plan', id, plan={'units':{}}, expected=409) check(len(push_events())==notification_count,'Stale duplicate commit does not notify twice') black.game_action('commit_plan', id, plan={'units':{}}) check(white.game(id)['state']['phase']=='playback','Both locks simulate an act') check(white.game(id)['yourTurn'] and black.game(id)['yourTurn'], 'Playback is both players turn') check(white.game(id)['state']['timeline']['durationMs']==3000,'Server stores a 3s playback timeline') check(black.game(id)['turnOrder']>current['turnOrder'],'Simulated act receives a later persistent queue position') black.game_action('resign', id) check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result') check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points') black.game_action('resign', id, expected=409) check(black.state()['user']['ratedGames']==1, 'Duplicate result cannot change rating twice') check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once') archive=white.get('/api.php?action=history') check(len(archive)==1 and archive[0]['outcome']=='win','Winner has saved game') saved_id=archive[0]['id'] saved=white.get(f'/api.php?action=replay&id={saved_id}') check(len(saved['positions'])>=1 and saved['positions'][0]['grid']['cols']==17,'Replay reconstructs the hex board') check(black.get('/api.php?action=history')[0]['outcome']=='loss','Both participants can access their result') check(saved['color']=='w','Replay retains player orientation') check(saved['whiteName']==white.state()['user']['name'] and saved['blackName']==black.state()['user']['name'],'Replay identifies both colors') token=saved['shareToken'] with urllib.request.urlopen(urllib.request.Request(base+'/api.php?action=shared_replay&token='+token,headers={'Host':'example.test'})) as response: public=json.load(response) check(public['positions']==saved['positions'] and public['outcome']=='White won','Anonymous shared replay contains original game') check(not {'a','b','csrf','opponentId'} & public.keys(),'Public replay exposes no account identifiers or session data') check(white.get('/api.php?action=shared_replay&token='+token)['positions']==saved['positions'],'Signed-in player can open a shared replay') check(black.get('/api.php?action=shared_replay&token='+token)['outcome']=='White won','Opponent session can open the same shared replay') with white.opener.open(base+'/?replay='+token) as response: page=response.read().decode() check('id="replay-page"' in page and 'id="your-games"' not in page,'Signed-in visitor gets the standalone replay page') check(white.get(f'/api.php?action=replay&id={saved_id}')['shareToken']==token,'Share token remains stable') try: urllib.request.urlopen(urllib.request.Request(base+'/api.php?action=shared_replay&token='+'0'*48,headers={'Host':'example.test'})) check(False,'Unknown shared token rejected') except urllib.error.HTTPError as e: check(e.code==404,'Unknown shared token rejected') old_color = a.game(id)['color'] a.game_action('rematch', id) check(b.game(id)['opponentRematch'], 'Rematch notification') b.game_action('rematch', id) check(a.game(id)['color'] != old_color and a.game(id)['state']['act']==0, 'Rematch swaps sides, same tile') turn = a if a.game(id)['yourTurn'] else b turn.game_action('offer_draw', id) other = b if turn is a else a other.game_action('accept_draw', id) check(a.state()['friends'][0]['ties']==1, 'Draw stats') check(white.state()['user']['rating']==1215 and black.state()['user']['rating']==1185, 'Rematch draw transfers one point to lower rated player') check(a.state()['user']['ratedGames']==b.state()['user']['ratedGames']==2, 'Rematch rated separately') archive=a.get('/api.php?action=history') check(len(archive)==2 and archive[0]['id']>archive[1]['id'] and archive[0]['outcome']=='draw','Rematches saved separately, newest first') check(white.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'] and white.get(f'/api.php?action=replay&id={saved_id}')['color']==saved['color'],'Rematch preserves original replay') a.game_action('rematch', id); b.game_action('exit', id) check(not a.game(id)['canRematch'], 'Exit disables opponent rematch') check(not b.state()['games'], 'Exit hides own tile only') check(len(b.get('/api.php?action=history'))==2,'Exiting keeps saved games') a.game_action('rematch', id, expected=409) a.game_action('exit', id) match = a.post('create_link',kind='match')['url'].split('=')[1] check(b.get('/api.php?invite='+match)['invite']['kind']=='match', 'Match link modal') check(b.get('/api.php?invite='+match)['invite']['kind']=='match', 'Preview/reject leaves link valid') def race_accept(_): req=urllib.request.Request(base+'/api.php',data=json.dumps({'action':'accept_link','token':match}).encode(),headers={'Content-Type':'application/json','X-CSRF-Token':b.csrf}) try: with b.opener.open(req) as response: response.read() return response.status except urllib.error.HTTPError as error: return error.code with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: statuses=list(pool.map(race_accept,range(2))) check(sorted(statuses)==[200,409],'Concurrent link acceptance starts only one game') con=sqlite3.connect(root/'data/synhex.sqlite') expired = a.post('create_link',kind='match')['url'].split('=')[1] con.execute('UPDATE links SET expires=0 WHERE token=?',(expired,));con.commit() b.post('accept_link',token=expired,expected=409) id=a.state()['games'][0]['id'] turn=a if a.game(id)['yourTurn'] else b turn.game_action('offer_draw',id) other=b if turn is a else a other.game_action('accept_draw',id) check(a.game(id)['reason']=='Draw by agreement','Draw by agreement') a.post('remove_friend',friend='local:test_user_2') check(not a.state()['friends'] and not b.state()['friends'],'Mutual removal') a.post('challenge',friend='local:test_user_2',expected=409) exported=a.get('/api.php?action=export') check(len(exported['results'])==3 and len(exported['games'])==2,'Export includes archived games/results') check('token' not in exported['profile'],'No auth token in export') check(exported['profile']['avatar']=='blue-knight','Data export includes avatar preference') for path in ['/data/synhex.sqlite','/lib/bootstrap.php','/tests/synhex.php','/data%2fsynhex.sqlite','/.htaccess']: try: urllib.request.urlopen(base+path) check(False,'Protected '+path) except urllib.error.HTTPError as e: check(e.code==403,'Protected '+path) req=urllib.request.Request(base+'/api.php',headers={'Host':'production.example'}) try: urllib.request.urlopen(req) check(False,'No production autologin') except urllib.error.HTTPError as e: check(e.code==401,'No production autologin') # Inactivity is enforced on the server, with stale confirmation protection. token=a.post('create_link',kind='match')['url'].split('=')[1] inactive_id=b.post('accept_link',token=token)['game'] a.game_action('stop_inactive',inactive_id,expected=409) con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-8*86400,inactive_id));con.commit() old=a.game(inactive_id) check(old['inactiveDays']==8,'Eight inactive days shown') turn=a if old['yourTurn'] else b turn.game_action('save_plan',inactive_id,plan={'units':{}}) a.post('stop_inactive',game=inactive_id,version=old['version'],expected=409) check(a.game(inactive_id)['inactiveDays']==0,'Plan save resets inactivity') con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-7*86400,inactive_id));con.commit() a.game_action('stop_inactive',inactive_id) check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles') check(len(a.get('/api.php?action=export')['results'])==3,'Stopped game adds no result') # Opponent statistics work without friendship; requests need recipient consent. opponent=a.state()['games'][0] check(opponent['opponentId']=='local:test_user_2' and sum(opponent['rivalry'].values())==3,'Non-friend opponent has historical rivalry statistics') a.post('send_friend_request',friend='local:test_user_1',expected=409) a.post('send_friend_request',friend='missing',expected=409) a.post('send_friend_request',friend=['invalid'],expected=409) old=a.csrf; a.csrf='wrong';a.post('send_friend_request',friend='local:test_user_2',expected=403);a.csrf=old with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: list(pool.map(lambda _:a.post('send_friend_request',friend='local:test_user_2'),range(2))) check(len(a.state()['friendRequests'])==len(b.state()['friendRequests'])==1,'Concurrent sends produce one request') check(not a.state()['friendRequests'][0]['incoming'] and b.state()['friendRequests'][0]['incoming'],'Request direction is correct') check(not a.state()['friends'] and not b.state()['friends'],'Sending request does not create friendship') check(len(a.get('/api.php?action=export')['friend_requests'])==1,'Export includes pending requests') a.post('accept_friend_request',friend='local:test_user_2',expected=409) a.post('reject_friend_request',friend='local:test_user_2',expected=409) b.post('send_friend_request',friend='local:test_user_1',expected=409) b.post('reject_friend_request',friend='local:test_user_1') check(not a.state()['friendRequests'] and not b.state()['friends'],'Rejection clears request without friendship') a.post('send_friend_request',friend='local:test_user_2') b.post('accept_friend_request',friend='local:test_user_1') check(len(a.state()['friends'])==len(b.state()['friends'])==1,'Acceptance creates bilateral friendship') check(not a.state()['friendRequests'] and not b.state()['friendRequests'],'Acceptance consumes request for both users') check({k:a.state()['friends'][0][k] for k in ['wins','losses','ties']}==opponent['rivalry'],'Friend and opponent statistics match') b.post('accept_friend_request',friend='local:test_user_1',expected=409) a.post('send_friend_request',friend='local:test_user_2',expected=409) a.post('remove_friend',friend='local:test_user_2') a.post('send_friend_request',friend='local:test_user_2') token=b.post('create_link',kind='friend')['url'].split('=')[1] a.post('accept_link',token=token) check(not a.state()['friendRequests'],'Friend link acceptance clears pending request') a.post('remove_friend',friend='local:test_user_2') # Queue requests survive sessions and never match the same user to themselves. before_count=con.execute('SELECT count(*) FROM games').fetchone()[0] a.post('join_matchmaking'); a.post('join_matchmaking') check(con.execute('SELECT count(*) FROM matchmaking').fetchone()[0]==1,'One queue entry per user') check(a.state()['matchmaking']['status']=='searching','Search persists on polling') check(con.execute('SELECT count(*) FROM games').fetchone()[0]==before_count,'No self match') a.post('cancel_matchmaking'); a.post('cancel_matchmaking') check(a.state()['matchmaking'] is None,'Cancel is persistent and idempotent') # Simultaneous joins produce one bilateral game, even without friendship. with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: list(pool.map(lambda c:c.post('join_matchmaking'),[a,b])) check(con.execute('SELECT count(*) FROM games').fetchone()[0]==before_count+1,'Concurrent joins create exactly one game') check(a.state()['matchmaking'] is None and b.state()['matchmaking'] is None,'Both entries consumed') matched=a.state()['games'][0] check(matched['id']==b.state()['games'][0]['id'] and matched['status']=='active','Match starts for both players') check(matched['color']!=b.game(matched['id'])['color'],'Matched players have opposite colors') # Set ratings and elapsed time directly rather than sleeping for minutes. con.execute('UPDATE ratings SET rating=1200 WHERE user_id=?',('local:test_user_1',)) con.execute('UPDATE ratings SET rating=1400 WHERE user_id=?',('local:test_user_2',)); con.commit() a.post('join_matchmaking'); b.post('join_matchmaking') check(a.state()['matchmaking'] and b.state()['matchmaking'],'200 point gap initially waits') con.execute('UPDATE matchmaking SET joined=? WHERE user_id=?',(int(time.time())-120,'local:test_user_1')) con.execute('UPDATE matchmaking_clock SET checked=0');con.commit() check(a.state()['matchmaking'] is not None,'Both players must allow rating gap') con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-120,)) con.execute('UPDATE matchmaking_clock SET checked=0');con.commit() check(a.state()['matchmaking'] is None and b.state()['matchmaking'] is None,'Activity matches after two minutes of widening') a.post('join_matchmaking') con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-86400,));con.commit() b.post('join_matchmaking') check(a.state()['matchmaking']['status']=='expired','Expired registration is excluded') a.post('join_matchmaking') check(a.state()['matchmaking']['status']=='searching','Expired search can restart') con.execute('UPDATE ratings SET rating=1800 WHERE user_id=?',('local:test_user_2',)) con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-3600,)) con.execute('UPDATE matchmaking_clock SET checked=0');con.commit() check(a.state()['matchmaking'] is not None,'Rating tolerance capped at 500') a.post('cancel_matchmaking');b.post('cancel_matchmaking') # An unrelated user's page activity processes the entire pool, oldest first, # choosing the closest eligible opponent and leaving unmatched entries intact. now=int(time.time()) for uid,rating,joined in [('queue:oldest',1200,now-300),('queue:far',1290,now-200),('queue:near',1220,now-100)]: con.execute('INSERT INTO users VALUES(?,?)',(uid,uid)) con.execute('INSERT INTO ratings VALUES(?,?,0)',(uid,rating)) con.execute('INSERT INTO matchmaking VALUES(?,?)',(uid,joined)) con.execute('UPDATE matchmaking_clock SET checked=0');con.commit() a.state() pair=con.execute('SELECT a,b FROM games ORDER BY id DESC LIMIT 1').fetchone() check(set(pair)=={'queue:oldest','queue:near'},'Whole pool prefers closest opponent for oldest entry') check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued') check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry') con.close() with sqlite3.connect(root/'data/synhex.sqlite') as archive_db: private_id=archive_db.execute("INSERT INTO results(game_id,a,b,winner,reason,state,ended) SELECT game_id,'queue:oldest','queue:near',NULL,'Draw','{}',ended FROM results WHERE id=?",(saved_id,)).lastrowid archive_db.execute("INSERT INTO replays(result_id,white,moves,piece_skin_white,piece_skin_black) SELECT ?, 'queue:oldest', moves, piece_skin_white, piece_skin_black FROM replays WHERE result_id=?",(private_id,saved_id)) outsider_token=os.urandom(24).hex() archive_db.execute('INSERT INTO replay_links(result_id,token) VALUES(?,?)',(private_id,outsider_token)) check(all(r['id']!=private_id for r in a.get('/api.php?action=history')),'History excludes other players games') check(a.get('/api.php?action=shared_replay&token='+outsider_token)['shared'] is True,'Signed-in outsider can view another pair\'s shared replay') try: a.get(f'/api.php?action=replay&id={private_id}') check(False,'Other players replay unavailable') except urllib.error.HTTPError as e: check(e.code==404,'Other players replay unavailable') with sqlite3.connect(root/'data/synhex.sqlite') as archive_db: blob=archive_db.execute('SELECT moves FROM replays WHERE result_id=?',(saved_id,)).fetchone()[0] if isinstance(blob,(bytes,memoryview)): blob=bytes(blob).decode() check(str(blob).startswith('{"version":1'),'Replay stores JSON act history') archive_db.execute('UPDATE results SET ended=? WHERE id=?',(int(time.time())-10*365*86400,saved_id)) check(any(r['id']==saved_id for r in a.get('/api.php?action=history')),'Old replay remains in history without a retention limit') check(a.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'],'Old replay remains fully playable') check(any(r['id']==saved_id for r in a.get('/api.php?action=export')['replays']),'Old replay remains available in exports') # Exercise the real OAuth state/session/redirect code against a local auth stub. auth_bootstrap=root/'lib/bootstrap.php' auth_bootstrap.write_text(auth_bootstrap.read_text().replace( " $ch=curl_init('https://auth.timfalken.com'.$path);", " return $path==='/api/me'?['user'=>['id'=>'oauth-fixture','username'=>'oauth_fixture']]:['access_token'=>'fixture-token','expires_in'=>86400];\n $ch=curl_init('https://auth.timfalken.com'.$path);")) config_path.write_text(config_path.read_text().replace("'client_secret' => ''", "'client_secret' => 'fixture-secret'")) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None oauth=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()),NoRedirect()) def redirect(path): try: oauth.open(base+path) raise AssertionError('Expected redirect') except urllib.error.HTTPError as error: check(error.code==302,'OAuth redirects: '+error.read().decode()) return error.headers['Location'] from urllib.parse import urlsplit,parse_qs login=redirect('/auth.php?game=42&invite='+'a'*48) oauth_state=parse_qs(urlsplit(login).query)['state'][0] callback=redirect('/callback.php?state='+oauth_state+'&code=fixture') check(parse_qs(urlsplit(callback).query)=={'game':['42'],'invite':['a'*48]},'OAuth round trip preserves game and invitation') check(urlsplit(callback).path=='/','OAuth returns to main screen') print(f'API: {checks} assertions passed.') finally: os.killpg(process.pid,signal.SIGTERM);process.wait();log.close()