import { EventEmitter } from "node:events"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { PassThrough, Readable } from "node:stream"; import { gunzipSync } from "node:zlib"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { dumpPostgresToFile, PostgresDumpError, type SpawnLike } from "./postgres.js"; interface FakeChild extends EventEmitter { stdout: PassThrough; stderr: PassThrough; } function makeFakeChild(): FakeChild { const emitter = new EventEmitter() as FakeChild; emitter.stdout = new PassThrough(); emitter.stderr = new PassThrough(); return emitter; } let workDir: string; beforeEach(async () => { workDir = await mkdtemp(join(tmpdir(), "cli-pgdump-")); }); afterEach(async () => { await rm(workDir, { recursive: true, force: true }); }); describe("dumpPostgresToFile", () => { it("pipes pg_dump stdout through gzip into the target file and returns size+checksum", async () => { const child = makeFakeChild(); const spawnFn: SpawnLike = ((_cmd: string, args: readonly string[]) => { // sanity: the connection string flag must be at the end expect(args).toContain("--dbname"); expect(args[args.length - 1]).toBe("postgres://example/db"); queueMicrotask(() => { Readable.from(["PGDUMP_PAYLOAD_ABCDEF"]).pipe(child.stdout); child.stdout.once("end", () => { child.emit("close", 0); }); }); return child as unknown as ReturnType; }) as unknown as SpawnLike; const outPath = join(workDir, "dump.sql.gz"); const result = await dumpPostgresToFile({ connectionString: "postgres://example/db", outPath, spawnFn, }); expect(result.sizeBytes).toBeGreaterThan(0); expect(result.checksum.algorithm).toBe("sha256"); expect(result.checksum.value).toMatch(/^[a-f0-9]{64}$/u); const decompressed = gunzipSync(await readFile(outPath)).toString("utf8"); expect(decompressed).toBe("PGDUMP_PAYLOAD_ABCDEF"); }); it("throws PostgresDumpError with stderr when pg_dump exits non-zero", async () => { const child = makeFakeChild(); const spawnFn: SpawnLike = (() => { queueMicrotask(() => { child.stderr.write("FATAL: connection failed\n"); child.stderr.end(); child.stdout.end(); child.emit("close", 2); }); return child as unknown as ReturnType; }) as unknown as SpawnLike; await expect( dumpPostgresToFile({ connectionString: "postgres://bad/db", outPath: join(workDir, "dump.sql.gz"), spawnFn, }), ).rejects.toBeInstanceOf(PostgresDumpError); }); it("propagates spawn errors", async () => { const child = makeFakeChild(); const spawnFn: SpawnLike = (() => { queueMicrotask(() => { child.stdout.end(); child.emit("error", new Error("spawn ENOENT")); }); return child as unknown as ReturnType; }) as unknown as SpawnLike; await expect( dumpPostgresToFile({ connectionString: "postgres://example/db", outPath: join(workDir, "dump.sql.gz"), spawnFn, }), ).rejects.toThrow(/ENOENT/); }); });