| 1 | #!/usr/bin/env python3 |
| 2 | """Isolated end-to-end API tests. No changes to the application's real database.""" |
| 3 | import concurrent.futures |
| 4 | import os |
| 5 | import signal |
| 6 | import http.cookiejar |
| 7 | import json |
| 8 | from pathlib import Path |
| 9 | import shutil |
| 10 | import socket |
| 11 | import sqlite3 |
| 12 | import subprocess |
| 13 | import tempfile |
| 14 | import time |
| 15 | import urllib.request |
| 16 | import urllib.error |
| 17 | |
| 18 | WEB = Path(__file__).resolve().parents[1] |
| 19 | ARTIFACTS = WEB / 'tests/artifacts' |
| 20 | ARTIFACTS.mkdir(exist_ok=True) |
| 21 | checks = 0 |
| 22 | |
| 23 | def check(value, label): |
| 24 | global checks |
| 25 | checks += 1 |
| 26 | assert value, label |
| 27 | |
| 28 | with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp: |
| 29 | root = Path(tmp) |
| 30 | for name in ['api.php', 'index.php', 'auth.php', 'callback.php', 'router.php']: |
| 31 | shutil.copy(WEB / name, root / name) |
| 32 | shutil.copytree(WEB / 'lib', root / 'lib', ignore=shutil.ignore_patterns('tablebase')) |
| 33 | shutil.copytree(WEB / 'assets/avatars', root / 'assets/avatars') |
| 34 | (root / 'data').mkdir() |
| 35 | with socket.socket() as sock: |
| 36 | sock.bind(('127.0.0.1', 0)) |
| 37 | port = sock.getsockname()[1] |
| 38 | base = f'http://127.0.0.1:{port}' |
| 39 | log = (root / 'server.log').open('w') |
| 40 | 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) |
| 41 | class Client: |
| 42 | def __init__(self): |
| 43 | self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) |
| 44 | self.csrf = None |
| 45 | def get(self, path='/api.php'): |
| 46 | with self.opener.open(base + path) as r: |
| 47 | return json.load(r) |
| 48 | def state(self): |
| 49 | state = self.get() |
| 50 | self.csrf = state['csrf'] |
| 51 | return state |
| 52 | def post(self, action, expected=200, **fields): |
| 53 | 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 ''}) |
| 54 | try: |
| 55 | response = self.opener.open(req) |
| 56 | except urllib.error.HTTPError as error: |
| 57 | response = error |
| 58 | with response: |
| 59 | check(response.status == expected, f'{action}: expected {expected}, got {response.status}') |
| 60 | return json.load(response) |
| 61 | def game(self, id): |
| 62 | return next(g for g in self.state()['games'] if g['id'] == id) |
| 63 | def game_action(self, action, id, **fields): |
| 64 | g = self.game(id) |
| 65 | return self.post(action, game=id, version=g['version'], **fields) |
| 66 | try: |
| 67 | for _ in range(100): |
| 68 | try: |
| 69 | urllib.request.urlopen(base + '/index.php').close() |
| 70 | break |
| 71 | except urllib.error.URLError: |
| 72 | time.sleep(.05) |
| 73 | config_path=root/'data/config.php' |
| 74 | check(config_path.is_file(),'First page request creates config.php') |
| 75 | generated=config_path.read_text() |
| 76 | check(all(f"'{key}' => ''" in generated for key in ['base_url','client_id','client_secret']),'Generated config fields are empty') |
| 77 | configured=generated.replace("'client_id' => ''", "'client_id' => 'fixture-client'")+'\n// Keep this server-specific comment.\n' |
| 78 | config_path.write_text(configured) |
| 79 | a, b = Client(), Client() |
| 80 | check(a.state()['user']['name'] == 'test_user_1', 'Local autologin') |
| 81 | check(config_path.read_text()==configured,'Existing configuration preserved byte-for-byte') |
| 82 | loaded=subprocess.check_output(['php','-r', |
| 83 | 'require $argv[1]; echo json_encode(config());',str(root/'lib/bootstrap.php')], |
| 84 | env={**os.environ,'MICROCHESS_BASE_URL':'https://example.test','MICROCHESS_CLIENT_ID':'environment-client','MICROCHESS_CLIENT_SECRET':'fixture-secret'},text=True) |
| 85 | 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') |
| 86 | b.state(); b.post('switch_user', user='test_user_2'); b.state() |
| 87 | check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions') |
| 88 | initial_avatar=b.state()['user']['avatar'] |
| 89 | check(initial_avatar in {v['id'] for v in json.loads((root/'assets/avatars/catalog.json').read_text())},'Random default avatar') |
| 90 | a.post('set_avatar',avatar='blue-knight') |
| 91 | check(a.state()['user']['avatar']=='blue-knight','Avatar persists across requests') |
| 92 | check(b.state()['user']['avatar']==initial_avatar,'Avatar change affects only the signed-in user') |
| 93 | a.post('set_avatar',avatar='../../data/config.php',expected=409) |
| 94 | a.post('set_avatar',avatar='not-a-piece',expected=409) |
| 95 | a.post('set_avatar',avatar=['blue-knight'],expected=409) |
| 96 | b.post('set_avatar',avatar='purple-elephant') |
| 97 | check(b.state()['user']['avatar']=='purple-elephant','Fairy avatar can be selected') |
| 98 | b.post('set_avatar',avatar=None) |
| 99 | check(b.state()['user']['avatar'] is not None,'Random avatar reset') |
| 100 | a.post('switch_user', user='admin', expected=409) |
| 101 | old = a.csrf; a.csrf = 'wrong'; a.post('create_link', kind='match', expected=403); a.csrf = old |
| 102 | token = a.post('create_link', kind='friend')['url'].split('=')[1] |
| 103 | check(b.get('/api.php?invite='+token)['invite']['kind'] == 'friend', 'Friend request preview') |
| 104 | a.post('accept_link', token=token, expected=409) |
| 105 | b.post('accept_link', token=token) |
| 106 | check(len(a.state()['friends']) == len(b.state()['friends']) == 1, 'Mutual friendship') |
| 107 | check(b.state()['friends'][0]['avatar']=='blue-knight','Friends see selected avatar') |
| 108 | b.post('accept_link', token=token, expected=409) |
| 109 | a.post('challenge', friend='local:test_user_2') |
| 110 | g = b.state()['games'][0]; id = g['id'] |
| 111 | check(g['incoming'] and g['status']=='pending', 'Incoming challenge') |
| 112 | a.post('challenge', friend='local:test_user_2', expected=409) |
| 113 | a.game_action('accept', id, expected=409) |
| 114 | b.game_action('reject', id) |
| 115 | check(not a.state()['games'] and not b.state()['games'], 'Reject removes both tiles') |
| 116 | a.post('challenge', friend='local:test_user_2'); id = b.state()['games'][0]['id']; b.game_action('accept', id) |
| 117 | ga, gb = a.game(id), b.game(id) |
| 118 | check(gb['opponentAvatar']=='blue-knight','Game tile includes opponent avatar') |
| 119 | check(ga['color'] != gb['color'] and ga['yourTurn'] != gb['yourTurn'], 'Opposite colors and one turn') |
| 120 | white, black = (a,b) if ga['color']=='w' else (b,a) |
| 121 | black.game_action('move', id, from_=4, to=8, expected=409) |
| 122 | current = white.game(id) |
| 123 | white.post('move', game=id, version=current['version'], **{'from':15,'to':7}, expected=409) |
| 124 | move = current['legal'][0] |
| 125 | check('analysis' not in current, 'Polling carries no obsolete evaluation data') |
| 126 | response = white.post('move', game=id, version=current['version'], **move) |
| 127 | check(response['feedback']['model'] == 'tactical-estimate' and response['feedback']['ply'] == 1, 'Confirmed move returns live tactical estimate') |
| 128 | check(response['feedback']['quality'] in [None, 'good', 'poor'], 'Only supported feedback values') |
| 129 | white.post('move', game=id, version=current['version'], **move, expected=409) |
| 130 | check(black.game(id)['yourTurn'], 'Turn passes') |
| 131 | black.game_action('resign', id) |
| 132 | check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result') |
| 133 | check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once') |
| 134 | old_color = a.game(id)['color'] |
| 135 | a.game_action('rematch', id) |
| 136 | check(b.game(id)['opponentRematch'], 'Rematch notification') |
| 137 | b.game_action('rematch', id) |
| 138 | check(a.game(id)['color'] != old_color and a.game(id)['state']['ply']==0, 'Rematch swaps sides, same tile') |
| 139 | turn = a if a.game(id)['yourTurn'] else b |
| 140 | turn.game_action('offer_draw', id) |
| 141 | move = turn.game(id)['legal'][0]; turn.game_action('move',id,**move) |
| 142 | other = b if turn is a else a |
| 143 | other.game_action('accept_draw', id) |
| 144 | check(a.state()['friends'][0]['ties']==1, 'Draw stats') |
| 145 | a.game_action('rematch', id); b.game_action('exit', id) |
| 146 | check(not a.game(id)['canRematch'], 'Exit disables opponent rematch') |
| 147 | check(not b.state()['games'], 'Exit hides own tile only') |
| 148 | a.game_action('rematch', id, expected=409) |
| 149 | a.game_action('exit', id) |
| 150 | match = a.post('create_link',kind='match')['url'].split('=')[1] |
| 151 | check(b.get('/api.php?invite='+match)['invite']['kind']=='match', 'Match link modal') |
| 152 | check(b.get('/api.php?invite='+match)['invite']['kind']=='match', 'Preview/reject leaves link valid') |
| 153 | def race_accept(_): |
| 154 | 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}) |
| 155 | try: |
| 156 | with b.opener.open(req) as response: |
| 157 | response.read() |
| 158 | return response.status |
| 159 | except urllib.error.HTTPError as error: |
| 160 | return error.code |
| 161 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 162 | statuses=list(pool.map(race_accept,range(2))) |
| 163 | check(sorted(statuses)==[200,409],'Concurrent link acceptance starts only one game') |
| 164 | con=sqlite3.connect(root/'data/microchess.sqlite') |
| 165 | expired = a.post('create_link',kind='match')['url'].split('=')[1] |
| 166 | con.execute('UPDATE links SET expires=0 WHERE token=?',(expired,));con.commit() |
| 167 | b.post('accept_link',token=expired,expected=409) |
| 168 | # Server-side claim with an intended move: no requirement to play it first. |
| 169 | id=a.state()['games'][0]['id'];g=a.game(id) |
| 170 | raw=json.loads(con.execute('SELECT state FROM games WHERE id=?',(id,)).fetchone()[0]);raw['halfmove']=99 |
| 171 | con.execute('UPDATE games SET state=? WHERE id=?',(json.dumps(raw),id));con.commit() |
| 172 | turn=a if g['yourTurn'] else b |
| 173 | move=next(m for m in turn.game(id)['legal'] if m['from']==18) |
| 174 | turn.game_action('claim_draw',id,**move) |
| 175 | check(a.game(id)['reason']=='50-move rule','Intended move draw claim') |
| 176 | a.post('remove_friend',friend='local:test_user_2') |
| 177 | check(not a.state()['friends'] and not b.state()['friends'],'Mutual removal') |
| 178 | a.post('challenge',friend='local:test_user_2',expected=409) |
| 179 | exported=a.get('/api.php?action=export') |
| 180 | check(len(exported['results'])==3 and len(exported['games'])==2,'Export includes archived games/results') |
| 181 | check('token' not in exported['profile'],'No auth token in export') |
| 182 | check(exported['profile']['avatar']=='blue-knight','Data export includes avatar preference') |
| 183 | for path in ['/data/microchess.sqlite','/lib/bootstrap.php','/tests/chess.php','/data%2fmicrochess.sqlite','/.htaccess']: |
| 184 | try: |
| 185 | urllib.request.urlopen(base+path) |
| 186 | check(False,'Protected '+path) |
| 187 | except urllib.error.HTTPError as e: |
| 188 | check(e.code==403,'Protected '+path) |
| 189 | req=urllib.request.Request(base+'/api.php',headers={'Host':'production.example'}) |
| 190 | try: |
| 191 | urllib.request.urlopen(req) |
| 192 | check(False,'No production autologin') |
| 193 | except urllib.error.HTTPError as e: |
| 194 | check(e.code==401,'No production autologin') |
| 195 | # Inactivity is enforced on the server, with stale confirmation protection. |
| 196 | token=a.post('create_link',kind='match')['url'].split('=')[1] |
| 197 | inactive_id=b.post('accept_link',token=token)['game'] |
| 198 | a.game_action('stop_inactive',inactive_id,expected=409) |
| 199 | con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-8*86400,inactive_id));con.commit() |
| 200 | old=a.game(inactive_id) |
| 201 | check(old['inactiveDays']==8,'Eight inactive days shown') |
| 202 | turn=a if old['yourTurn'] else b |
| 203 | turn.game_action('move',inactive_id,**turn.game(inactive_id)['legal'][0]) |
| 204 | a.post('stop_inactive',game=inactive_id,version=old['version'],expected=409) |
| 205 | check(a.game(inactive_id)['inactiveDays']==0,'Move resets inactivity') |
| 206 | con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-7*86400,inactive_id));con.commit() |
| 207 | a.game_action('stop_inactive',inactive_id) |
| 208 | check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles') |
| 209 | check(len(a.get('/api.php?action=export')['results'])==3,'Stopped game adds no result') |
| 210 | con.close() |
| 211 | print(f'API: {checks} assertions passed.') |
| 212 | finally: |
| 213 | os.killpg(process.pid,signal.SIGTERM);process.wait();log.close() |
projects-timfalken-com microchess