|
| 1 | +import { assert, assertEquals } from '@std/assert'; |
| 2 | + |
| 3 | +const FIXTURE_PATH = 'tests/fixtures/signal_runtime_fixture.ts'; |
| 4 | +type ShutdownSignal = 'SIGINT' | 'SIGTERM'; |
| 5 | + |
| 6 | +const readStream = async (stream: ReadableStream<Uint8Array> | null) => { |
| 7 | + if (!stream) return ''; |
| 8 | + return await new Response(stream).text(); |
| 9 | +}; |
| 10 | + |
| 11 | +const readUntil = async ( |
| 12 | + reader: ReadableStreamDefaultReader<Uint8Array>, |
| 13 | + expected: string, |
| 14 | +) => { |
| 15 | + const decoder = new TextDecoder(); |
| 16 | + let output = ''; |
| 17 | + |
| 18 | + while (!output.includes(expected)) { |
| 19 | + const { done, value } = await reader.read(); |
| 20 | + if (done) break; |
| 21 | + output += decoder.decode(value, { stream: true }); |
| 22 | + } |
| 23 | + |
| 24 | + return output; |
| 25 | +}; |
| 26 | + |
| 27 | +const assertSignalShutdown = async (signal: ShutdownSignal) => { |
| 28 | + const child = new Deno.Command('/bin/sh', { |
| 29 | + args: ['-c', `exec deno run -P ${FIXTURE_PATH} --signal=${signal}`], |
| 30 | + stdout: 'piped', |
| 31 | + stderr: 'piped', |
| 32 | + }).spawn(); |
| 33 | + |
| 34 | + const reader = child.stdout!.getReader(); |
| 35 | + let stdout = await readUntil(reader, 'fixture-ready'); |
| 36 | + |
| 37 | + child.kill(signal); |
| 38 | + |
| 39 | + const status = await child.status; |
| 40 | + const remainder = await readStream(new ReadableStream({ |
| 41 | + async start(controller) { |
| 42 | + while (true) { |
| 43 | + const { done, value } = await reader.read(); |
| 44 | + if (done) break; |
| 45 | + controller.enqueue(value); |
| 46 | + } |
| 47 | + controller.close(); |
| 48 | + reader.releaseLock(); |
| 49 | + }, |
| 50 | + })); |
| 51 | + stdout += remainder; |
| 52 | + const stderr = await readStream(child.stderr); |
| 53 | + |
| 54 | + assertEquals(status.success, true, stderr); |
| 55 | + assert(stdout.includes(`received:${signal}`)); |
| 56 | + assert(stdout.includes('close-called')); |
| 57 | + assert(stdout.includes('cleanup-complete')); |
| 58 | +}; |
| 59 | + |
| 60 | +Deno.test('process handles SIGTERM and exits cleanly', async () => { |
| 61 | + await assertSignalShutdown('SIGTERM'); |
| 62 | +}); |
| 63 | + |
| 64 | +Deno.test('process handles SIGINT and exits cleanly', async () => { |
| 65 | + await assertSignalShutdown('SIGINT'); |
| 66 | +}); |
0 commit comments