diff --git a/TESTING.md b/TESTING.md index 5401fc600..bfab94436 100644 --- a/TESTING.md +++ b/TESTING.md @@ -85,6 +85,12 @@ app or directory that a test writes from scratch with `createPackageFixtureDir() `packageFixturePath()`, not inside a test directory or a package root: Vitest lists those directories, and an entry that comes and goes there reruns every cached test task. +Start every server that a test stops later, such as `vp dev`, `vp preview` or a built app, with +`spawnFixtureServer()` or `spawnTestServer()` rather than `spawn`. They run the server under +`test/server-supervisor.ts`, which stops its whole process tree when the test process exits, also +when the task runner or Vitest kills it with SIGKILL. A server left running would keep `vp run test` +waiting for it: every Vite+ process in a task's tree holds the task runner's IPC channel open. + For a leaf-module edit with known import-based consumers, Vitest's native related command is useful: ```sh diff --git a/packages/md/test/integration/invalid-frontmatter.test.ts b/packages/md/test/integration/invalid-frontmatter.test.ts index 92ae082fc..133823ad5 100644 --- a/packages/md/test/integration/invalid-frontmatter.test.ts +++ b/packages/md/test/integration/invalid-frontmatter.test.ts @@ -1,10 +1,11 @@ import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import spawn from 'cross-spawn'; +import type spawn from 'cross-spawn'; import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -38,11 +39,14 @@ describe('invalid frontmatter on the dev server', () => { } const server = await startServer((port) => { - child = spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { - cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], - env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, - }); + child = spawnTestServer( + 'vp', + ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: playground.root, + env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, + }, + ); return child; }, 30_000); base = server.base; diff --git a/packages/void/test/integration/astro.test.ts b/packages/void/test/integration/astro.test.ts index 7d9853558..0a6e139fd 100644 --- a/packages/void/test/integration/astro.test.ts +++ b/packages/void/test/integration/astro.test.ts @@ -13,12 +13,13 @@ import type { AddressInfo } from 'node:net'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { PGlite } from '@electric-sql/pglite'; -import spawn from 'cross-spawn'; +import type spawn from 'cross-spawn'; import { createServer } from 'pglite-server'; import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground, StartedServer } from '../../../../test/integration-helpers.ts'; @@ -47,7 +48,7 @@ describe('playground/astro dev', () => { const startDev = async () => { const server = await startServer((port) => { - child = spawn( + child = spawnTestServer( process.execPath, [ join(playground.root, 'node_modules/astro/bin/astro.mjs'), @@ -59,7 +60,6 @@ describe('playground/astro dev', () => { ], { cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ASTRO_DEV_BACKGROUND: 'false', @@ -172,7 +172,7 @@ export const onRequest = defineMiddleware((_context, next) => next()); function start(script: 'dev' | 'preview'): Promise { const root = playground.root; return startServer((port) => { - child = spawn( + child = spawnTestServer( process.execPath, [ join(root, 'node_modules/astro/bin/astro.mjs'), @@ -184,7 +184,6 @@ export const onRequest = defineMiddleware((_context, next) => next()); ], { cwd: root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ASTRO_DEV_BACKGROUND: 'false', @@ -478,10 +477,10 @@ export const GET = () => it('serves .env values from the Worker env and public values as Vite defines them', async () => { const server = await startServer( (port) => - spawn( + spawnTestServer( process.execPath, [astro(), 'preview', '--host', '127.0.0.1', '--port', String(port)], - { cwd: playground.root, stdio: ['ignore', 'pipe', 'pipe'], env: env() }, + { cwd: playground.root, env: env() }, ), 20_000, ); diff --git a/packages/void/test/integration/auth-schema-startup.test.ts b/packages/void/test/integration/auth-schema-startup.test.ts index 9e821222e..ee1d09983 100644 --- a/packages/void/test/integration/auth-schema-startup.test.ts +++ b/packages/void/test/integration/auth-schema-startup.test.ts @@ -1,11 +1,12 @@ import { execFileSync } from 'node:child_process'; import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import spawn from 'cross-spawn'; +import type spawn from 'cross-spawn'; import { afterEach, expect, it } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -119,11 +120,14 @@ it('starts a fresh Cloudflare app with auth table imports without running prepar freshAuthApp(); const server = await startServer( (port) => { - child = spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { - cwd: fixture.root, - stdio: ['ignore', 'pipe', 'pipe'], - env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, - }); + child = spawnTestServer( + 'vp', + ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: fixture.root, + env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, + }, + ); return child; }, 30_000, diff --git a/packages/void/test/integration/http-errors-playground-suite.ts b/packages/void/test/integration/http-errors-playground-suite.ts index 1587a827c..ed3155839 100644 --- a/packages/void/test/integration/http-errors-playground-suite.ts +++ b/packages/void/test/integration/http-errors-playground-suite.ts @@ -5,6 +5,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground, StartedServer } from '../../../../test/integration-helpers.ts'; @@ -150,13 +151,15 @@ function httpErrorsSuite(mode: HttpErrorsMode): void { server = await startServer( (port) => mode === 'dev' - ? spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { + ? spawnTestServer( + 'vp', + ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: playground.root, + }, + ) + : spawnTestServer(process.execPath, ['dist/ssr/index.js'], { cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], - }) - : spawn(process.execPath, ['dist/ssr/index.js'], { - cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port), NODE_ENV: 'production' }, }), 30_000, diff --git a/packages/void/test/integration/node-target.test.ts b/packages/void/test/integration/node-target.test.ts index 9c8bded9e..7254723d9 100644 --- a/packages/void/test/integration/node-target.test.ts +++ b/packages/void/test/integration/node-target.test.ts @@ -6,6 +6,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -23,10 +24,13 @@ describe('playground/node-app dev', () => { beforeAll(async () => { playground = createIsolatedPlayground(ROOT, 'playground/node-app'); const server = await startServer((port) => { - child = spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { - cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], - }); + child = spawnTestServer( + 'vp', + ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: playground.root, + }, + ); return child; }, 20_000); DEV_BASE = server.base; @@ -93,9 +97,8 @@ describe('playground/node-app build + production', () => { expect(build.status, `${build.stdout ?? ''}${build.stderr ?? ''}`).toBe(0); const server = await startServer((port) => { - child = spawn('node', ['dist/ssr/index.js'], { + child = spawnTestServer('node', ['dist/ssr/index.js'], { cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port) }, }); return child; diff --git a/packages/void/test/integration/nuxt.test.ts b/packages/void/test/integration/nuxt.test.ts index 486f943c9..1b0d4bf41 100644 --- a/packages/void/test/integration/nuxt.test.ts +++ b/packages/void/test/integration/nuxt.test.ts @@ -1,11 +1,12 @@ import { existsSync, readFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; -import spawn from 'cross-spawn'; +import type spawn from 'cross-spawn'; import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -37,14 +38,17 @@ describe( // URL under Vitest, so only the page body shows that the answer comes from this app. const server = await startServer( (port) => { - child = spawn('vp', ['run', 'dev', '--host', '127.0.0.1', '--port', String(port)], { - cwd: fixture.root, - stdio: ['ignore', 'pipe', 'pipe'], - env: { - ...process.env, - VOID_INSPECTOR_PORT: 'false', + child = spawnTestServer( + 'vp', + ['run', 'dev', '--host', '127.0.0.1', '--port', String(port)], + { + cwd: fixture.root, + env: { + ...process.env, + VOID_INSPECTOR_PORT: 'false', + }, }, - }); + ); return child; }, 30_000, diff --git a/packages/void/test/integration/page-errors-suite.ts b/packages/void/test/integration/page-errors-suite.ts index f5b4eabe8..9f40c98c9 100644 --- a/packages/void/test/integration/page-errors-suite.ts +++ b/packages/void/test/integration/page-errors-suite.ts @@ -9,13 +9,14 @@ import { readFileSync, } from 'node:fs'; import { join } from 'node:path'; -import spawn from 'cross-spawn'; +import type spawn from 'cross-spawn'; import type { Browser } from 'playwright'; import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -276,9 +277,8 @@ export const loader = defineHandler(c => { }); const server = await startServer( (port) => - (child = spawn(process.execPath, ['dist/ssr/index.js'], { + (child = spawnTestServer(process.execPath, ['dist/ssr/index.js'], { cwd: fixture.root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port) }, })), 30_000, @@ -604,12 +604,11 @@ export const loader = defineHandler(c => { write('public/download', 'Download bytes'); const dev = await startServer( (port) => - (child = spawn( + (child = spawnTestServer( 'vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { cwd: fixture.root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, NODE_ENV: 'development' }, }, )), @@ -646,12 +645,11 @@ export const loader = defineHandler(c => { ); const trailing = await startServer( (port) => - (child = spawn( + (child = spawnTestServer( 'vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { cwd: fixture.root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, NODE_ENV: 'development' }, }, )), diff --git a/packages/void/test/integration/pages-target-assets.test.ts b/packages/void/test/integration/pages-target-assets.test.ts index 5517b074f..2ba94565d 100644 --- a/packages/void/test/integration/pages-target-assets.test.ts +++ b/packages/void/test/integration/pages-target-assets.test.ts @@ -7,6 +7,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -77,9 +78,8 @@ export default function Home() { writeFileSync(join(root, 'public/health.txt'), 'public asset'); execFileSync('vp', ['build'], { cwd: root, stdio: 'pipe' }); const server = await startServer((port) => { - child = spawn(command, [...args, 'dist/ssr/index.js'], { + child = spawnTestServer(command, [...args, 'dist/ssr/index.js'], { cwd: root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port) }, }); return child; @@ -132,9 +132,8 @@ export default function Home() { mkdirSync(elsewhere); const relocated = await startServer( (port) => - spawn(command, [...args, join(root, 'dist/ssr/index.js')], { + spawnTestServer(command, [...args, join(root, 'dist/ssr/index.js')], { cwd: elsewhere, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port) }, }), 20_000, @@ -196,9 +195,8 @@ ${serve} try { const server = await startServer( (port) => - spawn(command, [...args, 'supplied-server.mjs'], { + spawnTestServer(command, [...args, 'supplied-server.mjs'], { cwd: root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port) }, }), 20_000, diff --git a/packages/void/test/integration/react-router.test.ts b/packages/void/test/integration/react-router.test.ts index e00ace659..1a6539723 100644 --- a/packages/void/test/integration/react-router.test.ts +++ b/packages/void/test/integration/react-router.test.ts @@ -1,12 +1,13 @@ import { execFileSync } from 'node:child_process'; import { existsSync, globSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import spawn from 'cross-spawn'; +import type spawn from 'cross-spawn'; import { afterAll, beforeAll, describe, expect, it, onTestFinished } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, spawnFixtureServer, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground, StartedServer } from '../../../../test/integration-helpers.ts'; @@ -156,11 +157,14 @@ export default { } const server = await startServer( (port) => - spawn('vp', [script, '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { - cwd: fixture.root, - stdio: ['ignore', 'pipe', 'pipe'], - env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, - }), + spawnTestServer( + 'vp', + [script, '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: fixture.root, + env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, + }, + ), 30_000, ); onTestFinished(() => killChild(server.child)); @@ -266,11 +270,14 @@ export async function loader() { function start(script: 'dev' | 'preview'): Promise { return startServer((port) => { - child = spawn('vp', [script, '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { - cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], - env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, - }); + child = spawnTestServer( + 'vp', + [script, '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: playground.root, + env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, + }, + ); return child; }, 30_000); } diff --git a/packages/void/test/integration/server-auth-errors-suite.ts b/packages/void/test/integration/server-auth-errors-suite.ts index 5c621a0f3..82dbc23b7 100644 --- a/packages/void/test/integration/server-auth-errors-suite.ts +++ b/packages/void/test/integration/server-auth-errors-suite.ts @@ -1,11 +1,11 @@ import { join } from 'node:path'; -import spawn from 'cross-spawn'; import type { Browser, BrowserContext, Page, Response } from 'playwright'; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vite-plus/test'; import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground, StartedServer } from '../../../../test/integration-helpers.ts'; @@ -44,11 +44,14 @@ beforeAll(async () => { playground = createIsolatedPlayground(ROOT, PLAYGROUND); server = await startServer( (port) => - spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { - cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], - env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, - }), + spawnTestServer( + 'vp', + ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: playground.root, + env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, + }, + ), 60_000, { expectStatus: 200, expectBody: 'Server Auth Errors Example' }, ); diff --git a/packages/void/test/integration/spa-middleware-auth.test.ts b/packages/void/test/integration/spa-middleware-auth.test.ts index 85b3e4d7a..93a9755df 100644 --- a/packages/void/test/integration/spa-middleware-auth.test.ts +++ b/packages/void/test/integration/spa-middleware-auth.test.ts @@ -1,11 +1,12 @@ import { execSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import spawn from 'cross-spawn'; +import type spawn from 'cross-spawn'; import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -111,14 +112,17 @@ function writeProtectedAsset(): void { async function startSpaDevServer(): Promise { const server = await startServer((port) => { - child = spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { - cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], - env: { - ...process.env, - VOID_INSPECTOR_PORT: 'false', + child = spawnTestServer( + 'vp', + ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: playground.root, + env: { + ...process.env, + VOID_INSPECTOR_PORT: 'false', + }, }, - }); + ); return child; }, 30_000); return server.base; @@ -126,12 +130,11 @@ async function startSpaDevServer(): Promise { async function startSpaPreviewServer(): Promise { const server = await startServer((port) => { - child = spawn( + child = spawnTestServer( 'vp', ['preview', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, VOID_INSPECTOR_PORT: 'false' }, }, ); diff --git a/packages/void/test/integration/sveltekit.test.ts b/packages/void/test/integration/sveltekit.test.ts index 007927ee9..72704c51e 100644 --- a/packages/void/test/integration/sveltekit.test.ts +++ b/packages/void/test/integration/sveltekit.test.ts @@ -6,6 +6,7 @@ import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -83,7 +84,7 @@ export function checkSchema() { // even when the smart runner puts the workspace's binaries first on PATH. const server = await startServer( (port) => { - child = spawn( + child = spawnTestServer( process.execPath, [ join(pg, 'node_modules/vite-plus/bin/vp'), @@ -96,7 +97,6 @@ export function checkSchema() { ], { cwd: pg, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, VOID_INSPECTOR_PORT: 'false', diff --git a/packages/void/test/integration/trailing-slash.test.ts b/packages/void/test/integration/trailing-slash.test.ts index 8009f0836..93b872176 100644 --- a/packages/void/test/integration/trailing-slash.test.ts +++ b/packages/void/test/integration/trailing-slash.test.ts @@ -1,11 +1,12 @@ import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import spawn from 'cross-spawn'; +import type spawn from 'cross-spawn'; import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -64,7 +65,7 @@ export const action = (c) => c.json({ value: c.req.param(${JSON.stringify(name)} for (const mode of ['dev', 'production']) { const server = await startServer((port) => { const nodeProduction = target === 'node' && mode === 'production'; - const child = spawn( + const child = spawnTestServer( nodeProduction ? process.execPath : 'vp', nodeProduction ? ['dist/ssr/index.js'] @@ -78,7 +79,6 @@ export const action = (c) => c.json({ value: c.req.param(${JSON.stringify(name)} ], { cwd: fixture.root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port) }, }, ); diff --git a/packages/void/test/integration/tsx-server.test.ts b/packages/void/test/integration/tsx-server.test.ts index dd276b57d..c2dd35b74 100644 --- a/packages/void/test/integration/tsx-server.test.ts +++ b/packages/void/test/integration/tsx-server.test.ts @@ -5,6 +5,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -103,10 +104,13 @@ export const action = defineHandler(c => c.text(${JSON.stringify(text)}));`, const dev = await startServer( (port) => - spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { - cwd: root, - stdio: ['ignore', 'pipe', 'pipe'], - }), + spawnTestServer( + 'vp', + ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: root, + }, + ), 20_000, ); servers.push(dev.child); @@ -123,9 +127,8 @@ export const action = defineHandler(c => c.text(${JSON.stringify(text)}));`, expect(build.status, `${build.stdout ?? ''}${build.stderr ?? ''}`).toBe(0); const prod = await startServer( (port) => - spawn(process.execPath, ['dist/ssr/index.js'], { + spawnTestServer(process.execPath, ['dist/ssr/index.js'], { cwd: root, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, NODE_ENV: 'production', PORT: String(port) }, }), 20_000, diff --git a/packages/void/test/integration/vinext-app.test.ts b/packages/void/test/integration/vinext-app.test.ts index 712b84459..4c69c0008 100644 --- a/packages/void/test/integration/vinext-app.test.ts +++ b/packages/void/test/integration/vinext-app.test.ts @@ -6,6 +6,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vite-plus/ import { createIsolatedPlayground, killChild, + spawnTestServer, startServer, } from '../../../../test/integration-helpers.ts'; import type { IsolatedPlayground } from '../../../../test/integration-helpers.ts'; @@ -22,14 +23,17 @@ describe('playground/vinext-app dev', () => { beforeAll(async () => { playground = createIsolatedPlayground(ROOT, PLAYGROUND); const server = await startServer((port) => { - child = spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { - cwd: playground.root, - stdio: ['ignore', 'pipe', 'pipe'], - env: { - ...process.env, - VOID_INSPECTOR_PORT: 'false', + child = spawnTestServer( + 'vp', + ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], + { + cwd: playground.root, + env: { + ...process.env, + VOID_INSPECTOR_PORT: 'false', + }, }, - }); + ); return child; }, 30_000); DEV_BASE = server.base; diff --git a/packages/void/test/unit/test-server-supervisor.test.ts b/packages/void/test/unit/test-server-supervisor.test.ts new file mode 100644 index 000000000..268ac3c64 --- /dev/null +++ b/packages/void/test/unit/test-server-supervisor.test.ts @@ -0,0 +1,98 @@ +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { afterEach, beforeEach, describe, expect, it } from 'vite-plus/test'; +import { spawnTestServer } from '../../../../test/integration-helpers.ts'; + +const helpers = new URL('../../../../test/integration-helpers.ts', import.meta.url).href; + +// A server that, like `vite.js dev` and workerd, ignores SIGTERM, and starts a child that does too. +const server = ` +const { spawn } = require('node:child_process'); +process.on('SIGTERM', () => {}); +const child = spawn(process.execPath, ['-e', "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)"], { stdio: 'ignore' }); +console.log(process.pid + " " + child.pid); +setInterval(() => {}, 1000); +`; + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function firstLine(stream: NodeJS.ReadableStream): Promise { + let output = ''; + for await (const chunk of stream) { + output += String(chunk); + if (output.includes('\n')) { + return output.slice(0, output.indexOf('\n')); + } + } + throw new Error(`Stream ended before a line: ${output}`); +} + +describe.skipIf(process.platform === 'win32')('spawnTestServer', () => { + let dir: string; + const pids: Array = []; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'void-server-supervisor-')); + }); + + afterEach(() => { + for (const pid of pids.splice(0).filter(isAlive)) { + process.kill(pid, 'SIGKILL'); + } + rmSync(dir, { recursive: true, force: true }); + }); + + it('stops the server tree when the test process is killed', async () => { + writeFileSync(join(dir, 'server.cjs'), server); + writeFileSync( + join(dir, 'test-process.mjs'), + `import { spawnTestServer } from ${JSON.stringify(helpers)}; +const child = spawnTestServer(process.execPath, ['server.cjs']); +child.stdout.once('data', (chunk) => process.stdout.write(child.pid + ' ' + chunk)); +setInterval(() => {}, 1000); +`, + ); + const testProcess = spawn(process.execPath, ['test-process.mjs'], { cwd: dir, stdio: 'pipe' }); + pids.push(testProcess.pid!); + const serverPids = (await firstLine(testProcess.stdout)).split(' ').map(Number); + pids.push(...serverPids); + expect(serverPids).toHaveLength(3); + expect(serverPids.every(Number.isInteger)).toBe(true); + expect(serverPids.every(isAlive)).toBe(true); + + testProcess.kill('SIGKILL'); + for (const deadline = Date.now() + 10_000; Date.now() < deadline; await delay(50)) { + if (!serverPids.some(isAlive)) { + break; + } + } + expect(serverPids.filter(isAlive)).toEqual([]); + }, 15_000); + + it("passes on the server's exit code once the processes it left behind are stopped", async () => { + const child = spawnTestServer(process.execPath, [ + '-e', + `const child = require('node:child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); +console.log(String(child.pid)); +process.exit(3);`, + ]); + const exited = once(child, 'exit'); + const leftBehind = Number(await firstLine(child.stdout)); + pids.push(leftBehind); + expect(Number.isInteger(leftBehind)).toBe(true); + const [code] = await exited; + expect(code).toBe(3); + expect(isAlive(leftBehind)).toBe(false); + }); +}); diff --git a/test/integration-helpers.ts b/test/integration-helpers.ts index f9c5b0999..2b16cc268 100644 --- a/test/integration-helpers.ts +++ b/test/integration-helpers.ts @@ -1,5 +1,8 @@ -import { execSync } from 'node:child_process'; -import type { spawn } from 'node:child_process'; +// Platform scripts import this file into a program that also loads Workers types, which declare +// `process` as `any`. Load the Node types first, so that `process` keeps its Node type there. +/// +import { execSync, spawn } from 'node:child_process'; +import type { ChildProcessWithoutNullStreams, SpawnOptions } from 'node:child_process'; import { once } from 'node:events'; import { cpSync, @@ -17,8 +20,8 @@ import { createServer } from 'node:net'; import type { AddressInfo } from 'node:net'; import { basename, join, relative } from 'node:path/posix'; import { setTimeout as delay } from 'node:timers/promises'; +import { fileURLToPath } from 'node:url'; import { stripVTControlCharacters } from 'node:util'; -import crossSpawn from 'cross-spawn'; export { createPackageFixtureDir } from './fixture-dir.ts'; @@ -255,17 +258,41 @@ export function spawnFixtureServer( port: number, env: NodeJS.ProcessEnv = {}, ): ReturnType { - return crossSpawn( + return spawnTestServer( 'vp', ['run', script, '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { cwd: fixtureRoot, - stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, VOID_INSPECTOR_PORT: 'false', ...env }, }, ); } +const SERVER_SUPERVISOR = fileURLToPath(new URL('server-supervisor.ts', import.meta.url)); + +/** + * Spawns a server that a test starts and stops, such as `vp dev` or a built app. Use it instead + * of `spawn` for every process that keeps running until the test stops it. + * + * The server runs under `server-supervisor.ts`, which stops the server's whole process tree when + * the test process is gone, even after SIGKILL. Otherwise the server would keep running, and a + * Vite+ process in its tree would keep `vp run test` waiting for it. The server's stdin is + * ignored and its stdout and stderr are piped to the test process, never inherited. + */ +export function spawnTestServer( + command: string, + args: ReadonlyArray, + options: Omit = {}, +): ChildProcessWithoutNullStreams { + return spawn(process.execPath, [SERVER_SUPERVISOR, command, ...args], { + ...options, + stdio: 'pipe', + // Outside the test's process group: when a signal kills the whole group, the supervisor + // survives it and stops the server. + detached: process.platform !== 'win32', + }); +} + export async function waitForServer( url: string, timeoutMs: number, diff --git a/test/server-supervisor.ts b/test/server-supervisor.ts new file mode 100644 index 000000000..13efb33a6 --- /dev/null +++ b/test/server-supervisor.ts @@ -0,0 +1,116 @@ +/** + * Runs a test server and stops its whole process tree once the test process that started it is + * gone. Start it through `spawnTestServer()` in `integration-helpers.ts`: + * + * node test/server-supervisor.ts [...args] + * + * A test process can die without running its teardown: the task runner and Vitest's watchdog + * stop workers with SIGKILL. The server would then keep running, and a Vite+ process in its tree + * would keep the task runner waiting for it. The test process holds the write end of this + * process's stdin, so the end of stdin means that it is gone. The server runs in its own process + * group (on Windows, as a process tree), which is stopped as a whole on the end of stdin, on + * SIGTERM, SIGINT or SIGHUP, and when the server exits. This process exits once the group is + * empty, with the server's exit code or signal. + */ +import type { ChildProcess } from 'node:child_process'; +import { execFileSync } from 'node:child_process'; +import { setTimeout as delay } from 'node:timers/promises'; +import crossSpawn from 'cross-spawn'; + +/** Time the server's processes get to exit after SIGTERM before they are killed. */ +const STOP_GRACE_MS = 3000; +const STOP_SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const; +const isWindows = process.platform === 'win32'; + +const [command, ...args] = process.argv.slice(2); +if (!command) { + console.error('Usage: node server-supervisor.ts [...args]'); + process.exit(2); +} + +const server: ChildProcess = crossSpawn(command, args, { + stdio: ['ignore', 'inherit', 'inherit'], + detached: !isWindows, +}); + +function serverExited(): boolean { + return server.exitCode !== null || server.signalCode !== null; +} + +/** Whether a process of the server's group is still running. */ +function groupRunning(): boolean { + if (isWindows || server.pid === undefined) { + return !serverExited(); + } + try { + process.kill(-server.pid, 0); + return true; + } catch { + return false; + } +} + +function signalGroup(signal: 'SIGTERM' | 'SIGKILL'): void { + if (server.pid === undefined) { + return; + } + try { + if (isWindows) { + // Windows has no process groups or SIGTERM: end the tree while the server still roots it. + if (!serverExited()) { + execFileSync('taskkill', ['/pid', String(server.pid), '/T', '/F'], { stdio: 'ignore' }); + } + } else { + process.kill(-server.pid, signal); + } + } catch { + // The group is already empty. + } +} + +async function groupStopped(timeoutMs: number): Promise { + for (const deadline = Date.now() + timeoutMs; Date.now() < deadline; await delay(25)) { + if (!groupRunning()) { + return true; + } + } + return !groupRunning(); +} + +let stopping: Promise | undefined; + +/** Stops every process of the server's group, also the ones that ignore SIGTERM. */ +function stopGroup(): Promise { + stopping ??= (async () => { + signalGroup('SIGTERM'); + if (!(await groupStopped(STOP_GRACE_MS))) { + signalGroup('SIGKILL'); + await groupStopped(STOP_GRACE_MS); + } + })(); + return stopping; +} + +for (const signal of STOP_SIGNALS) { + process.on(signal, () => void stopGroup()); +} +process.stdin.on('data', () => {}); +process.stdin.on('end', () => void stopGroup()); +process.stdin.on('error', () => void stopGroup()); + +server.on('error', (error) => { + console.error(`Could not start ${command}: ${error.message}`); + process.exit(127); +}); + +server.on('exit', (code, signal) => { + void stopGroup().then(() => { + if (signal) { + for (const stopSignal of STOP_SIGNALS) { + process.removeAllListeners(stopSignal); + } + process.kill(process.pid, signal); + } + process.exit(code ?? 1); + }); +});