jukebox
All repositories: gitoria
13.9 KB
// tests/jb19.mjs — JB19 (jukebox#19): the player's controls. The bar reads Shuffle · Previous · Play/pause · Next · Repeat (no 10 second buttons);// Shuffle is a switch that changes what comes next and keeps the song that plays; Repeat steps off → all → one and shows it; at a song's end// 'one' plays it again, at the queue's end 'all' starts the list again and 'off' stops; both states survive a reload.// Own server on a generated database of 6 songs (the generator adds a few more) (one 1.5 s tone, ffmpeg), headless Chrome at 390 px.// node tests/jb19.mjs env: JB19_PORT (server, default 8821), JB19_DIR (scratch), JB19_ROOT (checkout to test), HL_PORT_BASE (Chrome debug ports base+200, default 8630), JUKEBOX_COLD_MSimport { spawn, execFileSync } from 'node:child_process'import { rmSync, mkdirSync, readFileSync } from 'node:fs'import { dirname, join } from 'node:path'import { fileURLToPath } from 'node:url'process.env.HL_CHROME = process.env.HL_CHROME || '/opt/google/chrome/chrome'process.env.HL_PORT_BASE = process.env.HL_PORT_BASE || '8630'const { launchBrowser, sleep } = await import('./cdp.mjs')const root = process.env.JB19_ROOT || join(dirname(fileURLToPath(import.meta.url)), '..')const dir = process.env.JB19_DIR || '/media/STORAGE/claude-scratch/jukebox/P1/gate-jb19'const port = Number(process.env.JB19_PORT || 8821)const BASE = `http://127.0.0.1:${port}`const COLD_MS = Number(process.env.JUKEBOX_COLD_MS || 150000)const TONE = 1.5let pass = 0, fail = 0const check = (name, ok, detail = '') => { console.log((ok ? 'ok ' : 'FAIL ') + name + (ok ? '' : ' — ' + detail)); if (ok) pass++; else fail++ }mkdirSync(dir, { recursive: true })process.env.TMPDIR = dirlet server = null, browser = null, log = ''async function stop() {if (browser) { try { await browser.close() } catch {} browser = null }if (server) { try { server.kill('SIGTERM') } catch {} await sleep(500); server = null }}process.on('SIGINT', async () => { await stop(); process.exit(1) })const storage = join(dir, 'storage')const tone = join(dir, 'tone.mp3')rmSync(storage, { recursive: true, force: true })execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', `sine=frequency=440:duration=${TONE}`, '-q:a', '9', tone])const cover = join(root, 'tests/fixtures/withcover/folder.jpg')execFileSync(join(root, 'bin/hybriel'), [join(root, 'tools/make-test-db.hl'), tone, cover, '6'], { env: { ...process.env, JUKEBOX_STORAGE: storage }, encoding: 'utf8', timeout: 600000 })server = spawn(join(root, 'bin/hybriel'), ['project.hl'], { cwd: root, env: { ...process.env, JUKEBOX_PORT: String(port), JUKEBOX_STORAGE: storage, JUKEBOX_AUTOSCAN: '0', JUKEBOX_WATCH: '0', HL_HOST: '127.0.0.1' }, stdio: ['ignore', 'pipe', 'pipe'] })console.log('server pid ' + server.pid)server.stdout.on('data', (d) => { log += d }); server.stderr.on('data', (d) => { log += d })try {for (const t0 = Date.now(); ; ) {try { if ((await fetch(BASE + '/')).ok) break } catch {}if (Date.now() - t0 > COLD_MS) { console.log(log); throw new Error('the server did not come up') }await sleep(500)}const order = (await (await fetch(BASE + '/api/songs?sort=artist&offset=0&limit=100')).json()).items.map((s) => String(s.id))console.log('list order (artist): ' + order.join(' '))browser = await launchBrowser()console.log('chrome pid ' + browser.proc?.pid)const page = await browser.newPage()const ev = (e) => page.evaluate(e)await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true })await page.goto(BASE + '/')await page.waitForSelector('virtual-list .vl-row:not(.blank)')await sleep(800)const playing = () => ev(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc ? a.currentSrc.split('/').pop() : '' })()`)const state = () => ev(`(() => { const a = document.querySelector('media-player audio'); const s = document.querySelector('#jb-shuffle'), r = document.querySelector('#jb-repeat'); return { src: a.currentSrc.split('/').pop(), paused: a.paused, ended: a.ended, t: a.currentTime, loop: a.loop, shuffle: s.getAttribute('aria-pressed'), repeat: r.getAttribute('aria-pressed'), repeatTitle: r.title, shuffleTitle: s.title, repeatIcon: r.querySelector('path').getAttribute('d') } })()`)const press = async (sel) => { await page.click(sel); await sleep(500) }const next = async (hold) => { const before = await playing(); await page.click('.jb-bar .jb-next'); try { await page.waitFor(`document.querySelector('media-player audio').currentSrc.split('/').pop() !== ${JSON.stringify(before)}`, { timeout: 4000 }) } catch {} await sleep(300); if (hold) await ev(`document.querySelector('media-player audio').pause(); 1`); return playing() }// ---- the songs screen: Shuffle my favourites is an ordinary buttonconst fav = await ev(`(() => { const b = document.querySelector('#shuffle-fav'), s = document.querySelector('#shuffle'); const rb = b.getBoundingClientRect(), rs = s.getBoundingClientRect(); return { cls: b.className, h: rb.height, hs: rs.height, fs: getComputedStyle(b).fontSize, fss: getComputedStyle(s).fontSize, w: rb.width } })()`)check('Songs: "Shuffle my favourites" is an ordinary button (no jb-big, same height and font as Shuffle)', !fav.cls.includes('jb-big') && fav.h <= fav.hs + 2 && fav.fs === fav.fss, JSON.stringify(fav))// ---- play the first song of the listawait page.click('virtual-list .vl-row:not(.blank)')await page.waitFor(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentTime > 0.2 && !a.paused })()`, { timeout: 20000, label: 'first song plays' })check('the first row of the list plays', (await playing()).endsWith(order[0]) || (await playing()) === order[0], await playing())// ---- the bar: order and sizesconst bar = await ev(`(() => [...document.querySelectorAll('.jb-bar button')].map((b) => { const r = b.getBoundingClientRect(); return { id: b.id, cls: b.className.split(' ')[0], x: Math.round(r.left), w: Math.round(r.width), h: Math.round(r.height) } }).filter((b) => b.w > 0).sort((a, b) => a.x - b.x))()`)const names = bar.map((b) => b.id || b.cls).join(' ')console.log('bar: ' + JSON.stringify(bar))check('the bar reads shuffle · previous · play/pause · next · repeat', names === 'jb-shuffle jb-prev mp-play jb-next jb-repeat', names)check('no 10 second back / forward buttons exist', await ev(`document.querySelectorAll('.mp-back, .mp-forward').length === 0`))check('every bar button is at least 44 px', bar.every((b) => b.w >= 44 && b.h >= 44), JSON.stringify(bar))check('both switches start off: Shuffle off, Repeat off', (await state()).shuffle === 'false' && (await state()).repeat === 'false', JSON.stringify(await state()))// ---- Shuffle: off, the list order goes on; on, what comes next is shuffled and the playing song stayslet id = await next()id = await next()check('shuffle off: Next follows the list order (third song)', id === order[2], id + ' vs ' + order[2])await ev(`window.__loads = 0; document.querySelector('media-player audio').addEventListener('loadstart', () => window.__loads++); 1`)await press('#jb-shuffle')const on = await state()check('Shuffle shows on (pressed) and keeps the song that plays, without loading anything', on.shuffle === 'true' && on.src === order[2] && !on.paused && (await ev('window.__loads')) === 0, JSON.stringify(on) + ' loads=' + await ev('window.__loads'))const col = await ev(`({ shuffle: getComputedStyle(document.querySelector('#jb-shuffle')).color, repeat: getComputedStyle(document.querySelector('#jb-repeat')).color })`)check('a switch that is on looks different from one that is off (colour)', col.shuffle !== col.repeat, JSON.stringify(col))const seq = []for (let i = 0; i < 3; i++) seq.push(await next())console.log('shuffled sequence after ' + order[2] + ': ' + seq.join(' ') + ' (list order would be ' + order.slice(3, 6).join(' ') + ')')check('shuffle on: the songs that come next are not the list order, and none comes twice or is the one that played', seq.join() !== order.slice(3, 6).join() && new Set([order[2], ...seq]).size === 4, seq.join())const mid = (await playing())await ev(`window.__loads = 0; 1`)await press('#jb-shuffle')const off = await state()check('Shuffle off keeps the song that plays too', off.shuffle === 'false' && off.src === mid && !off.paused && (await ev('window.__loads')) === 0, JSON.stringify(off))const after = await next()const place = order.indexOf(mid)check('shuffle off: the song after the current one is the list\'s next (by id)', place < 0 || place === order.length - 1 ? true : after === order[place + 1], `${mid} → ${after}, list says ${order[place + 1]}`)// ---- Repeat: off → all → one → off, shownlet rp = await state()check('Repeat starts off', rp.repeat === 'false' && /off/.test(rp.repeatTitle), JSON.stringify(rp))const iconOff = rp.repeatIconawait press('#jb-repeat'); const all = await state()check('Repeat once: all (pressed, title says all)', all.repeat === 'true' && /all/.test(all.repeatTitle) && all.repeatIcon === iconOff && !all.loop, JSON.stringify(all))await press('#jb-repeat'); const one = await state()check('Repeat twice: one (pressed, other icon, the audio loops)', one.repeat === 'true' && /this song/.test(one.repeatTitle) && one.repeatIcon !== iconOff && one.loop === true, JSON.stringify(one))// 'one': the song plays again by itself at its end, same file, no new loadawait ev(`window.__loads = 0; 1`)const t0 = await state()await sleep(TONE * 1000 + 1500)const again = await state()check('repeat one: after the song\'s length the same song plays on (not ended, same src, no new load)', again.src === t0.src && !again.paused && !again.ended && (await ev('window.__loads')) === 0, JSON.stringify({ t0, again }))await press('#jb-repeat'); rp = await state()check('Repeat third press: off again', rp.repeat === 'false' && /off/.test(rp.repeatTitle) && !rp.loop, JSON.stringify(rp))// ---- the end of the queue: go to the last song (Next until it stops moving), repeat off → stops; repeat all → the list starts againlet last = await playing()for (let i = 0; i < order.length + 2; i++) { const n = await next(true); if (n === last) break; last = n }check('Next walks to the last song of the list', last === order[order.length - 1], last)await ev(`window.__loads = 0; document.querySelector('media-player audio').play(); 1`)await sleep(TONE * 1000 + 2500)const end = await state()console.log('repeat off, after the last song ended: ' + JSON.stringify(end) + ' loads=' + await ev('window.__loads'))check('repeat off: at the queue\'s end the playing stops (the last song does not start again, no other song starts)', end.src === order[order.length - 1] && (end.paused || end.ended) && (await ev('window.__loads')) === 0, JSON.stringify(end))// all: play the last song again (tap Play), then let it endawait press('#jb-repeat')await ev(`document.querySelector('media-player audio').currentTime = 0; document.querySelector('media-player audio').play(); 1`)await page.waitFor(`!document.querySelector('media-player audio').paused`, { timeout: 5000 })// repeat was switched while the last song was the only one queued: the queue gets the list's first songs after itawait page.waitFor(`document.querySelector('media-player audio').currentSrc.split('/').pop() !== ${JSON.stringify(order[order.length - 1])}`, { timeout: 8000, label: 'the song after the last' }).catch(() => {})const wrap = await state()check('repeat all: at the queue\'s end the list starts again from its first song, by id', wrap.src === order[0] && !wrap.paused, JSON.stringify(wrap))await press('#jb-repeat'); await press('#jb-repeat') // one, then off// ---- shuffle on: one round of the pool, then it stops with Repeat off, goes on with Repeat allawait press('#jb-shuffle')await ev(`document.querySelector('media-player audio').pause(); 1`)const round = [await playing()]for (let i = 0; i < order.length + 2; i++) { const n = await next(true); if (n === round[round.length - 1]) break; round.push(n) }check('shuffle on, repeat off: Next stops after one round (every song once)', round.length === order.length && new Set(round).size === order.length, round.join())await press('#jb-repeat') // allconst more = await next(true)check('shuffle on, repeat all: Next goes on with a new round', more !== round[round.length - 1] && more !== '', more)// ---- states survive a reload (and are in storage/ui.json)const ui = JSON.parse(readFileSync(join(storage, 'ui.json'), 'utf8'))check('storage/ui.json holds shuffle on and repeat all', ui.shuffle === 'on' && ui.repeat === 'all', JSON.stringify(ui))await page.goto(BASE + '/')await page.waitForSelector('#jb-shuffle')await sleep(1000)const re = await state().catch(() => null) || await ev(`(() => { const s = document.querySelector('#jb-shuffle'), r = document.querySelector('#jb-repeat'); return { shuffle: s.getAttribute('aria-pressed'), repeat: r.getAttribute('aria-pressed'), repeatTitle: r.title, shuffleTitle: s.title } })()`)check('after a reload the buttons show shuffle on and repeat all', re.shuffle === 'true' && re.repeat === 'true' && /all/.test(re.repeatTitle) && /on/.test(re.shuffleTitle), JSON.stringify(re))// a song tapped with shuffle on: it plays, and what follows is a shuffle (not the list)await page.click('virtual-list .vl-row:not(.blank)')await page.waitFor(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentTime > 0.2 && !a.paused })()`, { timeout: 20000 })check('a tapped row plays that song while shuffle is on', (await playing()) === order[0], await playing())const s2 = [await next(), await next(), await next()]check('…and the songs after it are shuffled, not the list order', s2.join() !== order.slice(1, 4).join(), s2.join() + ' vs ' + order.slice(1, 4).join())} finally {await stop()}console.log(`${pass} passed, ${fail} failed`)process.exit(fail ? 1 : 0)
Branches
Latest commits
- cfe95440|||PR day39 re-vendor: Hybriel 51e921d7 (bin 6b481aa7), ids kebab-case since hybriel#256: quoted state rule and tests use jb-shuffle / jb-repeatmre
- f3614c9bRe-vendor to Hybriel day39 (51e921d7, bin 6b481aa7)mre
- 9f5c6532Merge branch 'status-22-pr' into mainJukebox
- 5838d6c7|||PR STATUS: #22 pending decision, PR-only rulemre
- 29d2029cRecords: PR-only rule (Kunibert)mre
- adacb0abRecords: neutral ticket rule, #22 decision recordedmre
- b2d6f121Records: #308 hold liftedmre
- 7ab67533Records: day39 on hold (hybriel#308)mre
- 22f21739Records: note rebase before mergemre
- f7368ea3Records: mission 011 day39, waits for lisbethmre
- 9515d2cdRecords: jb20 livemre
- 019f6601ui gate: comment names the open bug components#27 (workaround, not fixed)mre
- 277a2722README: provenance linemre
- 4169ca6aREADME: sync pinmre
- a01f3aa8ui gate: back to the top before the sort checks (the screen reopens where it was left)mre
- f7936c20Lists keep their scroll position across a reload (jukebox#20): per-list offsets in storage/ui.json, gate jb20mre
- d67906devirtual-list and icons from components.hybriel e5b98ec (centerId, scrollTop, onScroll)mre
- df7920ceRecords: R3 startedmre
- 0549f038Mission 010: jb20 livemre
- 273494e2STATUS rewrittenmre