Files
order-notification-automation/tests/service/supervisor-crash.test.cjs
T

21 lines
2.5 KiB
JavaScript

'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),net=require('node:net'),{spawn}=require('node:child_process');
const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
const crash=guard=>process.platform==='win32'?require('node:child_process').execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command','Stop-Process -Id '+guard.pid+' -Force'],{windowsHide:true}):guard.kill('SIGKILL');
const alive=pid=>{try{process.kill(pid,0);return true;}catch{return false;}};
async function until(predicate,timeout=5000){const end=Date.now()+timeout;while(Date.now()<end){if(await predicate())return true;await pause(40);}return false;}
async function freePort(){const socket=net.createServer();await new Promise(resolve=>socket.listen(0,'127.0.0.1',resolve));const port=socket.address().port;await new Promise(resolve=>socket.close(resolve));return port;}
async function fixture(t){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-guard-crash-')),port=await freePort();let childPid;
const guard=spawn(process.execPath,[path.resolve('tests/service/fixtures/crash-supervisor.cjs')],{cwd:process.cwd(),windowsHide:true,detached:true,stdio:'ignore',env:{...process.env,ORDER_CRASH_TEST_DIR:dir,ORDER_CRASH_TEST_PORT:String(port)}});
t.after(async()=>{if(alive(guard.pid))guard.kill('SIGKILL');if(childPid&&alive(childPid))process.kill(childPid,'SIGKILL');await until(()=>!alive(guard.pid)&&(!childPid||!alive(childPid)));await fs.rm(dir,{recursive:true,force:true});});
assert.equal(await until(async()=>{try{childPid=Number(await fs.readFile(path.join(dir,'child.pid'),'utf8'));return Number(await fs.readFile(path.join(dir,'ticks'),'utf8'))>1;}catch{return false;}}),true,'isolated child must start');
return {dir,port,guard,childPid};
}
test('Windows abrupt supervisor death stops its business child and releases its listening port',{timeout:15000,skip:process.platform!=='win32'},async t=>{
const {dir,port,guard,childPid}=await fixture(t);crash(guard);
assert.equal(await until(()=>!alive(childPid)),true,'orphan business child must exit after supervisor death');
const ticks=await fs.readFile(path.join(dir,'ticks'),'utf8');await pause(150);assert.equal(await fs.readFile(path.join(dir,'ticks'),'utf8'),ticks,'scheduled work must cease');
const socket=net.createServer();await new Promise((resolve,reject)=>{socket.once('error',reject);socket.listen(port,'127.0.0.1',resolve);});await new Promise(resolve=>socket.close(resolve));
});