#!/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') 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', '-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,'MICROCHESS_BASE_URL':'https://example.test','MICROCHESS_CLIENT_ID':'environment-client','MICROCHESS_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') 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') 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') a.post('challenge', friend='local:test_user_2', expected=409) a.game_action('accept', id, expected=409) 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['color'] != gb['color'] and ga['yourTurn'] != gb['yourTurn'], 'Opposite colors and one turn') white, black = (a,b) if ga['color']=='w' else (b,a) black.game_action('move', id, from_=4, to=8, expected=409) current = white.game(id) white.post('move', game=id, version=current['version'], **{'from':15,'to':7}, expected=409) move = current['legal'][0] white.post('move', game=id, version=current['version'], **move) white.post('move', game=id, version=current['version'], **move, expected=409) check(black.game(id)['yourTurn'], 'Turn passes') black.game_action('resign', id) check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result') check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once') 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']['ply']==0, 'Rematch swaps sides, same tile') turn = a if a.game(id)['yourTurn'] else b turn.game_action('offer_draw', id) move = turn.game(id)['legal'][0]; turn.game_action('move',id,**move) other = b if turn is a else a other.game_action('accept_draw', id) check(a.state()['friends'][0]['ties']==1, 'Draw stats') 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') 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/microchess.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) # Server-side claim with an intended move: no requirement to play it first. id=a.state()['games'][0]['id'];g=a.game(id) raw=json.loads(con.execute('SELECT state FROM games WHERE id=?',(id,)).fetchone()[0]);raw['halfmove']=99 con.execute('UPDATE games SET state=? WHERE id=?',(json.dumps(raw),id));con.commit() turn=a if g['yourTurn'] else b move=next(m for m in turn.game(id)['legal'] if m['from']==18) turn.game_action('claim_draw',id,**move) check(a.game(id)['reason']=='50-move rule','Intended move draw claim') 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/microchess.sqlite','/lib/bootstrap.php','/tests/chess.php','/data%2fmicrochess.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('move',inactive_id,**turn.game(inactive_id)['legal'][0]) a.post('stop_inactive',game=inactive_id,version=old['version'],expected=409) check(a.game(inactive_id)['inactiveDays']==0,'Move 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') con.close() print(f'API: {checks} assertions passed.') finally: os.killpg(process.pid,signal.SIGTERM);process.wait();log.close()