gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/tests/gate.mjs

13.4 KB

  1. // tests/gate.mjs — the jukebox gate. Part 1: the scanner reads the fixtures (tests/fixtures, made by tests/make-fixtures.mjs) and
  2. // the parsed values are checked one by one; a rescan changes nothing; a changed, a new and a vanished file are noticed; the
  3. // library copy is not touched. Part 2: the server answers the JSON API from that database (a real HTTP client).
  4. // Run: node tests/gate.mjs (JUKEBOX_GATE_DIR = scratch dir, default /media/STORAGE/claude-scratch/atlas/JB1/gate; port 8701)
  5. import { spawn, execFileSync } from 'node:child_process'
  6. import { cpSync, rmSync, mkdirSync, readdirSync, readFileSync, writeFileSync, statSync, existsSync } from 'node:fs'
  7. import { dirname, join } from 'node:path'
  8. import { fileURLToPath } from 'node:url'
  9. import { createHash } from 'node:crypto'
  10. const root = join(dirname(fileURLToPath(import.meta.url)), '..')
  11. const scratch = process.env.JUKEBOX_GATE_DIR || '/media/STORAGE/claude-scratch/atlas/JB1/gate'
  12. const port = Number(process.env.JUKEBOX_GATE_PORT || 8701)
  13. let pass = 0, fail = 0
  14. const check = (name, ok, detail = '') => { if (ok) pass++; else { fail++; console.log('FAIL ' + name + (detail ? ' — ' + detail : '')) } }
  15. const eq = (name, got, want) => check(name, JSON.stringify(got) === JSON.stringify(want), 'got ' + JSON.stringify(got) + ', want ' + JSON.stringify(want))
  16. const near = (name, got, want, tol) => check(name, typeof got === 'number' && Math.abs(got - want) <= tol, 'got ' + got + ', want ' + want)
  17. rmSync(scratch, { recursive: true, force: true })
  18. const lib = join(scratch, 'library'), storage = join(scratch, 'storage')
  19. mkdirSync(scratch, { recursive: true })
  20. cpSync(join(root, 'tests/fixtures'), lib, { recursive: true })
  21. const hashTree = (dir) => { const h = createHash('sha256'); const walk = (d) => { for (const e of readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) { const p = join(d, e.name); if (e.isDirectory()) walk(p); else { const s = statSync(p); h.update(p + s.size + ':' + s.mtimeMs + ':' + s.ctimeMs + ':' + createHash('sha256').update(readFileSync(p)).digest('hex')) } } }; walk(dir); return h.digest('hex') }
  22. const scan = () => {
  23. const out = execFileSync(join(root, 'bin/hybriel'), [join(root, 'tools/scan.hl'), lib], { env: { ...process.env, JUKEBOX_STORAGE: storage, JUKEBOX_DUMP: '1' }, encoding: 'utf8', timeout: 300000 })
  24. const lines = out.split('\n')
  25. const result = JSON.parse(lines.find((l) => l.startsWith('scan: ')).slice(6))
  26. const songs = {}
  27. for (const l of lines.filter((l) => l.startsWith('SONG '))) { const s = JSON.parse(l.slice(5)); songs[s.path.slice(lib.length + 1)] = s }
  28. return { result, songs, stats: JSON.parse(lines.find((l) => l.startsWith('stats: ')).slice(7)) }
  29. }
  30. console.log('part 1: scanner')
  31. const before = hashTree(lib)
  32. const first = scan()
  33. eq('first scan: files seen', first.result.seen, 11)
  34. eq('first scan: added', first.result.added, 11)
  35. eq('first scan: unreadable', first.result.unreadable, 0)
  36. const S = first.songs
  37. let s = S['v23-two-owners.mp3']
  38. eq('v2.3 title (UTF-16)', s.title, 'Über Song'); eq('v2.3 artist (Latin-1)', s.artist, 'Die Ärzte'); eq('v2.3 album: the CD marker is folded out of the name', s.album, 'Album Eins'); eq('v2.3 disc number from the CD 1 marker', s.disc, 1)
  39. eq('v2.3 track', [s.track, s.trackTotal], [3, 12]); eq('v2.3 disc', [s.disc, s.discTotal], [1, 2]); eq('v2.3 year from TYER', s.year, 1999)
  40. eq('genre (13) → Pop', s.genre, 'Pop'); eq('play count is the highest of Banshee 7, Guayadeque 12, PCNT 9', s.playCount, 12)
  41. eq('rating is the highest popm rating', s.rating, 192); eq('stars', s.stars, 4)
  42. eq('both owners kept', s.popm.map((p) => [p.owner, p.rating, p.count]).sort(), [['Banshee', 192, 7], ['Guayadeque', 128, 12]])
  43. near('mp3 duration', s.duration, 1, 0.25); eq('format', s.format, 'mp3'); check('size known', s.size > 5000); check('change time known', s.changeTime > 1e12)
  44. eq('search field is folded', s.search.includes('uber song') && s.search.includes('die arzte'), true)
  45. eq('album key = artist + album name, no folder, no disc marker', s.albumKey, 'die arzte|album eins')
  46. s = S['v24-cover.mp3']
  47. eq('v2.4 title (UTF-8)', s.title, 'Größe Ängste'); eq('first of two artists in TPE1', s.artist, 'Erste Band'); eq('album artist groups the album', s.albumArtist, 'Sammler')
  48. eq('v2.4 year from TDRC', s.year, 2005); eq('track 11/21', [s.track, s.trackTotal], [11, 21]); eq('genre 49 → Gothic', s.genre, 'Gothic')
  49. eq('WMP owner kept', s.popm.map((p) => [p.owner, p.rating, p.count]), [['Windows Media Player 9 Series', 255, 4]]); eq('5 stars', s.stars, 5); eq('play count', s.playCount, 4)
  50. check('embedded cover stored', s.coverId && existsSync(join(storage, 'covers', s.coverId + '.png')), 'coverId ' + s.coverId)
  51. s = S['v24-extheader.mp3']
  52. eq('extended header skipped: title', s.title, 'Mit Erweiterung'); eq('artist', s.artist, 'Extender'); eq('play count 3 with rating 0', [s.playCount, s.rating, s.stars], [3, 0, 0])
  53. s = S['v23-unsync.mp3']
  54. eq('unsynchronised tag: title', s.title, 'Unsynced'); eq('artist', s.artist, 'Sync Band'); eq('album', s.album, 'Sync Album')
  55. eq('counter 0x00ff00ff survives the FF 00 escaping', s.playCount, 16711935); eq('rating 255', s.rating, 255)
  56. s = S['v22.mp3']
  57. eq('v2.2 title', s.title, 'Alt'); eq('artist', s.artist, 'Old Timer'); eq('album', s.album, 'Retro'); eq('track', [s.track, s.trackTotal], [5, 9]); eq('year', s.year, 1994)
  58. eq('genre (17) → Rock', s.genre, 'Rock'); eq('POP counter', s.playCount, 21); eq('rating 64 → 2 stars', [s.rating, s.stars], [64, 2])
  59. s = S['comma.mp3']
  60. eq('commas kept in the texts', [s.title, s.artist, s.album], ['Eins, zwei', 'Band, The', 'Album, mit Komma'])
  61. check('no comma in the index keys', !s.albumKey.includes(',') && !s.sortTitle.includes(',') && !s.sortArtist.includes(',') && !s.artistKey.includes(','))
  62. s = S['pcnt-only.mp3']
  63. eq('PCNT only: play count', s.playCount, 5); eq('no popm', s.popm.length, 0); eq('title with umlaut', s.title, 'Nur Zähler')
  64. s = S['v1-only.mp3']
  65. eq('ID3v1: title', s.title, 'Alt Lied'); eq('artist', s.artist, 'Alte Band'); eq('album', s.album, 'Altes Album'); eq('year', s.year, 1987); eq('track', s.track, 4); eq('genre 17', s.genre, 'Rock')
  66. s = S['notags.mp3']
  67. eq('no tags: title = file name', s.title, 'notags'); eq('artist', s.artist, 'Unknown artist'); eq('album', s.album, 'Unknown album'); eq('no play count', s.playCount, 0)
  68. near('no tags: duration', s.duration, 1, 0.25)
  69. s = S['withcover/song-without-picture.mp3']
  70. check('folder.jpg used as the cover', s.coverId && existsSync(join(storage, 'covers', s.coverId + '.jpg')), 'coverId ' + s.coverId)
  71. s = S['tagged.ogg']
  72. eq('ogg via ffprobe: title', s.title, 'Vogel'); eq('artist', s.artist, 'Ogg Band'); eq('album', s.album, 'Ogg Album'); eq('year', s.year, 2011)
  73. eq('track 2/8', [s.track, s.trackTotal], [2, 8]); eq('genre', s.genre, 'Rock'); eq('format', s.format, 'ogg'); near('ogg duration', s.duration, 1, 0.3)
  74. eq('stats: songs', first.stats.songs, 11); eq('stats: covers (2 pictures)', first.stats.covers, 2); eq('stats: played at least 5', first.stats.playedAtLeast5, 4)
  75. eq('the library was not touched by the first scan', hashTree(lib), before)
  76. const again = scan()
  77. eq('rescan without changes: nothing added, updated or removed', [again.result.added, again.result.updated, again.result.removed], [0, 0, 0])
  78. eq('rescan without changes: all seen', again.result.seen, 11)
  79. eq('the library was not touched by the rescan', hashTree(lib), before)
  80. // a changed file, a new file, a vanished file (in the COPY of the fixtures)
  81. const pc = join(lib, 'pcnt-only.mp3'); const buf = readFileSync(pc); writeFileSync(pc, Buffer.concat([buf, Buffer.alloc(16)]))
  82. cpSync(join(lib, 'v22.mp3'), join(lib, 'v22-copy.mp3')); rmSync(join(lib, 'notags.mp3'))
  83. const third = scan()
  84. eq('changed + new + vanished noticed', [third.result.added, third.result.updated, third.result.removed], [1, 1, 1])
  85. check('vanished song gone from the database', third.songs['notags.mp3'] === undefined); check('new song present', third.songs['v22-copy.mp3'] !== undefined)
  86. eq('song count now', third.stats.songs, 11)
  87. eq('addedAt of the changed song is kept', third.songs['pcnt-only.mp3'].addedAt, again.songs['pcnt-only.mp3'].addedAt)
  88. // a missing library path removes nothing
  89. const gone = execFileSync(join(root, 'bin/hybriel'), [join(root, 'tools/scan.hl'), join(scratch, 'no-such-dir'), lib], { env: { ...process.env, JUKEBOX_STORAGE: storage }, encoding: 'utf8', timeout: 300000 })
  90. check('an unreadable library path removes nothing', JSON.parse(gone.split('\n').find((l) => l.startsWith('scan: ')).slice(6)).removed === 0)
  91. console.log('part 2: the JSON API')
  92. writeFileSync(join(storage, 'settings.json'), JSON.stringify({ libraryPaths: [lib], rescanMinutes: 30 }))
  93. const server = spawn(join(root, 'bin/hybriel'), [join(root, 'project.hl')], { env: { ...process.env, JUKEBOX_STORAGE: storage, JUKEBOX_PORT: String(port), JUKEBOX_WATCH: '0', JUKEBOX_AUTOSCAN: '0' }, stdio: ['ignore', 'pipe', 'pipe'] })
  94. const serverPid = server.pid
  95. const get = async (path, opt) => { const r = await fetch('http://127.0.0.1:' + port + path, opt); const t = await r.text(); let j = null; try { j = JSON.parse(t) } catch { } return { status: r.status, type: r.headers.get('content-type'), json: j, text: t, headers: r.headers } }
  96. try {
  97. let up = false
  98. for (let i = 0; i < 80 && !up; i++) { try { up = (await get('/api/stats')).status === 200 } catch { await new Promise((r) => setTimeout(r, 2000)) } }
  99. check('server up', up)
  100. let r = await get('/api/stats')
  101. eq('stats: songs', r.json.library.songs, 11); eq('stats: artists', r.json.library.artists, 10); check('stats: albums', r.json.library.albums >= 9)
  102. r = await get('/api/songs?sort=title&limit=3')
  103. eq('songs by title: first three', r.json.items.map((x) => x.title), ['Alt', 'Alt Lied', 'Eins, zwei']); eq('page numbers', [r.json.total, r.json.offset, r.json.limit], [10, 0, 3])
  104. r = await get('/api/songs?sort=artist&limit=2&offset=1'); check('songs by artist: offset works', r.json.items.length === 2 && r.json.offset === 1)
  105. r = await get('/api/songs?sort=album&limit=100000'); eq('limit is capped at 200', r.json.limit, 200)
  106. r = await get('/api/songs'); eq('default page is 50 rows at most', r.json.limit, 50)
  107. r = await get('/api/songs?minPlays=5'); eq('minPlays=5 keeps the played songs (the copy of v22 is shown once)', r.json.total, 4)
  108. for (const so of ['title', 'artist', 'album']) { r = await get('/api/songs?sort=' + so + '&limit=200'); eq('sorted by ' + so + ' lists every song after the database was reopened (indexed values with a comma)', r.json.items.length, 10) }
  109. r = await get('/api/songs?sort=title&limit=200'); check('the song with commas is listed', r.json.items.some((x) => x.title === 'Eins, zwei'))
  110. r = await get('/api/search?q=' + encodeURIComponent('band, the')); eq('search with a comma finds the artist too', [r.json.songs.total, r.json.artists.length], [1, 1])
  111. r = await get('/api/songs?sort=bogus'); eq('bad sort is refused', r.status, 400)
  112. r = await get('/api/search?q=' + encodeURIComponent('uber song')); eq('search folds accents: "uber song" finds Über Song', r.json.songs.items.map((x) => x.title), ['Über Song'])
  113. r = await get('/api/search?q=' + encodeURIComponent('GRÖSSE')); eq('search folds case and ß/ö: "GRÖSSE" finds Größe', r.json.songs.total, 1)
  114. r = await get('/api/search?q=sync+band'); eq('search needs every word', r.json.songs.total, 1); r = await get('/api/search?q=sync+nothing'); eq('search misses', r.json.songs.total, 0)
  115. r = await get('/api/search'); eq('search without q', r.status, 400)
  116. r = await get('/api/artists?limit=2'); eq('artists page', [r.json.items.length, r.json.total], [2, 10])
  117. r = await get('/api/albums'); check('albums page', r.json.total >= 10 && r.json.items[0].songCount >= 1)
  118. const aid = (await get('/api/albums')).json.items[0].id; r = await get('/api/songs?album=' + aid); check('songs of an album', r.json.total >= 1)
  119. r = await get('/api/shuffle?minPlays=5&count=3'); eq('shuffle: 3 of the 4 played songs', [r.json.items.length, r.json.total], [3, 4])
  120. const cov = (await get('/api/songs?sort=title&limit=50')).json.items.find((x) => x.coverId)
  121. const cr = await fetch('http://127.0.0.1:' + port + '/api/cover/' + cov.coverId); const cb = Buffer.from(await cr.arrayBuffer())
  122. eq('cover: status and type', [cr.status, cr.headers.get('content-type').startsWith('image/')], [200, true]); check('cover: the file bytes', cb.length > 50)
  123. r = await get('/api/cover/nothing'); eq('unknown cover', r.status, 404)
  124. r = await get('/api/rescan', { method: 'POST' }); eq('rescan accepted', r.status, 202)
  125. for (let i = 0; i < 60; i++) { r = await get('/api/stats'); if (!r.json.scan.running && !r.json.scan.queued) break; await new Promise((x) => setTimeout(x, 1000)) }
  126. check('the asked-for scan ran and ended', !r.json.scan.running && r.json.lastScan && r.json.scan.seen === 11, JSON.stringify(r.json.scan))
  127. r = await get('/api/rescan'); eq('rescan needs POST', r.status, 405)
  128. r = await get('/api/settings', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ libraryPaths: ['relative/path'] }) }); eq('settings: relative path refused', r.status, 400)
  129. r = await get('/api/settings', { method: 'POST', body: '{nonsense' }); eq('settings: bad JSON refused', r.status, 400)
  130. r = await get('/api/settings', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ libraryPaths: [lib], rescanMinutes: 15 }) }); eq('settings saved', r.json.rescanMinutes, 15)
  131. r = await get('/'); check('start page', r.status === 200 && r.text.includes('Jukebox'))
  132. } finally {
  133. if (existsSync('/proc/' + serverPid)) process.kill(serverPid)
  134. }
  135. console.log(`gate: ${pass} passed, ${fail} failed`)
  136. 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