jukebox
All repositories: gitoria
11.9 KB
// tests/jb13.mjs — JB13 (jukebox#13): a tapped song must be the song that plays, even when counted plays changed the server's order// while the rows on the screen stayed where they were. Own server on a generated database of 300 songs (one 3 s tone), headless Chrome.// Songs sorted by plays and Favourites: the screen is open, a play is counted for another song through POST /api/played/<id> (the order// changes), then a row is tapped: the song that plays (currentSrc of the audio element) must be the tapped row's id. The queue goes on// from that song's place in the new order, and the rows on the screen refresh to what the server now has.// node tests/jb13.mjs env: JB13_PORT (default 8735), JB13_DIR (scratch), JB13_ROOT (checkout to test), HL_PORT_BASE (default 8520), JUKEBOX_COLD_MSimport { spawn, execFileSync } from 'node:child_process'import { rmSync, mkdirSync } 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 || '8520'const { launchBrowser, sleep } = await import('./cdp.mjs')const root = process.env.JB13_ROOT || join(dirname(fileURLToPath(import.meta.url)), '..')const dir = process.env.JB13_DIR || '/media/STORAGE/claude-scratch/atlas/JB13/gate'const port = Number(process.env.JB13_PORT || 8735)const BASE = `http://127.0.0.1:${port}`const COLD_MS = Number(process.env.JUKEBOX_COLD_MS || 150000)let 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, 'tone3.mp3')rmSync(storage, { recursive: true, force: true })execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=3', '-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, '300'], { 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 })const api = async (path, method = 'GET') => (await fetch(BASE + path, { method })).json()const play = async (id, n = 1) => { for (let i = 0; i < n; i++) await api('/api/played/' + id, 'POST') }try {for (const t0 = Date.now(); ; ) {try { if ((await fetch(BASE + '/api/stats')).ok) break } catch {}if (Date.now() - t0 > COLD_MS) { console.log(log); throw new Error('the server did not come up') }await sleep(500)}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 })const byArtist = (await api('/api/songs?sort=artist&limit=200')).items// three songs that are favourites already (5 plays), far down the artist orderfor (const s of byArtist.slice(100, 103)) await play(s.id, 5)const rowIds = () => ev(`[...document.querySelectorAll('virtual-list .vl-row:not(.blank)')].map((r) => r.getAttribute('data-id'))`)const playing = () => ev(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc ? a.currentSrc.split('/stream/')[1] : '' })()`)const tapAndRead = async (index) => {await page.click(`virtual-list .vl-row[data-index="${index}"]`)await page.waitFor(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc.indexOf('/stream/') > 0 })()`, { timeout: 20000, label: 'a song plays' })await sleep(800)return playing()}// ---- Songs, most played ----await page.goto(BASE + '/')await page.waitForSelector('virtual-list .vl-row:not(.blank)')const press = async (key, code, vk) => { await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key, code, windowsVirtualKeyCode: vk }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code, windowsVirtualKeyCode: vk }) }await page.focus('#sort')for (let i = 0; i < 3; i++) { await press('ArrowDown', 'ArrowDown', 40); await sleep(300) }await page.waitFor(`document.querySelector('virtual-list .vl-row .vl-aside') && /×/.test(document.querySelector('virtual-list .vl-row .vl-aside').textContent)`, { label: 'sorted by plays' })await sleep(500)const before = await rowIds()const tapped = before[6], other = before[9]const tappedCount = (await api('/api/songs?sort=plays&limit=200')).items.find((s) => s.id === tapped).playCountawait play(other) // the order on the server changes: `other` jumps up, the rows above it move down one placeconst after = (await api('/api/songs?sort=plays&limit=40')).items.map((s) => s.id)check('setup: counting a play changed the server order at the tapped place', after[6] !== tapped, 'row 6 is still ' + tapped)const got = await tapAndRead(6)check('Songs by plays: the song that plays is the tapped row (not the song that moved into its place)', got === tapped, `tapped ${tapped}, plays ${got}, server row 6 now ${after[6]}`)const at = after.indexOf(tapped)const next = (await api('/api/songs?sort=plays&limit=40')).items[at + 1]const q = await ev(`[...document.querySelectorAll('.jb-bar ol.mp-queue li .mp-q-title')].map((e) => e.textContent)`)check('Songs by plays: the queue goes on from the tapped song\'s place in the current order', q.length > 1 && !!next && q.includes(next.title) && q.indexOf(next.title) <= 1, JSON.stringify({ next: next && next.title, q: q.slice(0, 3) }))await page.waitFor(`(() => { const a = [...document.querySelectorAll('virtual-list .vl-row:not(.blank)')].map((r) => r.getAttribute('data-id')); return a.length > 8 && a[0] === ${JSON.stringify(after[0])} && a[5] === ${JSON.stringify(after[5])} && a[6] === ${JSON.stringify(after[6])} })()`, { timeout: 8000, label: 'rows refreshed' }).then(() => check('Songs by plays: the rows on the screen show the server\'s order after the tap', true), (e) => check('Songs by plays: the rows on the screen show the server\'s order after the tap', false, 'rows ' + JSON.stringify([]) ))const wantAside = (tappedCount + 1) + '×'await ev(`(() => { const a = document.querySelector('media-player audio'); a.loop = true; if (a.paused) a.play(); return a.paused })()`)await page.waitFor(`(() => { const row = document.querySelector('virtual-list .vl-row[data-id="' + ${JSON.stringify(tapped)} + '"] .vl-aside'); return !!row && row.textContent === ${JSON.stringify(wantAside)} })()`, { timeout: 8000, label: 'counted play on the row' }).then(() => check('Songs by plays: counting the play updates that row on the open list', true), async () => {const seen = await ev(`(() => { const row = document.querySelector('virtual-list .vl-row[data-id="' + ${JSON.stringify(tapped)} + '"]'); const a = document.querySelector('media-player audio'); return { aside: row ? row.querySelector('.vl-aside').textContent : null, t: a && a.currentTime, paused: a && a.paused, ended: a && a.ended, dur: a && a.duration } })()`)const song = (await api('/api/songs?sort=plays&limit=200')).items.find((s) => s.id === tapped)check('Songs by plays: counting the play updates that row on the open list', false, 'wanted ' + wantAside + ' ' + JSON.stringify(seen) + ' api ' + JSON.stringify(song && { playCount: song.playCount, jukeboxPlays: song.jukeboxPlays }) + ' log ' + log.slice(-400))})// ---- Favourites ----await page.goto(BASE + '/')await page.waitForSelector('virtual-list .vl-row:not(.blank)')await sleep(1200)await page.click('#fav')await page.waitFor(`document.querySelector('#favmin') && document.querySelectorAll('virtual-list .vl-row:not(.blank)').length >= 3`, { label: 'favourites list' })await sleep(500)const fbefore = await rowIds()const ftapped = fbefore[1]await play(byArtist[0].id, 5) // a new favourite that sorts first: every row moves down one placeconst fafter = (await api('/api/songs?sort=artist&minPlays=5&limit=40')).items.map((s) => s.id)check('setup: a new favourite changed the order at the tapped place', fafter[1] !== ftapped, 'row 1 is still ' + ftapped)const fgot = await tapAndRead(1)check('Favourites: the song that plays is the tapped row', fgot === ftapped, `tapped ${ftapped}, plays ${fgot}, server row 1 now ${fafter[1]}`)// ---- Next, when the queue is down to one song ----// The last favourite is tapped (the queue holds only it). Then one new favourite sorts before it and one after it: its place number moves up by one.// Next must play the song AFTER it in the new order (the new favourite at the end), not ask for "place + 1" (which is the song itself again).// a short favourites list: the minimum is raised until at most 8 songs are left (the test songs carry generated file counts)let N = 5while ((await api('/api/songs?sort=artist&minPlays=' + N + '&limit=1')).total > 8) N++const favNow = (await api('/api/songs?sort=artist&minPlays=' + N + '&limit=40')).items.map((s) => s.id)const nfav = favNow.lengthawait page.goto(BASE + '/')await page.waitForSelector('virtual-list .vl-row:not(.blank)')// the screen opens the way it was left (most played, see JB14): back to the artist order the checks below count inawait page.focus('#sort')for (let i = 0; i < 3; i++) { await press('ArrowUp', 'ArrowUp', 38); await sleep(300) }await page.waitFor(`document.querySelector('#sort').value === 'artist'`, { label: 'sort artist' })await sleep(700)await page.click('#fav')await page.waitForSelector('#favmin')await page.type('#favmin', String(N), { clear: true })await page.waitFor(`document.querySelector('#count').textContent.startsWith(${JSON.stringify(String(nfav))} + ' ')`, { label: 'favourites with the minimum ' + N })await sleep(700)const last = favNow[nfav - 1]const got1 = await tapAndRead(nfav - 1)const queueLen = await ev(`document.querySelectorAll('.jb-bar ol.mp-queue li').length`)check('Next: the last favourite is tapped and the queue holds only that song', got1 === last && queueLen <= 1, `plays ${got1}, queue ${queueLen}`)const before1 = byArtist.find((s, i) => i > 0 && !favNow.includes(s.id)).id, after1 = (await api('/api/songs?sort=artist&limit=1&offset=299')).items[0].idawait play(before1, N); await play(after1, N)const order = (await api('/api/songs?sort=artist&minPlays=' + N + '&limit=40')).items.map((s) => s.id)check('setup: the order is now [..., the tapped song, a new favourite]', order[order.length - 2] === last && order[order.length - 1] === after1, JSON.stringify(order.slice(-3)))await page.click('.jb-bar .jb-next')await sleep(1500)const gotNext = await playing()if (process.env.JB13_DEBUG) console.log('DEBUG', JSON.stringify(await ev(`({ q: [...document.querySelectorAll('.jb-bar ol.mp-queue li .mp-q-title')].map((e) => e.textContent), paused: document.querySelector('media-player audio').paused, t: document.querySelector('media-player audio').currentTime })`)), log.slice(-600))check('Next: the song that plays is the one after the current song in the new order', gotNext === after1, `current ${last}, plays ${gotNext}, expected ${after1}`)} finally {await stop()}console.log(`${pass} passed, ${fail} failed`)process.exit(fail ? 1 : 0)
Branches
Latest commits
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre