forked from Blendman974/faceclaw
Remove some failing tests that were accidentally retained form experiments or other branches
This commit is contained in:
1 parent
07828db0bf
commit
183adf5a43
6 files changed
+3
-744
No files matched your search
@@ -1,154 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
|
||||
function load(file, requireModule, globals = {}) {
|
||||
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
|
||||
const js = ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText;
|
||||
const context = { exports: {}, require: requireModule, ...globals };
|
||||
vm.runInNewContext(js, context, { filename: file });
|
||||
return context.exports;
|
||||
}
|
||||
|
||||
const textwrap = load('app/graphics/textwrap.ts');
|
||||
const graphics = load('app/graphics/image.ts', () => textwrap);
|
||||
const { BdfFont } = load('app/graphics/bdffont.ts', () => ({}));
|
||||
const font = (size) => BdfFont.parse(fs.readFileSync(
|
||||
path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
|
||||
const small = font(12);
|
||||
const large = font(24);
|
||||
|
||||
function compass({ style, width = 576, height = 260 } = {}) {
|
||||
const settings = new Map(style === undefined ? [] : [['compass.style', style]]);
|
||||
let listener;
|
||||
let window;
|
||||
let renders = 0;
|
||||
let pops = 0;
|
||||
class RecordingImage extends graphics.GrayImage {
|
||||
lines = [];
|
||||
texts = [];
|
||||
drawLine(...args) { this.lines.push(args); super.drawLine(...args); }
|
||||
drawText(font, x, y, text, value) {
|
||||
this.texts.push({ x, y, text, value });
|
||||
super.drawText(font, x, y, text, value);
|
||||
}
|
||||
}
|
||||
const modules = {
|
||||
'../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
|
||||
'../../graphics/image': { ...graphics, GrayImage: RecordingImage },
|
||||
'../../graphics/textwrap': textwrap,
|
||||
'../../native/settings-store': {
|
||||
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
|
||||
setStringSetting: (key, value) => settings.set(key, value),
|
||||
},
|
||||
'../../native/compass': {
|
||||
COMPASS_CHANGED: 1, COMPASS_CALIBRATION_STARTED: 2, COMPASS_CALIBRATION_COMPLETE: 3,
|
||||
addCompassListener: (fn) => { listener = fn; return () => {}; },
|
||||
setCompassEnabled() {},
|
||||
},
|
||||
'../../ui/metrics': { lineStep: (font) => font.lineHeight + 2 },
|
||||
'../../ui/shell/geometry': { screenCenterInViewportX: () => width - 320 },
|
||||
'../../ui/shell/in-process-window': {
|
||||
YieldAtRootLayer: class { constructor(layer) { return layer; } },
|
||||
createInProcessWindow: (options) => { window = options; return { requestRender: () => renders++ }; },
|
||||
},
|
||||
'../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
|
||||
'../../native/location-permissions': { hasLocationPermission: () => false },
|
||||
'./calibration': { isCompassCalibrated: () => true, normalizeHeading: (n) => ((n % 360) + 360) % 360 },
|
||||
'./calibration-layer': {},
|
||||
'./compass-rose': load('app/apps/compass/compass-rose.ts', {
|
||||
'../../graphics/image': { ...graphics, GrayImage: RecordingImage },
|
||||
'./calibration': { normalizeHeading: (n) => ((n % 360) + 360) % 360 },
|
||||
}),
|
||||
'./declination': { onDeclinationChanged: () => () => {} },
|
||||
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (n) => ({ displayDegrees: n }) },
|
||||
};
|
||||
const app = load('app/apps/compass/compass-app.ts', (name) => {
|
||||
assert.ok(name in modules, `Unexpected dependency: ${name}`);
|
||||
return modules[name];
|
||||
}, { setInterval: () => 1, clearInterval() {} });
|
||||
const ctx = { stack: { getBaseSize: () => ({ width, height }), pop: () => pops++ } };
|
||||
const open = () => app.createCompassAppWindow({ onClosed() {} });
|
||||
open();
|
||||
return {
|
||||
settings, open,
|
||||
menu: () => window.menuItems(),
|
||||
toggle: () => window.menuItems().find((item) => item.label.startsWith('Style:')).onSelect(ctx),
|
||||
paint: () => window.baseLayer.paint(ctx),
|
||||
heading: (degrees) => listener({ command: 1, headingDegrees: degrees }),
|
||||
renders: () => renders,
|
||||
pops: () => pops,
|
||||
};
|
||||
}
|
||||
|
||||
test('Circle is the default; the context menu switches, repaints and remembers the style', () => {
|
||||
const app = compass();
|
||||
assert.equal(app.menu()[0].label, 'Style: Circle');
|
||||
const before = app.renders();
|
||||
app.toggle();
|
||||
assert.equal(app.menu()[0].label, 'Style: Strip');
|
||||
assert.equal(app.settings.get('compass.style'), 'strip');
|
||||
assert.equal(app.renders(), before + 1);
|
||||
assert.equal(app.pops(), 1);
|
||||
app.open();
|
||||
assert.equal(app.menu()[0].label, 'Style: Strip');
|
||||
app.toggle();
|
||||
assert.equal(app.menu()[0].label, 'Style: Circle');
|
||||
assert.equal(compass({ style: 'unknown' }).menu()[0].label, 'Style: Circle');
|
||||
});
|
||||
|
||||
test('switching styles preserves the numeric readout and status at every display size', () => {
|
||||
for (const [width, height] of [[576, 260], [576, 452], [640, 452]]) {
|
||||
const app = compass({ width, height });
|
||||
app.heading(82);
|
||||
const circle = app.paint();
|
||||
app.toggle();
|
||||
const strip = app.paint();
|
||||
assert.deepEqual(strip.texts.slice(0, 2), circle.texts);
|
||||
assert.deepEqual(circle.texts.map((item) => item.text), ['82° E', 'Magnetic heading']);
|
||||
}
|
||||
});
|
||||
|
||||
test('strip ticks are 5 degrees apart on the full-display 23 degree scale', () => {
|
||||
for (const width of [576, 640]) {
|
||||
const app = compass({ style: 'strip', width });
|
||||
app.heading(90);
|
||||
const image = app.paint();
|
||||
const top = image.lines[0][1];
|
||||
const ticks = image.lines.filter(([x0, y0, x1]) => x0 === x1 && y0 === top);
|
||||
assert.deepEqual(ticks.map(([x]) => x), [80, 85, 90, 95, 100]
|
||||
.map((bearing) => Math.round(width - 320 + (bearing - 90) * 640 / 23))
|
||||
.filter((x) => x >= 0 && x < width));
|
||||
assert.equal(image.lines[0][0], 0);
|
||||
assert.equal(image.lines[0][2], width - 1);
|
||||
assert.equal(image.lines[1][1], image.height - 4);
|
||||
assert.ok(image.texts.some(({ text }) => text === 'E'));
|
||||
}
|
||||
});
|
||||
|
||||
test('bearings scroll continuously through north with wrapped labels', () => {
|
||||
const app = compass({ style: 'strip' });
|
||||
const northX = (heading) => {
|
||||
app.heading(heading);
|
||||
const image = app.paint();
|
||||
const north = image.texts.find(({ text }) => text === 'N');
|
||||
assert.ok(north);
|
||||
assert.ok(image.texts.some(({ text }) => text === '355°'));
|
||||
assert.ok(image.texts.some(({ text }) => text === '5°'));
|
||||
return north.x;
|
||||
};
|
||||
assert.ok(Math.abs(northX(359.9) - northX(0.1) - 0.2 * 640 / 23) <= 1);
|
||||
});
|
||||
|
||||
test('a strip waiting for sensor data shows the rails without invented bearings', () => {
|
||||
const app = compass({ style: 'strip' });
|
||||
const image = app.paint();
|
||||
assert.deepEqual(image.texts.map(({ text }) => text), ['--°', 'Waiting for compass data…']);
|
||||
assert.equal(image.lines.length, 2);
|
||||
assert.ok(image.lines[0][4] < 105);
|
||||
});
|
||||
@@ -1,188 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
const root = path.join(__dirname, '..');
|
||||
function load(file, modules = {}, globals = {}, extra = '') {
|
||||
const context = { exports: {}, console, ...globals, require(name) {
|
||||
assert.ok(name in modules, `Unexpected dependency ${name}`); return modules[name];
|
||||
} };
|
||||
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(root, file), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText + extra, context);
|
||||
return context.exports;
|
||||
}
|
||||
const gestures = load('app/ui/gestures.ts');
|
||||
const textwrap = load('app/graphics/textwrap.ts');
|
||||
const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
|
||||
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
|
||||
const font = size => BdfFont.parse(fs.readFileSync(path.join(root, `app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
|
||||
const fonts = { terminus24: font(24), terminus32: font(32) }, small = font(18);
|
||||
function worker(game) {
|
||||
let now = 10000, id = 0, renders = 0;
|
||||
const timers = new Map(), posts = [];
|
||||
const schedule = (fn, delay, repeat) => { timers.set(++id, { fn, at: now + delay, repeat }); return id; };
|
||||
const cancel = id => timers.delete(id);
|
||||
const global = { postMessage: m => posts.push(m) };
|
||||
class Menu {
|
||||
constructor(options) { this.options = options; this.opened = false; }
|
||||
isOpen() { return this.opened; }
|
||||
open() { this.opened = true; }
|
||||
async handleInput(e) {
|
||||
if (e.type === 'click') this.options.items()[0].onSelect({ stack: { pop: () => { this.opened = false; } } });
|
||||
if (e.type === 'double-click' || e.type === 'system-menu-opened') this.opened = false;
|
||||
}
|
||||
}
|
||||
const modules = {
|
||||
'@nativescript/core/globals': {}, '../../graphics/image': graphics,
|
||||
'../../graphics/plane': {}, '../../graphics/glyph-wire': {},
|
||||
'../../graphics/bdffont': { getFont: name => fonts[name] },
|
||||
'../../graphics/ui-fonts': { getDefaultSmallFont: () => small },
|
||||
'../../native/frame-timings': { finishFrame() {}, logFrame() {} },
|
||||
'../../native/active-display': {}, '../../native/worker-buzzer': {},
|
||||
'../../native/settings-store': { getStringSetting: () => '0', setStringSetting() {} },
|
||||
'../../ui/sound-effects': {}, '../../ui/sound-setting': { loadSoundEnabled: () => false, saveSoundEnabled() {} },
|
||||
'../../ui/window-menu': { WindowMenu: Menu }, '../../ui/gestures': gestures,
|
||||
'../../util/numeric-util': { clamp: (v, a, b) => Math.max(a, Math.min(b, v)) },
|
||||
'./flappy-sprites': load('app/apps/flappy/flappy-sprites.ts', { '../../graphics/image': graphics }),
|
||||
};
|
||||
const extra = game === 'blocks' ? 'tick, hardDrop, idleDelayMs, dropIntervalMs, spawnPiece, windowMenu' :
|
||||
game === 'pinball' ? 'stepFlippers, flip, launchBall, windowMenu' : 'flap, windowMenu';
|
||||
const api = load(`app/apps/${game}/${game}-app.worker.ts`, modules, {
|
||||
global, Date: { now: () => now },
|
||||
setTimeout: (f, d) => schedule(f, d, 0), clearTimeout: cancel,
|
||||
setInterval: (f, d) => schedule(f, d, d), clearInterval: cancel,
|
||||
recordRender: () => renders++,
|
||||
}, `\nrenderAndSubmit = () => recordRender(); playSfx = () => {};
|
||||
exports.api = { windows, resetGame, paintContent, ${extra} };`).api;
|
||||
const message = data => global.onmessage({ data });
|
||||
message({ type: 'open-window', windowId: 'test', surfaceId: 'test', title: game, viewport: { width: 576, height: 288 } });
|
||||
message({ type: 'foreground', windowId: 'test', foreground: true, focused: true });
|
||||
const w = api.windows.get('test');
|
||||
if (game === 'blocks') { w.pieceIndex = 2; w.pieceRotation = 0; w.pieceY = 0; w.pieceX = 3; }
|
||||
function advance(ms) {
|
||||
const end = now + ms;
|
||||
for (;;) {
|
||||
const next = [...timers].filter(([, t]) => t.at <= end).sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
|
||||
if (!next) break;
|
||||
const [key, t] = next; now = t.at;
|
||||
if (t.repeat) t.at += t.repeat; else timers.delete(key);
|
||||
t.fn();
|
||||
}
|
||||
now = end;
|
||||
}
|
||||
return { ...api, w, message, advance, posts, timers, now: () => now, renders: () => renders,
|
||||
elapse: ms => { now += ms; }, input: (type, source = 'ring') => message({
|
||||
type: 'input', windowId: 'test', focused: true, frameId: 1, event: { type, source, timestampMs: now },
|
||||
}) };
|
||||
}
|
||||
|
||||
for (const [sequence, rotations, x] of [
|
||||
[['ring-press','click'],1,3], [['ring-press',300],1,3],
|
||||
[['ring-press',300,'click'],1,3], [['ring-press','ring-press','double-click'],2,3],
|
||||
[['ring-press','ring-press','ring-press','double-click'],3,3],
|
||||
[['ring-press','scroll-up'],0,2], [['ring-press','scroll-down'],0,4],
|
||||
[['ring-press','ring-press','ring-press','scroll-up'],2,2],
|
||||
[['ring-press','scroll-up','click'],0,2], [['click','double-click'],0,3],
|
||||
]) test(`Blocks: ${sequence.join(', ')} gives ${rotations} rotations`, () => {
|
||||
const h = worker('blocks');
|
||||
for (const step of sequence) typeof step === 'number' ? h.advance(step) : h.input(step);
|
||||
h.advance(350);
|
||||
assert.equal(h.w.pieceRotation, rotations); assert.equal(h.w.pieceX, x);
|
||||
assert.equal(h.w.phase, 'playing'); assert.equal(h.w.pendingRotationTimer, null);
|
||||
});
|
||||
|
||||
test('Blocks replaces only the last buffered press and expires at 300 ms', () => {
|
||||
const h = worker('blocks'); h.input('ring-press'); h.advance(200); h.input('ring-press');
|
||||
assert.equal(h.w.pieceRotation, 1); h.advance(299); assert.equal(h.w.pieceRotation, 1);
|
||||
h.advance(1); assert.equal(h.w.pieceRotation, 2); h.input('double-click'); assert.equal(h.w.pieceRotation, 2);
|
||||
});
|
||||
|
||||
test('Blocks a click from another source commits the pending rotation without duplicating it', () => {
|
||||
const h = worker('blocks'); h.input('ring-press'); h.input('click', 'left-arm');
|
||||
h.advance(300); assert.equal(h.w.pieceRotation, 1);
|
||||
h.input('click', 'watch'); assert.equal(h.w.pieceRotation, 2);
|
||||
});
|
||||
|
||||
test('Blocks idle acceleration starts at the deadline, runs at 5x, and ends on input', () => {
|
||||
const h = worker('blocks'); h.advance(1000);
|
||||
assert.equal(h.w.pieceY, 0);
|
||||
const before = h.w.gravityProgress; h.advance(300);
|
||||
assert.ok(Math.abs((h.w.pieceY + h.w.gravityProgress) - before - 1) < 1e-9);
|
||||
h.input('scroll-down'); const afterInput = h.w.pieceY + h.w.gravityProgress;
|
||||
h.advance(300);
|
||||
assert.ok(Math.abs((h.w.pieceY + h.w.gravityProgress) - afterInput - 0.2) < 1e-9);
|
||||
for (const [lines, expected] of [[0,1000],[10,950],[50,750],[100,500],[200,500]]) {
|
||||
h.w.lines = lines; assert.equal(h.idleDelayMs(h.w), expected);
|
||||
}
|
||||
});
|
||||
|
||||
test('Blocks continuous input cannot reset gravity progress; timeout rotation is not fresh input', () => {
|
||||
const h = worker('blocks');
|
||||
for (let i = 0; i < 20; i++) { h.input(i % 2 ? 'scroll-up' : 'scroll-down'); h.advance(100); }
|
||||
assert.equal(h.w.pieceY, 1);
|
||||
h.input('ring-press'); const when = h.w.lastInputAtMs; h.advance(300);
|
||||
assert.equal(h.w.lastInputAtMs, when);
|
||||
});
|
||||
|
||||
test('Blocks landing resets acceleration and prevents a pending rotation from reaching the next piece', () => {
|
||||
const h = worker('blocks'); h.advance(1100); h.input('ring-press');
|
||||
h.hardDrop(h.w);
|
||||
assert.equal(h.w.gravityProgress, 0); assert.equal(h.w.lastInputAtMs, h.now());
|
||||
h.advance(300); assert.equal(h.w.pieceRotation, 0);
|
||||
assert.equal(h.w.gravityProgress.toFixed(3), '0.200');
|
||||
// Let a naturally falling piece land while accelerated, then inspect its successor.
|
||||
h.w.pieceY = 17; h.w.board.fill(0);
|
||||
while (h.w.pieceY >= 17) h.advance(20);
|
||||
assert.equal(h.w.gravityProgress, 0); assert.equal(h.w.lastInputAtMs, h.now());
|
||||
});
|
||||
|
||||
test('Blocks hold pauses without dropping, opens a menu, and resumes with a fresh idle delay', async () => {
|
||||
const h = worker('blocks'); h.input('ring-press'); h.advance(100); h.input('long-press');
|
||||
assert.equal(h.w.phase, 'paused'); assert.equal(h.w.pieceY, 0);
|
||||
assert.ok(h.w.menu.isOpen()); assert.equal(h.w.menu.options.claimsLongPress(), false);
|
||||
h.advance(5000); assert.equal(h.w.pieceRotation, 0); assert.equal(h.w.pieceY, 0);
|
||||
h.input('click'); await Promise.resolve();
|
||||
assert.equal(h.w.phase, 'playing'); assert.equal(h.w.lastInputAtMs, h.now());
|
||||
assert.equal(h.w.menu.options.claimsLongPress(), true);
|
||||
h.advance(500); assert.equal(h.w.pieceY, 0);
|
||||
});
|
||||
|
||||
for (const event of [
|
||||
{ type: 'input-focus', windowId: 'test', focused: false },
|
||||
{ type: 'foreground', windowId: 'test', foreground: false, focused: false },
|
||||
{ type: 'screen', on: false }, { type: 'close-window', windowId: 'test' },
|
||||
]) test(`Blocks cancels buffered input and timers on ${event.type}`, () => {
|
||||
const h = worker('blocks'); h.input('ring-press'); h.message(event); h.advance(2000);
|
||||
assert.equal(h.w.pieceRotation, 0); assert.equal(h.timers.size, 0);
|
||||
});
|
||||
|
||||
test('Flappy acts on down and ignores subsequent ring click/scroll; watch still flaps', () => {
|
||||
const h = worker('flappy'); h.input('ring-press');
|
||||
assert.equal(h.w.phase, 'playing'); assert.ok(h.w.birdVy < 0);
|
||||
h.w.birdVy = 20; h.input('click'); h.input('scroll-up'); assert.equal(h.w.birdVy, 20);
|
||||
h.input('swipe-up', 'watch'); assert.ok(h.w.birdVy < 0);
|
||||
h.w.birdVy = 20; h.input('click', 'watch'); assert.ok(h.w.birdVy < 0);
|
||||
});
|
||||
|
||||
test('Pinball pulses both flippers for 300 ms, extends on another press, and ignores click in play', () => {
|
||||
const h = worker('pinball'); h.w.ballState = 'live'; h.input('ring-press');
|
||||
assert.ok(h.w.flippers.every(f => f.state === 'rising' && f.holdUntilMs === h.now() + 300));
|
||||
h.stepFlippers(h.w, 0.2); assert.ok(h.w.flippers.every(f => f.state === 'hold'));
|
||||
h.elapse(200); h.input('click'); assert.ok(h.w.flippers.every(f => f.holdUntilMs === h.now() + 100));
|
||||
h.input('ring-press'); h.elapse(299); h.stepFlippers(h.w, 0);
|
||||
assert.ok(h.w.flippers.every(f => f.state === 'hold'));
|
||||
h.elapse(1); h.stepFlippers(h.w, 0); assert.ok(h.w.flippers.every(f => f.state === 'falling'));
|
||||
});
|
||||
|
||||
test('Pinball swipes no longer flip; plunger power and click launch remain', () => {
|
||||
const h = worker('pinball'); h.w.ballState = 'live';
|
||||
for (const type of ['scroll-up','scroll-down','swipe-left','swipe-right']) h.input(type);
|
||||
assert.ok(h.w.flippers.every(f => f.state === 'rest'));
|
||||
h.w.ballState = 'ready'; h.w.launchPower = 2;
|
||||
h.input('scroll-up'); assert.equal(h.w.launchPower, 3);
|
||||
h.input('scroll-down'); assert.equal(h.w.launchPower, 2);
|
||||
h.input('click'); assert.equal(h.w.ballState, 'live');
|
||||
});
|
||||
@@ -1,122 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { loader } = require('./helpers/load-typescript.cjs');
|
||||
|
||||
function fixture({ ios = false, connected = true } = {}) {
|
||||
const messages = [], frames = [], sounds = [], errors = [], timers = new Set(), settings = new Map();
|
||||
const global = { isIOS: ios, isAndroid: !ios, postMessage: message => messages.push(message) };
|
||||
const timings = {
|
||||
startFrame: () => 1, finishFrame() {}, logFrame() {},
|
||||
span: (_id, _name, fn) => fn(), runWithFrame: (_id, fn) => fn(), spanCurrent: (_name, fn) => fn(),
|
||||
};
|
||||
const mocks = {
|
||||
'@nativescript/core': {}, '@nativescript/core/globals': {},
|
||||
'../../native/frame-timings': timings, '../native/frame-timings': timings,
|
||||
'../../native/settings-store': {
|
||||
getBooleanSetting: (key, fallback) => settings.get(key) ?? fallback,
|
||||
setBooleanSetting: (key, value) => settings.set(key, value),
|
||||
},
|
||||
};
|
||||
mocks['../native/settings-store'] = mocks['../../native/settings-store'];
|
||||
const display = { submitSurfaceFrame: (...args) => frames.push(args) };
|
||||
let active = connected;
|
||||
const load = loader({
|
||||
global, setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn),
|
||||
console: { log() {}, warn: error => errors.push(error), error: error => errors.push(error) },
|
||||
com: { faceclaw: { app: {
|
||||
FaceclawBleCommunicator: { getActive: () => active ? {
|
||||
...display, playBuzzerSequence: payload => sounds.push(payload),
|
||||
} : null },
|
||||
FaceclawPreviewCompositor: { getActive: () => display },
|
||||
} } },
|
||||
NSData: { dataWithBytesLength: buffer => ({ base64EncodedStringWithOptions: () => Buffer.from(buffer).toString('base64') }) },
|
||||
interop: { handleof: buffer => buffer },
|
||||
}, mocks);
|
||||
const { BdfFont } = load('app/graphics/bdffont.ts');
|
||||
const font = size => BdfFont.parse(fs.readFileSync(path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
|
||||
const small = font(12), medium = font(24);
|
||||
mocks['../../graphics/bdffont'] = { getFont: () => medium };
|
||||
mocks['../../graphics/ui-fonts'] = mocks['../graphics/ui-fonts'] = { getDefaultSmallFont: () => small };
|
||||
// Exercise the real iOS transport and Android preview selection. The atlas
|
||||
// boundary is stubbed; text baking and plane composition remain production code.
|
||||
mocks['../../graphics/glyph-wire'] = { prepareFrameDraws: () => null };
|
||||
if (ios) mocks['../../native/active-display'] = load('app/native/active-display.ios.ts');
|
||||
load('app/apps/paperclips/paperclips-app.worker.ts');
|
||||
const send = data => global.onmessage({ data });
|
||||
const input = type => send({ type: 'input', windowId: 'paperclips:main', focused: true, frameId: 1,
|
||||
event: { type, source: 'ring', timestampMs: 1 } });
|
||||
const open = () => {
|
||||
send({ type: 'open-window', windowId: 'paperclips:main', surfaceId: 'window:paperclips:main',
|
||||
title: 'Paperclips', viewport: { width: 576, height: 260 } });
|
||||
send({ type: 'foreground', windowId: 'paperclips:main', foreground: true, focused: true });
|
||||
};
|
||||
const pixels = () => ios ? Buffer.from(messages.filter(m => m.type === 'surface-frame').at(-1).pixels, 'base64')
|
||||
: Buffer.from(frames.at(-1)[0]);
|
||||
return { messages, frames, sounds, errors, timers, settings, send, input, open, pixels,
|
||||
disconnect: () => { active = false; } };
|
||||
}
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
for (const ios of [false, true]) {
|
||||
test(`Paperclips starts, renders text and plays sound through the ${ios ? 'iOS' : 'Android'} bridge`, () => {
|
||||
const h = fixture({ ios });
|
||||
assert.equal(h.messages[0].type, 'worker-ready');
|
||||
h.open();
|
||||
assert.equal(h.timers.size, 1);
|
||||
assert.equal(h.pixels().length, 576 * 260);
|
||||
assert.ok(h.pixels().some(value => value > 0));
|
||||
const first = h.pixels();
|
||||
h.input('click');
|
||||
assert.notDeepEqual(h.pixels(), first);
|
||||
h.input('long-press');
|
||||
assert.equal(h.timers.size, 0);
|
||||
assert.ok(ios ? h.messages.some(m => m.type === 'buzzer-sequence' && m.payload.length) : h.sounds.length);
|
||||
const gestures = h.messages.filter(m => m.type === 'set-window-gestures');
|
||||
assert.equal(gestures[0].claimsLongPress, true);
|
||||
assert.equal(gestures.at(-1).claimsLongPress, false);
|
||||
// The gap between the pause title and hints must occlude the deferred
|
||||
// game labels below, rather than letting them draw over the modal.
|
||||
const pixels = h.pixels();
|
||||
for (let y = 124; y < 136; y++) {
|
||||
assert.ok(pixels.subarray(y * 576 + 132, y * 576 + 444).every(value => value === 0));
|
||||
}
|
||||
h.input('click');
|
||||
assert.equal(h.timers.size, 1);
|
||||
h.send({ type: 'close-window', windowId: 'paperclips:main' });
|
||||
assert.equal(h.timers.size, 0);
|
||||
assert.deepEqual(h.errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
test('Paperclips uses the disconnected preview and suppresses duplicate frames', () => {
|
||||
const h = fixture({ connected: false });
|
||||
h.open();
|
||||
assert.equal(h.frames.length, 1);
|
||||
h.send({ type: 'render', windowId: 'paperclips:main', focused: true });
|
||||
assert.equal(h.frames.length, 1);
|
||||
h.input('click');
|
||||
assert.equal(h.frames.length, 2);
|
||||
assert.deepEqual(h.errors, []);
|
||||
});
|
||||
|
||||
test('Paperclips pauses for focus loss and its current context menu resumes and saves sound settings', async () => {
|
||||
const h = fixture(); h.open();
|
||||
h.send({ type: 'input-focus', windowId: 'paperclips:main', focused: false });
|
||||
assert.equal(h.timers.size, 0);
|
||||
h.input('short-then-long-press');
|
||||
h.input('click'); await flush(); // Resume
|
||||
assert.equal(h.timers.size, 1);
|
||||
h.input('short-then-long-press');
|
||||
assert.equal(h.timers.size, 0);
|
||||
for (let i = 0; i < 3; i++) { h.input('scroll-down'); await flush(); }
|
||||
h.input('click'); await flush(); // Sound: off
|
||||
assert.equal(h.settings.get('paperclips.soundOn'), false);
|
||||
const sounds = h.sounds.length;
|
||||
h.input('click'); // Resume without sound
|
||||
assert.equal(h.sounds.length, sounds);
|
||||
h.send({ type: 'screen', on: false });
|
||||
assert.equal(h.timers.size, 0);
|
||||
assert.deepEqual(h.errors, []);
|
||||
});
|
||||
@@ -1,153 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const worker = require('./fixtures/pinball-worker.cjs');
|
||||
|
||||
function lane(h, index) {
|
||||
h.w.ballX = h.ROLLOVERS[index].x;
|
||||
h.w.ballY = h.ROLLOVERS[index].y;
|
||||
h.checkRollovers(h.w);
|
||||
h.w.ballY = 60;
|
||||
h.checkRollovers(h.w);
|
||||
}
|
||||
|
||||
function target(h, index) {
|
||||
const t = h.TARGETS[index];
|
||||
h.w.ballX = t.x + (index < 3 ? 7 : -7);
|
||||
h.w.ballY = t.y;
|
||||
h.w.ballVx = index < 3 ? -50 : 50;
|
||||
h.checkTargets(h.w);
|
||||
}
|
||||
|
||||
test('skill shot awards only the marked first lane; rollovers debounce and raise multiplier to 5x', () => {
|
||||
const h = worker();
|
||||
h.launchBall(h.w);
|
||||
lane(h, 0);
|
||||
assert.equal(h.w.score, 800);
|
||||
lane(h, 0);
|
||||
assert.equal(h.w.score, 800);
|
||||
lane(h, 1); lane(h, 2);
|
||||
assert.equal(h.w.score, 1400);
|
||||
assert.equal(h.w.multiplier, 2);
|
||||
for (let round = 0; round < 6; round++) for (let i = 0; i < 3; i++) lane(h, i);
|
||||
assert.equal(h.w.multiplier, 5);
|
||||
const missed = worker();
|
||||
missed.launchBall(missed.w);
|
||||
lane(missed, 1); lane(missed, 0);
|
||||
assert.equal(missed.w.score, 100);
|
||||
});
|
||||
|
||||
test('six distinct drop targets light a repeatable, escalating center jackpot', () => {
|
||||
const h = worker();
|
||||
h.launchBall(h.w);
|
||||
for (let i = 0; i < 6; i++) { target(h, i); target(h, i); }
|
||||
assert.equal(h.w.score, 1900);
|
||||
assert.ok(h.w.targetsDown.every(Boolean));
|
||||
h.w.ballX = 121; h.w.ballY = 110;
|
||||
h.collideBumpers(h.w);
|
||||
assert.equal(h.w.score, 4000);
|
||||
assert.equal(h.w.jackpots, 1);
|
||||
assert.ok(h.w.targetsDown.every((value) => !value));
|
||||
for (let i = 0; i < 6; i++) target(h, i);
|
||||
h.w.ballX = 121; h.w.ballY = 110;
|
||||
h.collideBumpers(h.w);
|
||||
assert.equal(h.w.score, 9000);
|
||||
assert.equal(h.w.jackpots, 2);
|
||||
});
|
||||
|
||||
test('ball saver preserves objectives once, then a drain pays multiplied bonus and resets the ball', () => {
|
||||
const h = worker();
|
||||
h.launchBall(h.w);
|
||||
target(h, 0);
|
||||
h.w.multiplier = 3;
|
||||
h.ballDrained(h.w);
|
||||
assert.equal(h.w.ballsLeft, 3);
|
||||
assert.equal(h.w.ballState, 'ready');
|
||||
assert.equal(h.w.targetsDown[0], true);
|
||||
h.launchBall(h.w);
|
||||
assert.equal(h.w.ballSaveRemaining, 0);
|
||||
assert.equal(h.w.skillShotRemaining, 0);
|
||||
h.ballDrained(h.w);
|
||||
assert.equal(h.w.ballsLeft, 2);
|
||||
assert.equal(h.w.lastBonus, 300);
|
||||
assert.equal(h.w.score, 450);
|
||||
assert.equal(h.highScore(), 450);
|
||||
assert.equal(h.w.multiplier, 1);
|
||||
assert.equal(h.w.skillLane, 1);
|
||||
assert.ok(h.w.targetsDown.every((value) => !value));
|
||||
h.launchBall(h.w);
|
||||
assert.equal(h.w.ballSaveRemaining, 8);
|
||||
});
|
||||
|
||||
test('pause, background, screen-off and menus preserve gameplay timers', () => {
|
||||
for (const suspend of [
|
||||
(h) => h.input('double-click'),
|
||||
(h) => h.input('short-then-long-press'),
|
||||
(h) => h.message({ type: 'foreground', windowId: 'test', foreground: false, focused: false }),
|
||||
(h) => h.message({ type: 'screen', on: false }),
|
||||
]) {
|
||||
const h = worker(); h.launchBall(h.w); suspend(h);
|
||||
h.elapse(60); h.tick(h.w);
|
||||
assert.equal(h.w.ballSaveRemaining, 8);
|
||||
assert.equal(h.w.skillShotRemaining, 8);
|
||||
}
|
||||
});
|
||||
|
||||
test('expired saver drains normally; final bonus is included in game over and restart keeps high score', () => {
|
||||
const h = worker();
|
||||
for (let i = 0; i < 3; i++) {
|
||||
h.launchBall(h.w); target(h, 0);
|
||||
h.w.ballSaveRemaining = 0;
|
||||
h.ballDrained(h.w);
|
||||
}
|
||||
assert.equal(h.w.phase, 'game-over');
|
||||
assert.equal(h.w.score, 750);
|
||||
assert.equal(h.w.lastBonus, 100);
|
||||
h.resetGame(h.w);
|
||||
assert.equal(h.w.score, 0);
|
||||
assert.equal(h.w.ballsLeft, 3);
|
||||
assert.equal(h.w.lastBonus, 0);
|
||||
assert.equal(h.w.highScore, 750);
|
||||
});
|
||||
|
||||
test('live simulation consumes skill and save time; wall-clock pauses do not', () => {
|
||||
const h = worker(); h.launchBall(h.w);
|
||||
h.advance(0.25);
|
||||
assert.ok(Math.abs(h.w.ballSaveRemaining - 7.75) < 0.001);
|
||||
assert.ok(Math.abs(h.w.skillShotRemaining - 7.75) < 0.001);
|
||||
h.input('double-click'); h.elapse(90); h.input('click');
|
||||
h.advance(0.25);
|
||||
assert.ok(Math.abs(h.w.ballSaveRemaining - 7.5) < 0.001);
|
||||
assert.ok(Math.abs(h.w.skillShotRemaining - 7.5) < 0.001);
|
||||
h.w.skillShotRemaining = 0;
|
||||
lane(h, 0);
|
||||
assert.equal(h.w.score, 50);
|
||||
});
|
||||
|
||||
test('production physics stays finite and within the table at every launch power', () => {
|
||||
for (let power = 1; power <= 5; power++) {
|
||||
const h = worker(); h.w.launchPower = power; h.launchBall(h.w);
|
||||
let enteredPlayfield = false;
|
||||
for (let step = 0; step < 120 * 30 && h.w.ballState === 'live'; step++) {
|
||||
if (h.w.ballVy > 0 && h.w.ballY > 195) for (const f of h.w.flippers) h.flip(h.w, f);
|
||||
h.advance(1 / 120);
|
||||
assert.ok(Number.isFinite(h.w.ballX) && Number.isFinite(h.w.ballY));
|
||||
assert.ok(h.w.ballX >= 9 && h.w.ballX <= 261);
|
||||
if (h.w.ballX < 226) enteredPlayfield = true;
|
||||
}
|
||||
assert.ok(enteredPlayfield, `power ${power} enters playfield`);
|
||||
}
|
||||
});
|
||||
|
||||
test('ready, live jackpot, paused and game-over frames render at the glasses viewport size', () => {
|
||||
const h = worker();
|
||||
for (const phase of ['playing', 'paused', 'game-over']) {
|
||||
h.w.phase = phase;
|
||||
for (const lit of [false, true]) {
|
||||
h.w.targetsDown.fill(lit);
|
||||
const image = h.paintContent(h.w);
|
||||
assert.equal(image.width, 576);
|
||||
assert.equal(image.height, 260);
|
||||
assert.ok(image.withDrawsBaked().pixels.some((p) => p > 0));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -27,6 +27,8 @@ function worker() {
|
||||
clearInterval() { timer = undefined; },
|
||||
global: { postMessage: message => messages.push(message) },
|
||||
scheduleRender() { renderCount++; }, renderAndSubmit() {}, maybeReconnectView() {},
|
||||
// Glanceboard publication is outside the sidebar activity fixture.
|
||||
publishSessionsSnapshot() {},
|
||||
controlsInitialized: true, controls: new Map(), TERMINAL_TOOLS: [],
|
||||
getTerminalFontConfig: () => ({ cellWidth: 6, cellHeight: 12 }),
|
||||
};
|
||||
@@ -148,6 +150,7 @@ test('host applies activity only to its own open windows and cleans up on close'
|
||||
'../../assistant/tool-registry': { toolRegistry: { removeAppTools() {} } },
|
||||
'./geometry': { appViewportSize: () => ({ width: 576, height: 260 }) },
|
||||
'../../native/frame-timings': {},
|
||||
'./worker-state': {},
|
||||
'./shell': { shell: { registerWindow: w => shellWindows.set(w.windowId, w) } },
|
||||
});
|
||||
const host = new WorkerAppHost({ appId: 'terminal', worker, configureSurface: async () => {}, requestShellRender() { paints++; }, removeSurface() {} });
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const read = (file) => fs.readFileSync(path.join(root, file), 'utf8');
|
||||
const js = (source) => ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText;
|
||||
|
||||
// Run the actual decoder declarations without loading the Android shell.
|
||||
function decoder() {
|
||||
const source = ts.createSourceFile('shell.ts', read('app/ui/shell/shell.ts'), ts.ScriptTarget.Latest, true);
|
||||
const names = new Set(['rawInputEventToPayload', 'eventSourceToString', 'scrollEvent']);
|
||||
const declarations = source.statements.filter((s) => ts.isFunctionDeclaration(s) && names.has(s.name?.text));
|
||||
assert.equal(declarations.length, names.size);
|
||||
const context = { exports: {} };
|
||||
vm.createContext(context);
|
||||
vm.runInContext(js(read('app/g2/events.ts')), context);
|
||||
Object.assign(context, context.exports);
|
||||
vm.runInContext(js(declarations.map((s) => s.getText(source)).join('\n')), context);
|
||||
return context;
|
||||
}
|
||||
|
||||
test('wire edges require explicit left/right temple provenance', () => {
|
||||
const d = decoder();
|
||||
for (const [key, source] of [['TOUCH_EVENT_FROM_GLASSES_L', 'left-arm'], ['TOUCH_EVENT_FROM_GLASSES_R', 'right-arm']]) {
|
||||
const eventSource = d.EventSourceType[key];
|
||||
for (const [eventType, type] of [[12, 'touch-press'], [13, 'touch-release']]) {
|
||||
const event = d.rawInputEventToPayload({ kind: 'sys-event', eventSource, eventType });
|
||||
assert.equal(event.type, type);
|
||||
assert.equal(event.source, source);
|
||||
}
|
||||
assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventSource, eventType: 0 }).type, 'click');
|
||||
}
|
||||
for (const eventSource of [undefined, -1, 99, d.EventSourceType.TOUCH_EVENT_FROM_RING]) {
|
||||
assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventSource, eventType: 12 }).type, 'unknown');
|
||||
}
|
||||
});
|
||||
|
||||
function worker() {
|
||||
const noop = () => {};
|
||||
const modules = {
|
||||
'@nativescript/core/globals': {},
|
||||
'../../graphics/image': {}, '../../graphics/plane': {}, '../../graphics/glyph-wire': {},
|
||||
'../../graphics/bdffont': { getFont: noop },
|
||||
'../../graphics/ui-fonts': { getDefaultSmallFont: noop },
|
||||
'../../native/frame-timings': { finishFrame: noop, logFrame: noop },
|
||||
'../../native/active-display': {},
|
||||
'../../native/worker-buzzer': { playWorkerBuzzerSequence() {} },
|
||||
'../../native/settings-store': { getStringSetting: () => '0', setStringSetting: noop },
|
||||
'../../ui/sound-effects': {}, '../../ui/window-menu': {},
|
||||
'../../ui/sound-setting': { loadSoundEnabled: () => true, saveSoundEnabled: noop },
|
||||
'../../ui/gestures': { directionalFallback: (event) => event },
|
||||
'../../util/numeric-util': { clamp: (v, lo, hi) => Math.max(lo, Math.min(hi, v)) },
|
||||
};
|
||||
const context = {
|
||||
exports: {}, console, Date, setInterval: () => 1, clearInterval: noop,
|
||||
global: { postMessage: noop },
|
||||
require: (name) => { assert.ok(name in modules, name); return modules[name]; },
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(js(read('app/apps/pinball/pinball-app.worker.ts')) + `
|
||||
// Stub platform output only; exercise real worker input, physics and lifecycle.
|
||||
renderAndSubmit = () => {};
|
||||
playSfx = () => {};
|
||||
exports.harness = { windows, stepFlippers, resetGame };
|
||||
`, context);
|
||||
const message = (data) => context.global.onmessage({ data });
|
||||
message({ type: 'open-window', windowId: 'test', surfaceId: 'test', title: 'test', viewport: { width: 640, height: 480 } });
|
||||
message({ type: 'foreground', windowId: 'test', foreground: true, focused: true });
|
||||
const w = context.exports.harness.windows.get('test');
|
||||
w.ballState = 'live';
|
||||
const input = (type, source = 'left-arm') => message({ type: 'input', windowId: 'test', focused: true, frameId: 1, event: { type, source, timestampMs: Date.now() } });
|
||||
return { w, input, message, ...context.exports.harness };
|
||||
}
|
||||
|
||||
test('pinball responds on contact, holds independently, and releases before tap', () => {
|
||||
const h = worker();
|
||||
h.input('touch-press');
|
||||
assert.equal(h.w.flippers[0].state, 'rising');
|
||||
assert.equal(h.w.flippers[1].state, 'rest');
|
||||
h.stepFlippers(h.w, 1);
|
||||
h.w.flippers[0].holdUntilMs = 0;
|
||||
h.stepFlippers(h.w, 1);
|
||||
assert.equal(h.w.flippers[0].state, 'hold');
|
||||
h.input('touch-press', 'right-arm');
|
||||
h.input('touch-release');
|
||||
assert.equal(h.w.flippers[0].state, 'falling');
|
||||
assert.equal(h.w.flippers[1].touchHeld, true);
|
||||
h.input('click');
|
||||
assert.equal(h.w.flippers[0].state, 'falling');
|
||||
h.input('touch-release', 'right-arm');
|
||||
assert.equal(h.w.flippers[1].state, 'falling');
|
||||
});
|
||||
|
||||
test('pinball uses ring press for flippers and retains plunger click launch', () => {
|
||||
const h = worker();
|
||||
h.input('click');
|
||||
assert.ok(h.w.flippers.every((f) => f.state === 'rising'));
|
||||
h.resetGame(h.w);
|
||||
h.input('touch-press');
|
||||
h.input('touch-release');
|
||||
assert.equal(h.w.ballState, 'ready');
|
||||
h.input('click');
|
||||
assert.equal(h.w.ballState, 'live');
|
||||
h.input('ring-press', 'ring');
|
||||
assert.ok(h.w.flippers.every((f) => f.state === 'rising'));
|
||||
});
|
||||
|
||||
test('pinball clears held contacts on pause, focus loss, screen-off and menus', () => {
|
||||
for (const cancel of [
|
||||
(h) => h.input('double-click', 'ring'),
|
||||
(h) => h.input('system-menu-opened'),
|
||||
(h) => h.message({ type: 'foreground', windowId: 'test', foreground: false, focused: false }),
|
||||
(h) => h.message({ type: 'render', windowId: 'test', focused: false }),
|
||||
(h) => h.message({ type: 'screen', on: false }),
|
||||
]) {
|
||||
const h = worker();
|
||||
h.input('touch-press');
|
||||
cancel(h);
|
||||
assert.equal(h.w.flippers[0].touchHeld, false);
|
||||
assert.equal(h.w.flippers[0].state, 'falling');
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user