OverviewFilesCommitsIssuesDocsReleasesPeers

hypermosh-shell / test / frames.test.mjs

63 lines · javascript ref:
// frames unit test — the typed wire format must demux CTRL/DATA/SSH/SSH_END
// correctly, including when frames are split across arbitrary chunk boundaries.
import b4a from 'b4a'
import { frame, ctrlFrame, dataFrame, sshFrame, sshEndFrame, makeParser, T_DATA, T_SSH } from '../lib/frames.mjs'

let failures = 0
const ok = (cond, msg) => { if (cond) console.log('    ✅ ' + msg); else { console.log('    ❌ ' + msg); failures++ } }

console.log('[frames] typed frame demux')

// 1. Round-trip every type in one buffer.
{
  const events = []
  const parse = makeParser({
    onCtrl: (o) => events.push(['ctrl', o]),
    onData: (d) => events.push(['data', b4a.toString(d)]),
    onSsh: (d) => events.push(['ssh', b4a.toString(d)]),
    onSshEnd: () => events.push(['sshend'])
  })
  const buf = b4a.concat([
    ctrlFrame({ bridge: 60007 }),
    dataFrame(b4a.from('DGRAM1')),
    sshFrame(b4a.from('ssh-bytes')),
    sshEndFrame(),
    dataFrame(b4a.from('DGRAM2'))
  ])
  parse(buf)
  ok(events.length === 5, 'all 5 frames parsed')
  ok(events[0][0] === 'ctrl' && events[0][1].bridge === 60007, 'ctrl json decoded')
  ok(events[1][1] === 'DGRAM1' && events[4][1] === 'DGRAM2', 'data frames in order')
  ok(events[2][1] === 'ssh-bytes', 'ssh frame decoded')
  ok(events[3][0] === 'sshend', 'ssh-end frame decoded')
}

// 2. Byte-at-a-time delivery must reassemble identically (partial-frame safety).
{
  const events = []
  const parse = makeParser({ onData: (d) => events.push(b4a.toString(d)), onSsh: (d) => events.push('S:' + b4a.toString(d)) })
  const buf = b4a.concat([dataFrame(b4a.from('hello')), sshFrame(b4a.from('world'))])
  for (let i = 0; i < buf.length; i++) parse(buf.subarray(i, i + 1))
  ok(events.length === 2 && events[0] === 'hello' && events[1] === 'S:world', 'reassembles across 1-byte chunks')
}

// 3. Empty-payload frame (sshEnd) has a correct 5-byte header, len 0.
{
  const f = sshEndFrame()
  ok(f.length === 5 && f.readUInt32BE(1) === 0, 'empty frame header well-formed')
  const d = dataFrame(b4a.alloc(0))
  ok(d.length === 5 && d.readUInt8(0) === T_DATA, 'zero-length data frame well-formed')
  ok(sshFrame(b4a.from('x')).readUInt8(0) === T_SSH, 'ssh type byte correct')
}

// 4. Unknown handlers are ignored (wire tolerance) — no throw when onSsh absent.
{
  let dataSeen = 0
  const parse = makeParser({ onData: () => dataSeen++ })
  parse(b4a.concat([sshFrame(b4a.from('ignored')), dataFrame(b4a.from('x'))]))
  ok(dataSeen === 1, 'missing handler ignored, other frames still delivered')
}

console.log(failures === 0 ? '\n✅ frames test passed' : '\n❌ frames test failed')
process.exit(failures === 0 ? 0 : 1)