liveCleanup.test.mjs 1.9 KB
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'

const modulePath = path.join(
  path.dirname(fileURLToPath(import.meta.url)),
  'liveCleanup.mjs',
)

async function loadCleanup() {
  assert.equal(fs.existsSync(modulePath), true, 'Live cleanup helper must exist')
  return import(pathToFileURL(modulePath))
}

test('best-effort cleanup attempts every tracked order in reverse order', async () => {
  const { cleanupTrackedOrders } = await loadCleanup()
  const calls = []
  const diagnostics = []
  const client = {
    async post(method, payload) {
      calls.push({ method, orderCode: payload.orderCode })
      if (method.endsWith('.revoke') && payload.orderCode === 'ORDER-2') {
        throw new Error('fixture revoke failure')
      }
      if (method.endsWith('.revoke')) return { code: 0 }
      return { code: 0, data: { status: 9 } }
    },
  }

  const result = await cleanupTrackedOrders({
    client,
    context: { sessionId: 'runtime-session' },
    orders: [
      { orderCode: 'ORDER-1', role: 'source' },
      { orderCode: 'ORDER-2', role: 'corrected' },
    ],
    label: 'fixture',
    onDiagnostic: (message) => diagnostics.push(message),
  })

  assert.deepEqual(
    calls.filter((call) => call.method.endsWith('.revoke')).map((call) => call.orderCode),
    ['ORDER-2', 'ORDER-1'],
  )
  assert.equal(result.length, 2)
  assert.equal(result.find((item) => item.orderCode === 'ORDER-2').revoked, false)
  assert.equal(result.find((item) => item.orderCode === 'ORDER-1').revoked, true)
  assert.deepEqual(JSON.parse(diagnostics[0].replace('fixture: ', '')), {
    orderCode: 'ORDER-2',
    role: 'corrected',
    reason: 'request-or-status-check-failed',
  })
  assert.doesNotMatch(JSON.stringify(result), /runtime-session/)
  assert.doesNotMatch(diagnostics.join('\n'), /runtime-session/)
})