gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchday418ed6da45|||PR README: media-player pin df9e7dfmreday41/tests/jb13.mjs

11.9 KB

  1. // tests/jb13.mjs — JB13 (jukebox#13): a tapped song must be the song that plays, even when counted plays changed the server's order
  2. // 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.
  3. // Songs sorted by plays and Favourites: the screen is open, a play is counted for another song through POST /api/played/<id> (the order
  4. // 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
  5. // from that song's place in the new order, and the rows on the screen refresh to what the server now has.
  6. // node tests/jb13.mjs env: JB13_PORT (default 8735), JB13_DIR (scratch), JB13_ROOT (checkout to test), HL_PORT_BASE (default 8520), JUKEBOX_COLD_MS
  7. import { spawn, execFileSync } from 'node:child_process'
  8. import { rmSync, mkdirSync } from 'node:fs'
  9. import { dirname, join } from 'node:path'
  10. import { fileURLToPath } from 'node:url'
  11. process.env.HL_CHROME = process.env.HL_CHROME || '/opt/google/chrome/chrome'
  12. process.env.HL_PORT_BASE = process.env.HL_PORT_BASE || '8520'
  13. const { launchBrowser, sleep } = await import('./cdp.mjs')
  14. const root = process.env.JB13_ROOT || join(dirname(fileURLToPath(import.meta.url)), '..')
  15. const dir = process.env.JB13_DIR || '/media/STORAGE/claude-scratch/atlas/JB13/gate'
  16. const port = Number(process.env.JB13_PORT || 8735)
  17. const BASE = `http://127.0.0.1:${port}`
  18. const COLD_MS = Number(process.env.JUKEBOX_COLD_MS || 150000)
  19. let pass = 0, fail = 0
  20. const check = (name, ok, detail = '') => { console.log((ok ? 'ok ' : 'FAIL ') + name + (ok ? '' : ' — ' + detail)); if (ok) pass++; else fail++ }
  21. mkdirSync(dir, { recursive: true })
  22. process.env.TMPDIR = dir
  23. let server = null, browser = null, log = ''
  24. async function stop() {
  25. if (browser) { try { await browser.close() } catch {} browser = null }
  26. if (server) { try { server.kill('SIGTERM') } catch {} await sleep(500); server = null }
  27. }
  28. process.on('SIGINT', async () => { await stop(); process.exit(1) })
  29. const storage = join(dir, 'storage')
  30. const tone = join(dir, 'tone3.mp3')
  31. rmSync(storage, { recursive: true, force: true })
  32. execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=3', '-q:a', '9', tone])
  33. const cover = join(root, 'tests/fixtures/withcover/folder.jpg')
  34. 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 })
  35. 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'] })
  36. console.log('server pid ' + server.pid)
  37. server.stdout.on('data', (d) => { log += d }); server.stderr.on('data', (d) => { log += d })
  38. const api = async (path, method = 'GET') => (await fetch(BASE + path, { method })).json()
  39. const play = async (id, n = 1) => { for (let i = 0; i < n; i++) await api('/api/played/' + id, 'POST') }
  40. try {
  41. for (const t0 = Date.now(); ; ) {
  42. try { if ((await fetch(BASE + '/api/stats')).ok) break } catch {}
  43. if (Date.now() - t0 > COLD_MS) { console.log(log); throw new Error('the server did not come up') }
  44. await sleep(500)
  45. }
  46. browser = await launchBrowser()
  47. console.log('chrome pid ' + browser.proc?.pid)
  48. const page = await browser.newPage()
  49. const ev = (e) => page.evaluate(e)
  50. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true })
  51. const byArtist = (await api('/api/songs?sort=artist&limit=200')).items
  52. // three songs that are favourites already (5 plays), far down the artist order
  53. for (const s of byArtist.slice(100, 103)) await play(s.id, 5)
  54. const rowIds = () => ev(`[...document.querySelectorAll('virtual-list .vl-row:not(.blank)')].map((r) => r.getAttribute('data-id'))`)
  55. const playing = () => ev(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc ? a.currentSrc.split('/stream/')[1] : '' })()`)
  56. const tapAndRead = async (index) => {
  57. await page.click(`virtual-list .vl-row[data-index="${index}"]`)
  58. await page.waitFor(`(() => { const a = document.querySelector('media-player audio'); return a && a.currentSrc.indexOf('/stream/') > 0 })()`, { timeout: 20000, label: 'a song plays' })
  59. await sleep(800)
  60. return playing()
  61. }
  62. // ---- Songs, most played ----
  63. await page.goto(BASE + '/')
  64. await page.waitForSelector('virtual-list .vl-row:not(.blank)')
  65. 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 }) }
  66. await page.focus('#sort')
  67. for (let i = 0; i < 3; i++) { await press('ArrowDown', 'ArrowDown', 40); await sleep(300) }
  68. 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' })
  69. await sleep(500)
  70. const before = await rowIds()
  71. const tapped = before[6], other = before[9]
  72. const tappedCount = (await api('/api/songs?sort=plays&limit=200')).items.find((s) => s.id === tapped).playCount
  73. await play(other) // the order on the server changes: `other` jumps up, the rows above it move down one place
  74. const after = (await api('/api/songs?sort=plays&limit=40')).items.map((s) => s.id)
  75. check('setup: counting a play changed the server order at the tapped place', after[6] !== tapped, 'row 6 is still ' + tapped)
  76. const got = await tapAndRead(6)
  77. 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]}`)
  78. const at = after.indexOf(tapped)
  79. const next = (await api('/api/songs?sort=plays&limit=40')).items[at + 1]
  80. const q = await ev(`[...document.querySelectorAll('.jb-bar ol.mp-queue li .mp-q-title')].map((e) => e.textContent)`)
  81. 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) }))
  82. 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([]) ))
  83. const wantAside = (tappedCount + 1) + '×'
  84. await ev(`(() => { const a = document.querySelector('media-player audio'); a.loop = true; if (a.paused) a.play(); return a.paused })()`)
  85. 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 () => {
  86. 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 } })()`)
  87. const song = (await api('/api/songs?sort=plays&limit=200')).items.find((s) => s.id === tapped)
  88. 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))
  89. })
  90. // ---- Favourites ----
  91. await page.goto(BASE + '/')
  92. await page.waitForSelector('virtual-list .vl-row:not(.blank)')
  93. await sleep(1200)
  94. await page.click('#fav')
  95. await page.waitFor(`document.querySelector('#favmin') && document.querySelectorAll('virtual-list .vl-row:not(.blank)').length >= 3`, { label: 'favourites list' })
  96. await sleep(500)
  97. const fbefore = await rowIds()
  98. const ftapped = fbefore[1]
  99. await play(byArtist[0].id, 5) // a new favourite that sorts first: every row moves down one place
  100. const fafter = (await api('/api/songs?sort=artist&minPlays=5&limit=40')).items.map((s) => s.id)
  101. check('setup: a new favourite changed the order at the tapped place', fafter[1] !== ftapped, 'row 1 is still ' + ftapped)
  102. const fgot = await tapAndRead(1)
  103. check('Favourites: the song that plays is the tapped row', fgot === ftapped, `tapped ${ftapped}, plays ${fgot}, server row 1 now ${fafter[1]}`)
  104. // ---- Next, when the queue is down to one song ----
  105. // 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.
  106. // 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).
  107. // a short favourites list: the minimum is raised until at most 8 songs are left (the test songs carry generated file counts)
  108. let N = 5
  109. while ((await api('/api/songs?sort=artist&minPlays=' + N + '&limit=1')).total > 8) N++
  110. const favNow = (await api('/api/songs?sort=artist&minPlays=' + N + '&limit=40')).items.map((s) => s.id)
  111. const nfav = favNow.length
  112. await page.goto(BASE + '/')
  113. await page.waitForSelector('virtual-list .vl-row:not(.blank)')
  114. // the screen opens the way it was left (most played, see JB14): back to the artist order the checks below count in
  115. await page.focus('#sort')
  116. for (let i = 0; i < 3; i++) { await press('ArrowUp', 'ArrowUp', 38); await sleep(300) }
  117. await page.waitFor(`document.querySelector('#sort').value === 'artist'`, { label: 'sort artist' })
  118. await sleep(700)
  119. await page.click('#fav')
  120. await page.waitForSelector('#favmin')
  121. await page.type('#favmin', String(N), { clear: true })
  122. await page.waitFor(`document.querySelector('#count').textContent.startsWith(${JSON.stringify(String(nfav))} + ' ')`, { label: 'favourites with the minimum ' + N })
  123. await sleep(700)
  124. const last = favNow[nfav - 1]
  125. const got1 = await tapAndRead(nfav - 1)
  126. const queueLen = await ev(`document.querySelectorAll('.jb-bar ol.mp-queue li').length`)
  127. check('Next: the last favourite is tapped and the queue holds only that song', got1 === last && queueLen <= 1, `plays ${got1}, queue ${queueLen}`)
  128. 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].id
  129. await play(before1, N); await play(after1, N)
  130. const order = (await api('/api/songs?sort=artist&minPlays=' + N + '&limit=40')).items.map((s) => s.id)
  131. 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)))
  132. await page.click('.jb-bar .jb-next')
  133. await sleep(1500)
  134. const gotNext = await playing()
  135. 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))
  136. 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}`)
  137. } finally {
  138. await stop()
  139. }
  140. console.log(`${pass} passed, ${fail} failed`)
  141. process.exit(fail ? 1 : 0)

Branches

Latest commits

  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre
  • 89cdabb1Vendor Hybriel day41 (57054d9e): plugin dirs, set .somre
  • 1fecd6a7Merge branch 'records-day39' into mainJukebox
  • d6b3e068|||PR Records: day39 live (PR #2), mission 011 PR step, statusmre
  • 5fa19e89Merge branch 'day39' into mainJukebox
  • 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