summaryrefslogtreecommitdiff
path: root/test/gpu_snake_interaction.py
diff options
context:
space:
mode:
Diffstat (limited to 'test/gpu_snake_interaction.py')
-rw-r--r--test/gpu_snake_interaction.py119
1 files changed, 119 insertions, 0 deletions
diff --git a/test/gpu_snake_interaction.py b/test/gpu_snake_interaction.py
new file mode 100644
index 00000000..a3e5b2b4
--- /dev/null
+++ b/test/gpu_snake_interaction.py
@@ -0,0 +1,119 @@
+#!/usr/bin/env python3
+"""Check snake v1 migration, resize, hover and idle animation in a private GUI."""
+import argparse
+import io
+import json
+import os
+from pathlib import Path
+import subprocess
+import time
+from PIL import Image, ImageChops, ImageStat
+from ninep import Client
+from gpu_snake import wait
+from daemon import install, processes
+
+parser = argparse.ArgumentParser(description=__doc__)
+for name in ['binary', 'old_addon', 'new_addon', 'output']:
+ parser.add_argument(name, type=Path)
+args = parser.parse_args()
+root = args.output.resolve()
+root.mkdir(parents=True, mode=0o700)
+(root / 'config/pardes').mkdir(parents=True)
+(root / 'config/pardes/init').write_text('Shell /bin/bash\nMessageLinger 0\n')
+addon = root / 'snake.so'
+install(args.old_addon.resolve(), addon)
+env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')}
+env.pop('XDG_DATA_HOME', None)
+env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root), PARDES_TEST_COLS='100',
+ PARDES_TEST_ROWS='30', SDL_VIDEO_DRIVER='offscreen', PARDES_DAEMON='on')
+log = (root / 'stderr.log').open('w')
+p = subprocess.Popen([str(args.binary.resolve()), '--9p=snake'], cwd=root, env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=log, start_new_session=True)
+client = None
+try:
+ sock = root / '9p/pardes/snake'
+ wait(sock.exists)
+ client = Client(sock)
+ text = int(client.read('/pane/new'))
+ client.write(f'/pane/{text}/body', b'unsaved text preserved\n')
+ shells = wait(lambda: [line for line in client.read('/sessions').splitlines() if line.startswith(b'shell ')])
+
+ def execute(word):
+ client.write(f'/pane/{text}/exec', (word + '\n').encode())
+
+ execute(f'Addon load {addon}')
+ execute('SnakeShader')
+ client.write('/focus', str(text).encode())
+ snake = int(next(line.split()[0] for line in client.read('/index').splitlines()
+ if line.split()[1] == b'snake_shader'))
+
+ def body():
+ return client.read(f'/pane/{snake}/body').splitlines()
+
+ state = body()[:4]
+ install(args.new_addon.resolve(), addon)
+ execute('Addon reload snake_shader')
+ wait(lambda: len(body()) == 6)
+ assert body()[:4] == state, body()
+ time.sleep(.2)
+ board = body()[4]
+ execute('Addon reload snake_shader')
+ time.sleep(.2)
+ assert body()[:4] == state and body()[4] == board, body()
+
+ screen = json.loads(client.read('/screen'))
+ rows = [''.join(cell[0] for cell in screen['cells'][i:i + screen['cols']])
+ for i in range(0, len(screen['cells']), screen['cols'])]
+ tag = next(i for i, row in enumerate(rows) if 'SnakeShader' in row)
+ bottom = next((i for i in range(tag + 1, len(rows)) if ' Collapse ' in rows[i]), len(rows))
+
+ def capture(name):
+ stamp = (root / 'latest.ppm').stat().st_mtime_ns
+ wait(lambda: (root / 'latest.ppm').stat().st_mtime_ns > stamp)
+ im = Image.open(io.BytesIO((root / 'latest.ppm').read_bytes())).convert('RGB')
+ im.save(root / (name + '.png'))
+ return im.crop((0, (tag + 1) * im.height // screen['rows'], im.width, bottom * im.height // screen['rows']))
+
+ a = capture('idle-a')
+ time.sleep(.25)
+ b = capture('idle-b')
+ idle_change = sum(ImageStat.Stat(ImageChops.difference(a, b)).mean)
+ assert 0 < idle_change < 2, idle_change
+ assert body()[:4] == state, body()
+ client.write('/mousein', f'm 10 {tag + 4} 0\n'.encode())
+ wait(lambda: body()[5] != b'hover -1 -1')
+ hovered = capture('hover')
+ hover_change = sum(ImageStat.Stat(ImageChops.difference(b, hovered)).mean)
+ assert hover_change > idle_change, (hover_change, idle_change)
+ client.write('/mousein', b'm 0 0 0\n')
+ wait(lambda: body()[5] == b'hover -1 -1')
+ execute('Newcol')
+ wait(lambda: body()[4] != board)
+ assert body()[:4] == state, body()
+ assert client.read(f'/pane/{text}/body') == b'unsaved text preserved\n'
+ assert [line for line in client.read('/sessions').splitlines() if line.startswith(b'shell ')] == shells
+ result = {'state': [line.decode() for line in state], 'before': board.decode(),
+ 'after': body()[4].decode(), 'idle_pixel_change': idle_change, 'hover_pixel_change': hover_change}
+ (root / 'result.json').write_text(json.dumps(result, indent=2) + '\n')
+ print('PASS: migration, reload, resize, hover, idle animation, text and shells', result, flush=True)
+except Exception:
+ if client:
+ for path in ['/addons', '/log', '/index']:
+ print(path, client.read(path).decode(), flush=True)
+ if 'snake' in globals():
+ print('game', body(), flush=True)
+ raise
+finally:
+ if client:
+ client.socket.close()
+ if p.poll() is None:
+ p.kill()
+ p.wait(timeout=10)
+ for pid in processes(root):
+ try:
+ os.kill(pid, 9)
+ except ProcessLookupError:
+ pass
+ p.stdin.close()
+ log.close()