BlueGit

projects-timfalken-com microchess

Files

microchess / web / tests / integration.py

integration.py

integration.py 29.4 KiB Download Raw
1#!/usr/bin/env python3
2"""Isolated end-to-end API tests. No changes to the application's real database."""
3import concurrent.futures
4import os
5import signal
6import http.cookiejar
7import json
8from pathlib import Path
9import shutil
10import socket
11import sqlite3
12import subprocess
13import tempfile
14import time
15import urllib.request
16import urllib.error
17
18WEB = Path(__file__).resolve().parents[1]
19ARTIFACTS = WEB / 'tests/artifacts'
20ARTIFACTS.mkdir(exist_ok=True)
21checks = 0
22
23def check(value, label):
24 global checks
25 checks += 1
26 assert value, label
27
28with 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 push_file=root/'lib/Push.php'
34 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=[];"))
35 def push_events():
36 path=root/'data/push-events.jsonl'
37 return [event for line in path.read_text().splitlines() for event in json.loads(line)] if path.exists() else []
38 shutil.copytree(WEB / 'assets/avatars', root / 'assets/avatars')
39 (root / 'data').mkdir()
40 with socket.socket() as sock:
41 sock.bind(('127.0.0.1', 0))
42 port = sock.getsockname()[1]
43 base = f'http://127.0.0.1:{port}'
44 log = (root / 'server.log').open('w')
45 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)
46 class Client:
47 def __init__(self):
48 self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
49 self.csrf = None
50 def get(self, path='/api.php'):
51 with self.opener.open(base + path) as r:
52 return json.load(r)
53 def state(self):
54 state = self.get()
55 self.csrf = state['csrf']
56 return state
57 def post(self, action, expected=200, **fields):
58 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 ''})
59 try:
60 response = self.opener.open(req)
61 except urllib.error.HTTPError as error:
62 response = error
63 with response:
64 check(response.status == expected, f'{action}: expected {expected}, got {response.status}')
65 return json.load(response)
66 def game(self, id):
67 return next(g for g in self.state()['games'] if g['id'] == id)
68 def game_action(self, action, id, **fields):
69 g = self.game(id)
70 return self.post(action, game=id, version=g['version'], **fields)
71 try:
72 for _ in range(100):
73 try:
74 urllib.request.urlopen(base + '/index.php').close()
75 break
76 except urllib.error.URLError:
77 time.sleep(.05)
78 config_path=root/'data/config.php'
79 check(config_path.is_file(),'First page request creates config.php')
80 generated=config_path.read_text()
81 check(all(f"'{key}' => ''" in generated for key in ['base_url','client_id','client_secret']),'Generated config fields are empty')
82 configured=generated.replace("'client_id' => ''", "'client_id' => 'fixture-client'")+'\n// Keep this server-specific comment.\n'
83 config_path.write_text(configured)
84 a, b = Client(), Client()
85 check(a.state()['user']['name'] == 'test_user_1', 'Local autologin')
86 check(config_path.read_text()==configured,'Existing configuration preserved byte-for-byte')
87 loaded=subprocess.check_output(['php','-r',
88 'require $argv[1]; echo json_encode(config());',str(root/'lib/bootstrap.php')],
89 env={**os.environ,'MICROCHESS_BASE_URL':'https://example.test','MICROCHESS_CLIENT_ID':'environment-client','MICROCHESS_CLIENT_SECRET':'fixture-secret'},text=True)
90 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')
91 b.state(); b.post('switch_user', user='test_user_2'); b.state()
92 check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')
93 public_key=a.get('/api.php?action=push_config')['publicKey']
94 check(public_key==b.get('/api.php?action=push_config')['publicKey'],'Persistent server public key across sessions')
95 subscription={'endpoint':'https://fcm.googleapis.com/fcm/send/api-fixture','keys':{'p256dh':public_key,'auth':'AAAAAAAAAAAAAAAAAAAAAA'}}
96 a.post('push_subscribe',subscription=subscription)
97 a.post('push_subscribe',subscription=subscription)
98 with sqlite3.connect(root/'data/microchess.sqlite') as push_db:
99 check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Repeated device registration does not duplicate')
100 old_csrf=a.csrf;a.csrf='wrong';a.post('push_subscribe',subscription=subscription,expected=403);a.csrf=old_csrf
101 a.post('push_subscribe',subscription={**subscription,'endpoint':'https://127.0.0.1/private'},expected=409)
102 b.post('push_unsubscribe',endpoint=subscription['endpoint'])
103 with sqlite3.connect(root/'data/microchess.sqlite') as push_db:
104 check(push_db.execute('SELECT COUNT(*) FROM push_subscriptions').fetchone()[0]==1,'Unsubscribe requires owning account')
105 a.post('push_unsubscribe',endpoint=subscription['endpoint'])
106 check(a.state()['user']['rating']==b.state()['user']['rating']==1200, 'Accounts start at 1200 Elo')
107 avatars=json.loads((root/'assets/avatars/catalog.json').read_text())
108 check(len(avatars)==91 and sum(v['group']=='fairy' for v in avatars)==67,'Only retained fairy and colored avatars are available')
109 check(len({Path(v['file']).stem.casefold() for v in avatars})==len(avatars),'PNG and SVG versions of a piece appear only once')
110 check(len({v['id'] for v in avatars})==len(avatars),'Avatar IDs are unique')
111 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')
112 initial_avatar=b.state()['user']['avatar']
113 check(initial_avatar in {v['id'] for v in json.loads((root/'assets/avatars/catalog.json').read_text())},'Random default avatar')
114 a.post('set_avatar',avatar='blue-knight')
115 check(a.state()['user']['avatar']=='blue-knight','Avatar persists across requests')
116 check(b.state()['user']['avatar']==initial_avatar,'Avatar change affects only the signed-in user')
117 a.post('set_avatar',avatar='../../data/config.php',expected=409)
118 a.post('set_avatar',avatar='not-a-piece',expected=409)
119 a.post('set_avatar',avatar=['blue-knight'],expected=409)
120 b.post('set_avatar',avatar='purple-elephant')
121 check(b.state()['user']['avatar']=='purple-elephant','Fairy avatar can be selected')
122 b.post('set_avatar',avatar=None)
123 check(b.state()['user']['avatar'] is not None,'Random avatar reset')
124 a.post('switch_user', user='admin', expected=409)
125 old = a.csrf; a.csrf = 'wrong'; a.post('create_link', kind='match', expected=403); a.csrf = old
126 token = a.post('create_link', kind='friend')['url'].split('=')[1]
127 check(b.get('/api.php?invite='+token)['invite']['kind'] == 'friend', 'Friend request preview')
128 a.post('accept_link', token=token, expected=409)
129 b.post('accept_link', token=token)
130 check(len(a.state()['friends']) == len(b.state()['friends']) == 1, 'Mutual friendship')
131 check(b.state()['friends'][0]['avatar']=='blue-knight','Friends see selected avatar')
132 b.post('accept_link', token=token, expected=409)
133 a.post('challenge', friend='local:test_user_2')
134 g = b.state()['games'][0]; id = g['id']
135 check(g['incoming'] and g['status']=='pending', 'Incoming challenge')
136 check(push_events()[-1]['kind']=='challenge' and push_events()[-1]['user']=='local:test_user_2','Challenge notification targets recipient')
137 notification_count=len(push_events())
138 a.post('challenge', friend='local:test_user_2', expected=409)
139 a.game_action('accept', id, expected=409)
140 check(len(push_events())==notification_count,'Rejected actions never notify')
141 b.game_action('reject', id)
142 check(not a.state()['games'] and not b.state()['games'], 'Reject removes both tiles')
143 a.post('challenge', friend='local:test_user_2'); id = b.state()['games'][0]['id']; b.game_action('accept', id)
144 ga, gb = a.game(id), b.game(id)
145 check(gb['opponentAvatar']=='blue-knight','Game tile includes opponent avatar')
146 check(push_events()[-1]['kind']=='turn' and push_events()[-1]['user']==('local:test_user_1' if ga['yourTurn'] else 'local:test_user_2'),'Acceptance notifies first player')
147 check(ga['color'] != gb['color'] and ga['yourTurn'] != gb['yourTurn'], 'Opposite colors and one turn')
148 white, black = (a,b) if ga['color']=='w' else (b,a)
149 black.game_action('move', id, from_=4, to=8, expected=409)
150 current = white.game(id)
151 white.post('move', game=id, version=current['version'], **{'from':15,'to':7}, expected=409)
152 move = current['legal'][0]
153 check('analysis' not in current, 'Polling carries no obsolete evaluation data')
154 response = white.post('move', game=id, version=current['version'], **move)
155 check(response['feedback']['model'] == 'tactical-estimate' and response['feedback']['ply'] == 1, 'Confirmed move returns live tactical estimate')
156 check(response['feedback']['quality'] in [None, 'good', 'poor'], 'Only supported feedback values')
157 event=push_events()[-1]
158 check(event['kind']=='turn' and event['game']==id and event['user']==black.state()['user']['id'],'Move notifies opponent')
159 notification_count=len(push_events())
160 white.post('move', game=id, version=current['version'], **move, expected=409)
161 check(len(push_events())==notification_count,'Stale duplicate move does not notify twice')
162 check(black.game(id)['yourTurn'], 'Turn passes')
163 check(black.game(id)['turnOrder']>current['turnOrder'],'New turn receives a later persistent queue position')
164 black.game_action('resign', id)
165 check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')
166 check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points')
167 black.game_action('resign', id, expected=409)
168 check(black.state()['user']['ratedGames']==1, 'Duplicate result cannot change rating twice')
169 check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once')
170 archive=white.get('/api.php?action=history')
171 check(len(archive)==1 and archive[0]['outcome']=='win','Winner has saved game')
172 saved_id=archive[0]['id']
173 saved=white.get(f'/api.php?action=replay&id={saved_id}')
174 check(len(saved['positions'])==2 and saved['positions'][-1]['board']==white.game(id)['state']['board'],'Replay reconstructs opening and final board')
175 check(black.get('/api.php?action=history')[0]['outcome']=='loss','Both participants can access their result')
176 check(saved['color']=='w','Replay retains player orientation')
177 check(saved['whiteName']==white.state()['user']['name'] and saved['blackName']==black.state()['user']['name'],'Replay identifies both colors')
178 token=saved['shareToken']
179 with urllib.request.urlopen(urllib.request.Request(base+'/api.php?action=shared_replay&token='+token,headers={'Host':'example.test'})) as response:
180 public=json.load(response)
181 check(public['positions']==saved['positions'] and public['outcome']=='White won','Anonymous shared replay contains original game')
182 check(not {'a','b','csrf','opponentId'} & public.keys(),'Public replay exposes no account identifiers or session data')
183 check(white.get('/api.php?action=shared_replay&token='+token)['positions']==saved['positions'],'Signed-in player can open a shared replay')
184 check(black.get('/api.php?action=shared_replay&token='+token)['outcome']=='White won','Opponent session can open the same shared replay')
185 with white.opener.open(base+'/?replay='+token) as response:
186 page=response.read().decode()
187 check('id="replay-page"' in page and 'id="your-games"' not in page,'Signed-in visitor gets the standalone replay page')
188 check(white.get(f'/api.php?action=replay&id={saved_id}')['shareToken']==token,'Share token remains stable')
189 try:
190 urllib.request.urlopen(urllib.request.Request(base+'/api.php?action=shared_replay&token='+'0'*48,headers={'Host':'example.test'}))
191 check(False,'Unknown shared token rejected')
192 except urllib.error.HTTPError as e:
193 check(e.code==404,'Unknown shared token rejected')
194
195 old_color = a.game(id)['color']
196 a.game_action('rematch', id)
197 check(b.game(id)['opponentRematch'], 'Rematch notification')
198 b.game_action('rematch', id)
199 check(a.game(id)['color'] != old_color and a.game(id)['state']['ply']==0, 'Rematch swaps sides, same tile')
200 turn = a if a.game(id)['yourTurn'] else b
201 turn.game_action('offer_draw', id)
202 move = turn.game(id)['legal'][0]; turn.game_action('move',id,**move)
203 other = b if turn is a else a
204 other.game_action('accept_draw', id)
205 check(a.state()['friends'][0]['ties']==1, 'Draw stats')
206 check(white.state()['user']['rating']==1215 and black.state()['user']['rating']==1185, 'Rematch draw transfers one point to lower rated player')
207 check(a.state()['user']['ratedGames']==b.state()['user']['ratedGames']==2, 'Rematch rated separately')
208 archive=a.get('/api.php?action=history')
209 check(len(archive)==2 and archive[0]['id']>archive[1]['id'] and archive[0]['outcome']=='draw','Rematches saved separately, newest first')
210 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')
211 a.game_action('rematch', id); b.game_action('exit', id)
212 check(not a.game(id)['canRematch'], 'Exit disables opponent rematch')
213 check(not b.state()['games'], 'Exit hides own tile only')
214 check(len(b.get('/api.php?action=history'))==2,'Exiting keeps saved games')
215 a.game_action('rematch', id, expected=409)
216 a.game_action('exit', id)
217 match = a.post('create_link',kind='match')['url'].split('=')[1]
218 check(b.get('/api.php?invite='+match)['invite']['kind']=='match', 'Match link modal')
219 check(b.get('/api.php?invite='+match)['invite']['kind']=='match', 'Preview/reject leaves link valid')
220 def race_accept(_):
221 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})
222 try:
223 with b.opener.open(req) as response:
224 response.read()
225 return response.status
226 except urllib.error.HTTPError as error:
227 return error.code
228 with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
229 statuses=list(pool.map(race_accept,range(2)))
230 check(sorted(statuses)==[200,409],'Concurrent link acceptance starts only one game')
231 con=sqlite3.connect(root/'data/microchess.sqlite')
232 expired = a.post('create_link',kind='match')['url'].split('=')[1]
233 con.execute('UPDATE links SET expires=0 WHERE token=?',(expired,));con.commit()
234 b.post('accept_link',token=expired,expected=409)
235 # Server-side claim with an intended move: no requirement to play it first.
236 id=a.state()['games'][0]['id'];g=a.game(id)
237 raw=json.loads(con.execute('SELECT state FROM games WHERE id=?',(id,)).fetchone()[0]);raw['halfmove']=99
238 con.execute('UPDATE games SET state=? WHERE id=?',(json.dumps(raw),id));con.commit()
239 turn=a if g['yourTurn'] else b
240 move=next(m for m in turn.game(id)['legal'] if m['from']==18)
241 turn.game_action('claim_draw',id,**move)
242 check(a.game(id)['reason']=='50-move rule','Intended move draw claim')
243 a.post('remove_friend',friend='local:test_user_2')
244 check(not a.state()['friends'] and not b.state()['friends'],'Mutual removal')
245 a.post('challenge',friend='local:test_user_2',expected=409)
246 exported=a.get('/api.php?action=export')
247 check(len(exported['results'])==3 and len(exported['games'])==2,'Export includes archived games/results')
248 check('token' not in exported['profile'],'No auth token in export')
249 check(exported['profile']['avatar']=='blue-knight','Data export includes avatar preference')
250 for path in ['/data/microchess.sqlite','/lib/bootstrap.php','/tests/chess.php','/data%2fmicrochess.sqlite','/.htaccess']:
251 try:
252 urllib.request.urlopen(base+path)
253 check(False,'Protected '+path)
254 except urllib.error.HTTPError as e:
255 check(e.code==403,'Protected '+path)
256 req=urllib.request.Request(base+'/api.php',headers={'Host':'production.example'})
257 try:
258 urllib.request.urlopen(req)
259 check(False,'No production autologin')
260 except urllib.error.HTTPError as e:
261 check(e.code==401,'No production autologin')
262 # Inactivity is enforced on the server, with stale confirmation protection.
263 token=a.post('create_link',kind='match')['url'].split('=')[1]
264 inactive_id=b.post('accept_link',token=token)['game']
265 a.game_action('stop_inactive',inactive_id,expected=409)
266 con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-8*86400,inactive_id));con.commit()
267 old=a.game(inactive_id)
268 check(old['inactiveDays']==8,'Eight inactive days shown')
269 turn=a if old['yourTurn'] else b
270 turn.game_action('move',inactive_id,**turn.game(inactive_id)['legal'][0])
271 a.post('stop_inactive',game=inactive_id,version=old['version'],expected=409)
272 check(a.game(inactive_id)['inactiveDays']==0,'Move resets inactivity')
273 con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-7*86400,inactive_id));con.commit()
274 a.game_action('stop_inactive',inactive_id)
275 check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles')
276 check(len(a.get('/api.php?action=export')['results'])==3,'Stopped game adds no result')
277 # Opponent statistics work without friendship; requests need recipient consent.
278 opponent=a.state()['games'][0]
279 check(opponent['opponentId']=='local:test_user_2' and sum(opponent['rivalry'].values())==3,'Non-friend opponent has historical rivalry statistics')
280 a.post('send_friend_request',friend='local:test_user_1',expected=409)
281 a.post('send_friend_request',friend='missing',expected=409)
282 a.post('send_friend_request',friend=['invalid'],expected=409)
283 old=a.csrf; a.csrf='wrong';a.post('send_friend_request',friend='local:test_user_2',expected=403);a.csrf=old
284 with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
285 list(pool.map(lambda _:a.post('send_friend_request',friend='local:test_user_2'),range(2)))
286 check(len(a.state()['friendRequests'])==len(b.state()['friendRequests'])==1,'Concurrent sends produce one request')
287 check(not a.state()['friendRequests'][0]['incoming'] and b.state()['friendRequests'][0]['incoming'],'Request direction is correct')
288 check(not a.state()['friends'] and not b.state()['friends'],'Sending request does not create friendship')
289 check(len(a.get('/api.php?action=export')['friend_requests'])==1,'Export includes pending requests')
290 a.post('accept_friend_request',friend='local:test_user_2',expected=409)
291 a.post('reject_friend_request',friend='local:test_user_2',expected=409)
292 b.post('send_friend_request',friend='local:test_user_1',expected=409)
293 b.post('reject_friend_request',friend='local:test_user_1')
294 check(not a.state()['friendRequests'] and not b.state()['friends'],'Rejection clears request without friendship')
295 a.post('send_friend_request',friend='local:test_user_2')
296 b.post('accept_friend_request',friend='local:test_user_1')
297 check(len(a.state()['friends'])==len(b.state()['friends'])==1,'Acceptance creates bilateral friendship')
298 check(not a.state()['friendRequests'] and not b.state()['friendRequests'],'Acceptance consumes request for both users')
299 check({k:a.state()['friends'][0][k] for k in ['wins','losses','ties']}==opponent['rivalry'],'Friend and opponent statistics match')
300 b.post('accept_friend_request',friend='local:test_user_1',expected=409)
301 a.post('send_friend_request',friend='local:test_user_2',expected=409)
302 a.post('remove_friend',friend='local:test_user_2')
303 a.post('send_friend_request',friend='local:test_user_2')
304 token=b.post('create_link',kind='friend')['url'].split('=')[1]
305 a.post('accept_link',token=token)
306 check(not a.state()['friendRequests'],'Friend link acceptance clears pending request')
307 a.post('remove_friend',friend='local:test_user_2')
308 # Queue requests survive sessions and never match the same user to themselves.
309 before_count=con.execute('SELECT count(*) FROM games').fetchone()[0]
310 a.post('join_matchmaking'); a.post('join_matchmaking')
311 check(con.execute('SELECT count(*) FROM matchmaking').fetchone()[0]==1,'One queue entry per user')
312 check(a.state()['matchmaking']['status']=='searching','Search persists on polling')
313 check(con.execute('SELECT count(*) FROM games').fetchone()[0]==before_count,'No self match')
314 a.post('cancel_matchmaking'); a.post('cancel_matchmaking')
315 check(a.state()['matchmaking'] is None,'Cancel is persistent and idempotent')
316 # Simultaneous joins produce one bilateral game, even without friendship.
317 with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
318 list(pool.map(lambda c:c.post('join_matchmaking'),[a,b]))
319 check(con.execute('SELECT count(*) FROM games').fetchone()[0]==before_count+1,'Concurrent joins create exactly one game')
320 check(a.state()['matchmaking'] is None and b.state()['matchmaking'] is None,'Both entries consumed')
321 matched=a.state()['games'][0]
322 check(matched['id']==b.state()['games'][0]['id'] and matched['status']=='active','Match starts for both players')
323 check(matched['color']!=b.game(matched['id'])['color'],'Matched players have opposite colors')
324 # Set ratings and elapsed time directly rather than sleeping for minutes.
325 con.execute('UPDATE ratings SET rating=1200 WHERE user_id=?',('local:test_user_1',))
326 con.execute('UPDATE ratings SET rating=1400 WHERE user_id=?',('local:test_user_2',)); con.commit()
327 a.post('join_matchmaking'); b.post('join_matchmaking')
328 check(a.state()['matchmaking'] and b.state()['matchmaking'],'200 point gap initially waits')
329 con.execute('UPDATE matchmaking SET joined=? WHERE user_id=?',(int(time.time())-120,'local:test_user_1'))
330 con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()
331 check(a.state()['matchmaking'] is not None,'Both players must allow rating gap')
332 con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-120,))
333 con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()
334 check(a.state()['matchmaking'] is None and b.state()['matchmaking'] is None,'Activity matches after two minutes of widening')
335 a.post('join_matchmaking')
336 con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-86400,));con.commit()
337 b.post('join_matchmaking')
338 check(a.state()['matchmaking']['status']=='expired','Expired registration is excluded')
339 a.post('join_matchmaking')
340 check(a.state()['matchmaking']['status']=='searching','Expired search can restart')
341 con.execute('UPDATE ratings SET rating=1800 WHERE user_id=?',('local:test_user_2',))
342 con.execute('UPDATE matchmaking SET joined=?',(int(time.time())-3600,))
343 con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()
344 check(a.state()['matchmaking'] is not None,'Rating tolerance capped at 500')
345 a.post('cancel_matchmaking');b.post('cancel_matchmaking')
346 # An unrelated user's page activity processes the entire pool, oldest first,
347 # choosing the closest eligible opponent and leaving unmatched entries intact.
348 now=int(time.time())
349 for uid,rating,joined in [('queue:oldest',1200,now-300),('queue:far',1290,now-200),('queue:near',1220,now-100)]:
350 con.execute('INSERT INTO users VALUES(?,?)',(uid,uid))
351 con.execute('INSERT INTO ratings VALUES(?,?,0)',(uid,rating))
352 con.execute('INSERT INTO matchmaking VALUES(?,?)',(uid,joined))
353 con.execute('UPDATE matchmaking_clock SET checked=0');con.commit()
354 a.state()
355 pair=con.execute('SELECT a,b FROM games ORDER BY id DESC LIMIT 1').fetchone()
356 check(set(pair)=={'queue:oldest','queue:near'},'Whole pool prefers closest opponent for oldest entry')
357 check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued')
358 check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry')
359 con.close()
360 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
361 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
362 archive_db.execute("INSERT INTO replays SELECT ?,'queue:oldest',moves FROM replays WHERE result_id=?",(private_id,saved_id))
363 outsider_token=os.urandom(24).hex()
364 archive_db.execute('INSERT INTO replay_links(result_id,token) VALUES(?,?)',(private_id,outsider_token))
365 check(all(r['id']!=private_id for r in a.get('/api.php?action=history')),'History excludes other players games')
366 check(a.get('/api.php?action=shared_replay&token='+outsider_token)['shared'] is True,'Signed-in outsider can view another pair\'s shared replay')
367 try:
368 a.get(f'/api.php?action=replay&id={private_id}')
369 check(False,'Other players replay unavailable')
370 except urllib.error.HTTPError as e:
371 check(e.code==404,'Other players replay unavailable')
372 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
373 check(archive_db.execute('SELECT length(moves) FROM replays WHERE result_id=?',(saved_id,)).fetchone()[0]==23,'One move uses two bytes plus initial position')
374 archive_db.execute('UPDATE results SET ended=? WHERE id=?',(int(time.time())-10*365*86400,saved_id))
375 check(any(r['id']==saved_id for r in a.get('/api.php?action=history')),'Old replay remains in history without a retention limit')
376 check(a.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'],'Old replay remains fully playable')
377 check(any(r['id']==saved_id for r in a.get('/api.php?action=export')['replays']),'Old replay remains available in exports')
378 # Exercise the real OAuth state/session/redirect code against a local auth stub.
379 auth_bootstrap=root/'lib/bootstrap.php'
380 auth_bootstrap.write_text(auth_bootstrap.read_text().replace(
381 " $ch=curl_init('https://auth.timfalken.com'.$path);",
382 " 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);"))
383 config_path.write_text(config_path.read_text().replace("'client_secret' => ''", "'client_secret' => 'fixture-secret'"))
384 class NoRedirect(urllib.request.HTTPRedirectHandler):
385 def redirect_request(self, req, fp, code, msg, headers, newurl): return None
386 oauth=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()),NoRedirect())
387 def redirect(path):
388 try:
389 oauth.open(base+path)
390 raise AssertionError('Expected redirect')
391 except urllib.error.HTTPError as error:
392 check(error.code==302,'OAuth redirects: '+error.read().decode())
393 return error.headers['Location']
394 from urllib.parse import urlsplit,parse_qs
395 login=redirect('/auth.php?game=42&invite='+'a'*48)
396 oauth_state=parse_qs(urlsplit(login).query)['state'][0]
397 callback=redirect('/callback.php?state='+oauth_state+'&code=fixture')
398 check(parse_qs(urlsplit(callback).query)=={'game':['42'],'invite':['a'*48]},'OAuth round trip preserves game and invitation')
399 check(urlsplit(callback).path=='/','OAuth returns to main screen')
400 print(f'API: {checks} assertions passed.')
401 finally:
402 os.killpg(process.pid,signal.SIGTERM);process.wait();log.close()