jukebox
All repositories: gitoria
13.4 KB
// tests/gate.mjs — the jukebox gate. Part 1: the scanner reads the fixtures (tests/fixtures, made by tests/make-fixtures.mjs) and// the parsed values are checked one by one; a rescan changes nothing; a changed, a new and a vanished file are noticed; the// library copy is not touched. Part 2: the server answers the JSON API from that database (a real HTTP client).// Run: node tests/gate.mjs (JUKEBOX_GATE_DIR = scratch dir, default /media/STORAGE/claude-scratch/atlas/JB1/gate; port 8701)import { spawn, execFileSync } from 'node:child_process'import { cpSync, rmSync, mkdirSync, readdirSync, readFileSync, writeFileSync, statSync, existsSync } from 'node:fs'import { dirname, join } from 'node:path'import { fileURLToPath } from 'node:url'import { createHash } from 'node:crypto'const root = join(dirname(fileURLToPath(import.meta.url)), '..')const scratch = process.env.JUKEBOX_GATE_DIR || '/media/STORAGE/claude-scratch/atlas/JB1/gate'const port = Number(process.env.JUKEBOX_GATE_PORT || 8701)let pass = 0, fail = 0const check = (name, ok, detail = '') => { if (ok) pass++; else { fail++; console.log('FAIL ' + name + (detail ? ' — ' + detail : '')) } }const eq = (name, got, want) => check(name, JSON.stringify(got) === JSON.stringify(want), 'got ' + JSON.stringify(got) + ', want ' + JSON.stringify(want))const near = (name, got, want, tol) => check(name, typeof got === 'number' && Math.abs(got - want) <= tol, 'got ' + got + ', want ' + want)rmSync(scratch, { recursive: true, force: true })const lib = join(scratch, 'library'), storage = join(scratch, 'storage')mkdirSync(scratch, { recursive: true })cpSync(join(root, 'tests/fixtures'), lib, { recursive: true })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') }const scan = () => {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 })const lines = out.split('\n')const result = JSON.parse(lines.find((l) => l.startsWith('scan: ')).slice(6))const songs = {}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 }return { result, songs, stats: JSON.parse(lines.find((l) => l.startsWith('stats: ')).slice(7)) }}console.log('part 1: scanner')const before = hashTree(lib)const first = scan()eq('first scan: files seen', first.result.seen, 11)eq('first scan: added', first.result.added, 11)eq('first scan: unreadable', first.result.unreadable, 0)const S = first.songslet s = S['v23-two-owners.mp3']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)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)eq('genre (13) → Pop', s.genre, 'Pop'); eq('play count is the highest of Banshee 7, Guayadeque 12, PCNT 9', s.playCount, 12)eq('rating is the highest popm rating', s.rating, 192); eq('stars', s.stars, 4)eq('both owners kept', s.popm.map((p) => [p.owner, p.rating, p.count]).sort(), [['Banshee', 192, 7], ['Guayadeque', 128, 12]])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)eq('search field is folded', s.search.includes('uber song') && s.search.includes('die arzte'), true)eq('album key = artist + album name, no folder, no disc marker', s.albumKey, 'die arzte|album eins')s = S['v24-cover.mp3']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')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')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)check('embedded cover stored', s.coverId && existsSync(join(storage, 'covers', s.coverId + '.png')), 'coverId ' + s.coverId)s = S['v24-extheader.mp3']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])s = S['v23-unsync.mp3']eq('unsynchronised tag: title', s.title, 'Unsynced'); eq('artist', s.artist, 'Sync Band'); eq('album', s.album, 'Sync Album')eq('counter 0x00ff00ff survives the FF 00 escaping', s.playCount, 16711935); eq('rating 255', s.rating, 255)s = S['v22.mp3']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)eq('genre (17) → Rock', s.genre, 'Rock'); eq('POP counter', s.playCount, 21); eq('rating 64 → 2 stars', [s.rating, s.stars], [64, 2])s = S['comma.mp3']eq('commas kept in the texts', [s.title, s.artist, s.album], ['Eins, zwei', 'Band, The', 'Album, mit Komma'])check('no comma in the index keys', !s.albumKey.includes(',') && !s.sortTitle.includes(',') && !s.sortArtist.includes(',') && !s.artistKey.includes(','))s = S['pcnt-only.mp3']eq('PCNT only: play count', s.playCount, 5); eq('no popm', s.popm.length, 0); eq('title with umlaut', s.title, 'Nur Zähler')s = S['v1-only.mp3']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')s = S['notags.mp3']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)near('no tags: duration', s.duration, 1, 0.25)s = S['withcover/song-without-picture.mp3']check('folder.jpg used as the cover', s.coverId && existsSync(join(storage, 'covers', s.coverId + '.jpg')), 'coverId ' + s.coverId)s = S['tagged.ogg']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)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)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)eq('the library was not touched by the first scan', hashTree(lib), before)const again = scan()eq('rescan without changes: nothing added, updated or removed', [again.result.added, again.result.updated, again.result.removed], [0, 0, 0])eq('rescan without changes: all seen', again.result.seen, 11)eq('the library was not touched by the rescan', hashTree(lib), before)// a changed file, a new file, a vanished file (in the COPY of the fixtures)const pc = join(lib, 'pcnt-only.mp3'); const buf = readFileSync(pc); writeFileSync(pc, Buffer.concat([buf, Buffer.alloc(16)]))cpSync(join(lib, 'v22.mp3'), join(lib, 'v22-copy.mp3')); rmSync(join(lib, 'notags.mp3'))const third = scan()eq('changed + new + vanished noticed', [third.result.added, third.result.updated, third.result.removed], [1, 1, 1])check('vanished song gone from the database', third.songs['notags.mp3'] === undefined); check('new song present', third.songs['v22-copy.mp3'] !== undefined)eq('song count now', third.stats.songs, 11)eq('addedAt of the changed song is kept', third.songs['pcnt-only.mp3'].addedAt, again.songs['pcnt-only.mp3'].addedAt)// a missing library path removes nothingconst 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 })check('an unreadable library path removes nothing', JSON.parse(gone.split('\n').find((l) => l.startsWith('scan: ')).slice(6)).removed === 0)console.log('part 2: the JSON API')writeFileSync(join(storage, 'settings.json'), JSON.stringify({ libraryPaths: [lib], rescanMinutes: 30 }))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'] })const serverPid = server.pidconst 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 } }try {let up = falsefor (let i = 0; i < 80 && !up; i++) { try { up = (await get('/api/stats')).status === 200 } catch { await new Promise((r) => setTimeout(r, 2000)) } }check('server up', up)let r = await get('/api/stats')eq('stats: songs', r.json.library.songs, 11); eq('stats: artists', r.json.library.artists, 10); check('stats: albums', r.json.library.albums >= 9)r = await get('/api/songs?sort=title&limit=3')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])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)r = await get('/api/songs?sort=album&limit=100000'); eq('limit is capped at 200', r.json.limit, 200)r = await get('/api/songs'); eq('default page is 50 rows at most', r.json.limit, 50)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)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) }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'))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])r = await get('/api/songs?sort=bogus'); eq('bad sort is refused', r.status, 400)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'])r = await get('/api/search?q=' + encodeURIComponent('GRÖSSE')); eq('search folds case and ß/ö: "GRÖSSE" finds Größe', r.json.songs.total, 1)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)r = await get('/api/search'); eq('search without q', r.status, 400)r = await get('/api/artists?limit=2'); eq('artists page', [r.json.items.length, r.json.total], [2, 10])r = await get('/api/albums'); check('albums page', r.json.total >= 10 && r.json.items[0].songCount >= 1)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)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])const cov = (await get('/api/songs?sort=title&limit=50')).json.items.find((x) => x.coverId)const cr = await fetch('http://127.0.0.1:' + port + '/api/cover/' + cov.coverId); const cb = Buffer.from(await cr.arrayBuffer())eq('cover: status and type', [cr.status, cr.headers.get('content-type').startsWith('image/')], [200, true]); check('cover: the file bytes', cb.length > 50)r = await get('/api/cover/nothing'); eq('unknown cover', r.status, 404)r = await get('/api/rescan', { method: 'POST' }); eq('rescan accepted', r.status, 202)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)) }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))r = await get('/api/rescan'); eq('rescan needs POST', r.status, 405)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)r = await get('/api/settings', { method: 'POST', body: '{nonsense' }); eq('settings: bad JSON refused', r.status, 400)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)r = await get('/'); check('start page', r.status === 200 && r.text.includes('Jukebox'))} finally {if (existsSync('/proc/' + serverPid)) process.kill(serverPid)}console.log(`gate: ${pass} passed, ${fail} failed`)process.exit(fail ? 1 : 0)
Branches
Latest commits
- 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
- 227c9b96Records: jb19 livemre
- 9f365376README: the bar's controls (jb19)mre
- d18851fdjb19: pressed switches look different (whole selector), queue column cannot widen past the panel, gates follow the new bar (jb3, jb11, jb15)mre