beffroi-tools/companion-modules/media-player-classic/test/lifecycle.test.js

214 lines
7.8 KiB
JavaScript

import assert from 'node:assert/strict'
import { createServer } from 'node:http'
import { test } from 'node:test'
import { InstanceStatus } from '@companion-module/base'
import MpcInstance from '../src/main.js'
import { status as sample } from './fixture.js'
function instance() {
const state = { statuses: [] }
const module = new MpcInstance({
_isInstanceContext: true,
id: 'test-mpc',
label: 'MPC_TEST',
setActionDefinitions: (actions) => {
state.actions = actions
},
setPresetDefinitions: (sections, presets) => {
state.sections = sections
state.presets = presets
},
setFeedbackDefinitions: (feedbacks) => {
state.feedbacks = feedbacks
},
setVariableDefinitions: () => {},
setVariableValues: (variables) => {
state.variables = variables
},
checkAllFeedbacks: () => {},
updateStatus: (status) => state.statuses.push(status),
})
return { module, state }
}
test('initialization registers API 2 presets; successful actions recover failed requests', async (t) => {
let status = 200
const server = createServer((_, response) => {
response.writeHead(status)
response.end(JSON.stringify(sample))
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const { module, state } = instance()
t.after(async () => {
await module.destroy()
server.closeAllConnections()
server.close()
})
await module.init({ host: '127.0.0.1', port: server.address().port })
await module.send('887')
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
assert.equal(Object.keys(state.actions).length, 142)
assert.deepEqual(state.sections.flatMap((section) => section.definitions).sort(), Object.keys(state.presets).sort())
assert.equal(state.variables.remaining, '00:48')
assert.equal(state.feedbacks.playing.callback(), true)
assert.ok(Object.values(state.presets).every((preset) => ['simple', 'layered'].includes(preset.type)))
status = 503
await module.send('887')
assert.equal(state.statuses.at(-1), InstanceStatus.ConnectionFailure)
assert.equal(state.variables.state, 'offline')
assert.equal(state.variables.muted, null)
assert.equal(state.feedbacks.playing.callback(), false)
status = 200
await module.send('888')
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
})
test('configuration changes and destroy cancel stale operations without overwriting status', async (t) => {
const server = createServer(() => {})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
t.after(() => {
server.closeAllConnections()
server.close()
})
const { module, state } = instance()
await module.init({ host: '127.0.0.1', port: server.address().port })
const oldRequest = module.send('887')
await module.configUpdated({ host: '' })
await oldRequest
assert.equal(state.statuses.at(-1), InstanceStatus.BadConfig)
await module.configUpdated({ host: '127.0.0.1', port: server.address().port })
const pending = module.send('888')
await module.destroy()
const count = state.statuses.length
await pending
assert.equal(state.statuses.length, count)
assert.equal(module.main, undefined)
assert.equal(module.backup, undefined)
})
test('polling discovers external changes, retries failures, and stops on destroy', async (t) => {
let data = { ...sample }
let code = 200
let requests = 0
let active = 0
let maximum = 0
const server = createServer((_, response) => {
requests++
active++
maximum = Math.max(maximum, active)
setTimeout(() => {
active--
response.writeHead(code)
response.end(JSON.stringify(data))
}, 15)
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const { module, state } = instance()
t.after(async () => {
await module.destroy()
server.closeAllConnections()
server.close()
})
const until = async (condition) => {
const deadline = Date.now() + 3000
while (!condition()) {
assert.ok(Date.now() < deadline, 'polling did not reach expected state')
await new Promise((resolve) => setTimeout(resolve, 10))
}
}
await module.init({ host: '127.0.0.1', port: server.address().port, poll_interval: 250 })
await Promise.all(Array.from({ length: 10 }, () => module.refresh()))
assert.equal(maximum, 1)
assert.equal(requests, 1)
data = { ...sample, state: 1, muted: true, position: 20000 }
await until(() => state.variables.paused && state.variables.muted)
assert.equal(state.variables.remaining, '00:40')
code = 503
await until(() => state.variables.state === 'offline')
assert.equal(state.variables.remaining, '--:--')
code = 200
data = { ...sample, state: 0, position: 0 }
await until(() => state.variables.stopped)
assert.equal(state.feedbacks.stopped.callback(), true)
await module.destroy()
const lastCount = requests
await new Promise((resolve) => setTimeout(resolve, 350))
assert.equal(requests, lastCount)
})
for (const direction of ['next', 'previous']) {
const navigationId = direction === 'next' ? '920' : '919'
test(`Load ${direction} preset runs on main with unavailable backup and exposes independent results`, async (t) => {
const data = { ...sample, state: 0 }
const commands = []
const mainServer = createServer((req, res) => {
const id = new URL(req.url, 'http://localhost').searchParams.get('wm_command')
if (id) {
commands.push(id)
if (id === '909') data.muted = !data.muted
if (id === navigationId) {
data.file = 'Next.mp4'
data.state = 2
}
if (id === '890') data.state = 0
}
res.end(JSON.stringify(data))
})
const backupServer = createServer((_, res) => {
res.writeHead(503)
res.end()
})
await Promise.all(
[mainServer, backupServer].map((server) => new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))),
)
const { module, state } = instance()
t.after(async () => {
await module.destroy()
for (const server of [mainServer, backupServer]) {
server.closeAllConnections()
server.close()
}
})
await module.init({
host: '127.0.0.1',
port: mainServer.address().port,
backup_host: '127.0.0.1',
backup_port: backupServer.address().port,
})
assert.equal(state.presets[`transport_load_${direction}`].steps[0].down[0].actionId, `load_${direction}`)
const pending = state.actions[`load_${direction}`].callback({ options: { target: 'both' } })
await module.send('887')
await Promise.all([pending, state.actions[`load_${direction}`].callback({ options: { target: 'both' } })])
assert.deepEqual(commands, ['909', navigationId, '890', '909'])
assert.equal(state.variables[`load_${direction}_status`], 'ready')
assert.equal(state.variables[`backup_load_${direction}_status`], 'failed')
assert.equal(state.variables[`load_${direction === 'next' ? 'previous' : 'next'}_status`], 'idle')
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
assert.equal(
state.feedbacks[`load_${direction}_status`].callback().text,
direction === 'next' ? '↦\nLOADED\nNEXT' : '↤\nLOADED\nPREV',
)
assert.deepEqual(state.presets.transport_load_result.steps[0].down, [])
await new Promise((resolve) => setTimeout(resolve, 2100))
assert.equal(
state.feedbacks[`load_${direction}_status`].callback().text,
direction === 'next' ? '↦\nLOAD\nNEXT' : '↤\nLOAD\nPREV',
)
assert.equal(module.backup.loadDisplayStatus, 'idle')
assert.equal(state.variables.backup_load_result_status, 'failed')
assert.equal(state.variables.load_result_status, 'ready')
assert.equal(state.variables.load_result_direction, direction)
assert.equal(state.variables.load_result_file, 'Next.mp4')
const resultText = 'LOADED\nNext'
assert.equal(state.feedbacks.load_result.callback().text, resultText)
data.state = 2
await module.refresh()
assert.equal(state.variables[`load_${direction}_status`], 'idle')
assert.equal(state.feedbacks.load_result.callback().text, resultText)
data.volume = null
await module.refresh()
assert.equal(state.variables.state, 'offline')
assert.equal(state.feedbacks.load_result.callback().text, resultText)
})
}