spherex-projects / tests /app_test.js
AkshithSurya's picture
Deploy SPHEREx Data Explorer (Static)
057a205 verified
Raw History Blame Contribute Delete
16 kB
const ROOT = require('path').join(__dirname, '..') + '/';
const { makeDom } = require('./fake_dom.js');
global.window = global;
const doc = makeDom(); global.document = doc;
global.location = { search: '' };
global.URLSearchParams = URLSearchParams;
let rafQ = [], rafId = 1; global.requestAnimationFrame = (f) => { rafQ.push({ id: rafId, f }); return rafId++; }; global.cancelAnimationFrame = (id) => { rafQ = rafQ.filter(r => r.id !== id); };
const frame = (t) => { const q = rafQ; rafQ = []; q.forEach(r => r.f(t)); };
const C = require(ROOT + 'dome-coords.js'); global.DomeCoords = C;
const S = require(ROOT + 'app-state.js'); global.DomeState = S; global.THREE = {};
const log = [];
// ---- fakes for the pieces dome-app.js orchestrates
let GL = true;
global.DomeView = function (host, o) { this.container = host; this.supported = GL; this.opts = o; this.calls = [];
['setActive', 'resize', 'setExposure', 'setReferenceLines', 'setObserver'].forEach(n => { this[n] = (...a) => { this.calls.push([n, ...a]); }; }); };
global.DomeLook = function (view, o) { this.view = view; this.o = o; this.obs = o.observer; this.cam = { yaw: -123.6, pitch: 22, fov: 75 }; this.calls = [];
this.getCenter = () => ({ ra: 127.571, dec: -39.214, fov: this.cam.fov, alt: this.cam.pitch, az: C.norm360(-this.cam.yaw) });
this.getView = () => Object.assign({}, this.cam); this.setView = (y, p, f) => { this.cam = { yaw: y, pitch: p, fov: f }; this.calls.push(['setView', y, p, f]); };
this.lookAt = (ra, dec) => this.calls.push(['lookAt', ra, dec]); this.reset = () => this.calls.push(['reset']); this.setObserver = (ob) => { this.obs = ob; this.calls.push(['setObserver', ob]); }; };
global.DomeLandscape = function () { this.calls = []; this.setVisible = (on) => this.calls.push(['visible', on]); this.setLabels = (on) => this.calls.push(['labels', on]); };
const LAYERS = [{ id: 'dss2-color', label: 'Optical', survey: 'DSS2', regime: 'optical', wavelength_um: [0.4, 0.9] }, { id: '2mass-color', label: 'Near-infrared', survey: '2MASS', regime: 'near-infrared', wavelength_um: [1.2, 2.2] },
{ id: 'mellinger-color', label: 'Optical (smooth)', survey: 'Mellinger', regime: 'optical', wavelength_um: [0.4, 0.8] }];
let layersFail = false;
global.DomeLayers = function (view, o) { this.o = o; this.byId = {}; this.current = null; this.shown = [];
this.load = () => layersFail ? Promise.reject(new Error('manifest HTTP 404')) : Promise.resolve(LAYERS.map(l => (this.byId[l.id] = l)));
this.show = (id) => { this.shown.push(id); this.current = this.byId[id]; this.o.onChange(this.current); return Promise.resolve({ ok: true, id }); };
this.credit = (l) => 'credit-' + l.id; };
let outlineOk = true;
global.DomeSelect = function (view, o) { this.o = o; this.calls = []; this.selection = null;
this.bindLook = (look) => this.calls.push(['bind']); this.loadOutline = () => Promise.resolve(outlineOk);
this.selectAt = (ra, dec, x) => { this.calls.push(['selectAt', ra, dec, x && x.name]); return { ra, dec }; };
this.restore = (s) => this.calls.push(['restore', s]); this.clear = () => this.calls.push(['clear']); this.setOutlineVisible = (on) => this.calls.push(['outline', on]); };
let hudInst = null;
global.DomeHud = function (root, o) { hudInst = this; this.o = o; this.calls = []; this.root = root;
['setLayers', 'setLayer', 'setCenter', 'setSelection', 'setStatus', 'setSimLabel', 'setTime', 'progress'].forEach(n => { this[n] = (...a) => { this.calls.push([n, ...a]); }; }); };
require(ROOT + 'dome-app.js');
let bad = 0; const ok = (c, m) => { if (!c) bad++; console.log((c ? 'PASS ' : 'FAIL ') + m); };
const near = (a, b, t) => Math.abs(a - b) < (t || 1e-6);
const flush = () => new Promise(r => setImmediate(r));
const hudCalls = (n) => hudInst.calls.filter(c => c[0] === n);
const fresh = () => { delete global.__domeApp; doc.body.children.length = 0; global.location.search = ''; };
(async () => {
// ---- start conditions
global.location.search = '?dome=0'; ok(DomeApp.start() === null && doc.body.children.length === 0, '?dome=0 opens the app without the dome (nothing added to the page)');
fresh(); const saveHud = global.DomeHud; delete global.DomeHud; const w = console.warn; let warned = ''; console.warn = (m) => { warned = m; };
ok(DomeApp.start() === null && /DomeHud/.test(warned) && doc.body.children.length === 0, 'a missing file: dome does not start, names the file, the app is untouched');
console.warn = w; global.DomeHud = saveHud; fresh();
GL = false; let app = DomeApp.start(); ok(!!app && !app.look && app.root.children.some(c => /Professional/.test(c.textContent)), 'no WebGL: dome shows a way into Professional Mode instead of crashing');
app.root.children.find(c => c.tag === 'button').fire('click'); ok(app.root.style.display === 'none', 'that button reveals the normal app');
GL = true; fresh();
// ---- normal start
app = DomeApp.start(); await flush(); await flush();
ok(doc.body.children.includes(app.root) && app.root.style.cssText.includes('position:fixed') && app.ret.style.display === 'none', 'dome mounts as a full-screen layer; Return button hidden');
ok(DomeApp.start() === app, 'start() twice returns the same app (no double mount)');
const aa = C.altAz(127.571, -39.214, app.observer); ok(near(aa.alt, 22, 1e-6) && app.observer.lat === -30, 'observer: latitude 30 S, moment chosen so the field starts 22 deg up');
ok(app.look.o.observer === app.observer && app.view.opts.fov === 75 && app.look.o.startRa === 127.571, 'look controller gets the observer and the field as its start');
ok(hudCalls('setLayers').length === 1 && hudCalls('setLayers')[0][1].length === 3, 'layers loaded from the manifest and handed to the HUD');
ok(app.layers.shown.join() === '2mass-color', 'default layer shown first: 2MASS');
ok(app.state.get().survey === '2mass-color' && near(app.state.get().wavelengthRange[0], 1.2) && hudCalls('setLayer').length === 1 && /credit-2mass-color/.test(hudCalls('setLayer')[0][2]), 'layer change updates the state store and the HUD credit line');
ok(/latitude 30\u00b0 S, fixed moment/.test(hudCalls('setSimLabel').pop()[1]) && /not live/.test(hudCalls('setSimLabel').pop()[1]), 'HUD says "Simulated sky: latitude 30 S, fixed moment (not your location, not live)"');
ok(app.select.calls.some(c => c[0] === 'bind'), 'selection is bound to the look controller (clicks select)');
// ---- user actions
hudInst.o.onLayer('dss2-color'); await flush(); ok(app.layers.shown.pop() === 'dss2-color' && app.state.get().survey === 'dss2-color' && hudCalls('progress').some(c => c[1] === 'layer'), 'user layer switch: layer shown, state updated, "layer" tip completed');
hudInst.o.onToggle('landscape', false); hudInst.o.onToggle('compass', false); hudInst.o.onToggle('field', false); hudInst.o.onToggle('ring', true);
ok(app.landscape.calls.join('|') === 'visible,false|labels,false' && app.select.calls.some(c => c[0] === 'outline' && c[1] === false) && app.view.calls.some(c => c[0] === 'setReferenceLines' && c[1] === true), 'menu toggles reach landscape, compass, field outline and the equator ring');
hudInst.o.onReset(); ok(app.look.calls.some(c => c[0] === 'reset'), 'Reset view');
hudInst.o.onClear(); ok(app.select.calls.some(c => c[0] === 'clear'), 'Clear selection');
hudInst.o.onExposure(1.8); ok(app.view.calls.some(c => c[0] === 'setExposure' && c[1] === 1.8), 'brightness reaches the view');
app._lastLook = { az: 124, alt: 22 }; app._lookTotal = 0; app._onCenter({ ra: 1, dec: 2, fov: 75, alt: 22, az: 140 }); ok(hudCalls('progress').some(c => c[1] === 'look'), 'turning the view more than 8 degrees completes the "look" tip');
app._onCenter({ ra: 1, dec: 2, fov: 50, alt: 22, az: 140 }); ok(hudCalls('progress').some(c => c[1] === 'zoom'), 'changing the FOV completes the "zoom" tip');
// ---- time
const base = app.baseLst; app.setTimeShift(2); ok(near(app.observer.lst, C.norm360(base + 30)) && app.look.calls.pop()[0] === 'setObserver' && /shifted \+2\.0 h/.test(hudCalls('setSimLabel').pop()[1]), 'time +2 h turns the sky 30 degrees; label says the moment is shifted');
app.setTimeShift(99); ok(app.timeShift === 12, 'time shift clamps at +12 h'); app.setTimeShift(-99); ok(app.timeShift === -12, 'and at -12 h');
app.setTimeShift(0); ok(/fixed moment/.test(hudCalls('setSimLabel').pop()[1]), 'shift 0 says "fixed moment" again');
app.setPlaying(true); frame(1000); frame(2000); frame(3500); ok(near(app.timeShift, 2.5, 1e-9), 'Play: one simulated hour per real second (2.5 h after 2.5 s)');
app.setPlaying(false); const t0 = app.timeShift; frame(9000); ok(app.timeShift === t0 && rafQ.length === 0, 'Pause stops the animation and cancels its frame');
app.setTimeShift(11.5); app.setPlaying(true); frame(0); frame(1000); ok(near(app.timeShift, -11.5, 1e-9), 'Play wraps from +12 h round to -12 h');
app.setPlaying(false); app.setTimeShift(0);
// ---- go-to
const gr = []; let fetchMode = 'ok'; global.fetch = (url) => { gr.push(url); if (fetchMode === 'net') return Promise.reject(new Error('offline'));
return Promise.resolve({ ok: fetchMode === 'ok', json: async () => (fetchMode === 'ok' ? { name: 'Sirius B', ra: 101.287, dec: -16.716 } : { error: 'nope' }) }); };
global.KNOWN_BENCHMARK_TARGETS = [{ name: 'M42', ra: 83.8221, dec: -5.3911 }, { name: 'Sirius', ra: 101.2872, dec: -16.7161 }];
app.observer = { lat: -30, lst: 83.8221 + 20 }; app.look.o.observer = app.observer;
ok((await app.goTo(' ')).ok === false, 'go-to: empty text is rejected politely');
let res = await app.goTo('m42'); ok(res.ok && gr.length === 0 && app.look.calls.some(c => c[0] === 'lookAt' && near(c[1], 83.8221)) && app.select.calls.some(c => c[0] === 'selectAt' && c[3] === 'M42'), 'go-to: well-known name works offline (no network call), looks at it and selects it');
app.look.calls.length = 0; app.select.calls.length = 0; app.observer = { lat: -30, lst: 83.8221 + 20 + 180 };
res = await app.goTo('M42'); ok(!res.ok && /below the horizon/.test(res.message) && /time slider/.test(res.message) && !app.select.calls.some(c => c[0] === 'selectAt') && !app.look.calls.length, 'go-to: object below the horizon is explained, nothing changes');
app.observer = { lat: -30, lst: 101.287 + 15 };
res = await app.goTo('Betelgeuze2'); ok(res.ok && gr.length === 1 && /q=Betelgeuze2/.test(gr[0]) && app.select.calls.some(c => c[3] === 'Sirius B'), 'go-to: unknown name asks the resolver and uses its answer');
fetchMode = 'bad'; res = await app.goTo('zzz'); ok(!res.ok && /Could not find/.test(res.message), 'go-to: unknown to the resolver -> "Could not find"');
fetchMode = 'net'; res = await app.goTo('zzz'); ok(!res.ok && /unavailable/.test(res.message) && /M42/.test(res.message), 'go-to: offline -> clear message that suggests names that work');
// ---- handoff into the existing app
const seen = []; const reg = (n, f) => { global[n] = (...a) => { seen.push([n, ...a]); return f && f(...a); }; };
reg('showSkyMap'); reg('setSearchCenter'); reg('runSearch'); reg('applySky'); global.skySurveys = [{ key: 'dss2-color' }, { key: '2mass-color' }, { key: 'allwise-color' }];
const radius = doc.registerId('sRadius', doc.createElement('input')); radius.value = '0.05';
app.state.select({ ra: 83.8221, dec: -5.3911, alt: 40, az: 100, l: 209, b: -19, count: 4, lookup: 'ok', radius: 0.25, name: 'M42' });
app.look.cam = { yaw: -77.5, pitch: 31, fov: 60 };
app.state.setLayer(LAYERS[1]);
const p = hudInst.o.onInvestigate();
ok(app.root.style.display === 'none' && app.ret.style.display === 'block' && app.view.calls.some(c => c[0] === 'setActive' && c[1] === false) && app.state.get().mode === 'professional', 'Investigate: dome hides, Return button appears, drawing pauses, mode = professional');
ok(seen.map(s => s[0]).join() === 'showSkyMap,applySky,setSearchCenter,runSearch', 'existing app is driven in order: showSkyMap, applySky, setSearchCenter, runSearch');
ok(radius.value === '0.25', 'search radius field set to the dome selection radius (0.25 deg)');
const sc = seen.find(s => s[0] === 'setSearchCenter'); ok(near(sc[1], 83.8221) && near(sc[2], -5.3911) && sc[3].flyTo === true && sc[3].label === 'M42', 'setSearchCenter gets the exact RA/Dec, flyTo, and the object name as label');
ok(seen.find(s => s[0] === 'applySky')[1] === '2mass-color', 'survey continuity: the app opens on the same layer (2mass-color)');
ok(hudCalls('progress').some(c => c[1] === 'investigate'), 'Investigate completes its tip');
// return
app.look.calls.length = 0; app.select.calls.length = 0; app.state.set({ survey: 'dss2-color' }); // Professional Mode changed things
const back = app.returnToDome();
ok(app.root.style.display === '' && app.ret.style.display === 'none' && app.state.get().mode === 'dome' && app.view.calls.filter(c => c[0] === 'setActive').pop()[1] === true && app.view.calls.some(c => c[0] === 'resize'), 'Return: dome visible again, Return button hidden, drawing resumes, view resized');
ok(app.look.calls.some(c => c[0] === 'setView' && c[1] === -77.5 && c[2] === 31 && c[3] === 60), 'Return: camera restored to the exact yaw / pitch / FOV');
const rs = app.select.calls.find(c => c[0] === 'restore'); ok(rs && rs[1].ra === 83.8221 && rs[1].name === 'M42' && rs[1].count === 4, 'Return: marker and selection restored (with the name and lookup count)');
// open without investigating, and robustness
seen.length = 0; app.openProfessional({ investigate: false }); ok(!seen.some(s => s[0] === 'runSearch') && seen.some(s => s[0] === 'setSearchCenter'), 'Open Professional Mode: sets the centre but does not run the search');
app.returnToDome(); seen.length = 0; app.state.setLayer(LAYERS[2]);
app.openProfessional({}); ok(seen.find(s => s[0] === 'applySky')[1] === 'dss2-color', 'a dome-only layer (mellinger) maps to the app survey with the same wavelength regime (dss2-color)');
app.returnToDome(); global.skySurveys = [{ key: 'dss2-color' }, { key: 'mellinger' }]; seen.length = 0; app.openProfessional({});
ok(seen.find(s => s[0] === 'applySky')[1] === 'mellinger', 'mellinger-color opens as the app\u2019s own "mellinger" survey when it exists');
app.returnToDome(); delete global.skySurveys; seen.length = 0; app.state.setLayer(LAYERS[1]); app.openProfessional({}); ok(seen.find(s => s[0] === 'applySky')[1] === '2mass-color', 'survey mapping also works before the app has loaded its survey list');
app.returnToDome();
global.applySky = () => { throw new Error('boom'); }; seen.length = 0; const w2 = console.warn; let warn2 = ''; console.warn = (m) => { warn2 = m; };
app.openProfessional({ investigate: true }); console.warn = w2;
ok(seen.some(s => s[0] === 'setSearchCenter') && seen.some(s => s[0] === 'runSearch') && /applySky: boom/.test(warn2) && app.lastBridge.warnings.length === 1, 'one failing app function does not stop the rest; the problem is logged');
app.returnToDome(); delete global.setSearchCenter; delete global.runSearch; delete global.showSkyMap; delete global.applySky; const w3 = console.warn; console.warn = () => {};
let threw = false; try { app.openProfessional({ investigate: true }); } catch (e) { threw = true; } console.warn = w3;
ok(!threw && app.lastBridge.warnings.length === 4 && app.state.get().mode === 'professional', 'if the app functions are missing, nothing throws and the user still reaches Professional Mode');
app.returnToDome();
// ---- failures at boot
fresh(); layersFail = true; outlineOk = false; app = DomeApp.start(); await flush(); await flush();
ok(hudCalls('setStatus').some(c => /Sky layers unavailable: manifest HTTP 404/.test(c[1]) && c[2] === 'error'), 'missing manifest: error shown on screen, dome still runs');
ok(hudCalls('setStatus').some(c => /outline unavailable/.test(c[1]) && c[2] === 'warn'), 'missing field outline: warning shown, nothing else affected');
console.log(bad ? bad + ' FAILED' : 'ALL PASS'); process.exit(bad ? 1 : 0);
})();