diff --git a/server/tests/helpers/fake-pg-tools.ts b/server/tests/helpers/fake-pg-tools.ts new file mode 100644 index 000000000..bb14098f5 --- /dev/null +++ b/server/tests/helpers/fake-pg-tools.ts @@ -0,0 +1,124 @@ +/** + * Stand-in PostgreSQL client tools (pg_dump, pg_restore and psql) for the unit + * tests of the Postgres backup and restore. Each is an executable shell script + * in a bin directory, which the test hands TREK as its client-tool directory. + * + * A stand-in writes its argv and its PG* environment to `/.log` + * before anything else it does, so readToolCall() says what the tool was given. + * The log holds the last call. What a call does is a list of shell snippets, + * run in order: the builders below name what a test sets up (answersSchema, + * writesFile, failsWith, ...), so a test reads as the scenario it describes. + * Output files are found by their `--file=` argument, not by position. + */ +import { chmodSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; + +export type PgToolName = 'pg_dump' | 'pg_restore' | 'psql'; + +export interface FakeToolOptions { + /** What `--version` answers after "PostgreSQL". Defaults to 17.11. */ + version?: string; + /** Shell fragments run after the call is logged, in order. */ + snippets?: readonly string[]; +} + +/** What a stand-in was called with: its arguments, and its PG* environment. */ +export interface ToolCall { + args: string[]; + env: Record; +} + +/** A value as one single-quoted shell word. */ +function shellWord(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'`; +} + +/** Answers a call whose arguments contain `pattern` with `text`, and ends the call. */ +export function printsWhen(pattern: string, text: string): string { + return `case "$*" in *${pattern}*) printf '%s' ${shellWord(text)}; exit 0;; esac`; +} + +/** psql's current-schema answer: the schema's name, and its quote_ident spelling, as pgCurrentSchema reads them. */ +export function answersSchema(name = 'public', quoted = name): string { + return printsWhen('quote_ident', `${name}\t${quoted}\n`); +} + +/** psql's table listing, one name per line, as pgTableNames reads it. */ +export function answersTables(names: readonly string[]): string { + return printsWhen('table_name', names.map((name) => `${name}\n`).join('')); +} + +/** Writes `content` to the output file the call names with `--file=`. */ +export function writesFile(content: string): string { + return `printf '%s' ${shellWord(content)} > "$(fake_file_target "$@")"`; +} + +/** Writes the start of a restore script that restricts psql (CVE-2025-8714) and creates TREK's migration table. */ +export function writesRestrictedScript(table = 'public.mikro_orm_migrations'): string { + return writesFile(`\\restrict k1\nCREATE TABLE ${table} (\n);\n`); +} + +/** Answers a `--data-only` call with the COPY block of `mikro_orm_migrations`, one row per name. */ +export function listsMigrations(names: readonly string[]): string { + const rows = names.map((name, i) => `${i + 1}\t${name}\tx\n`).join(''); + const copy = `COPY public.mikro_orm_migrations (id, name, executed_at) FROM stdin;\n${rows}\\.\n`; + return `case "$*" in *--data-only*) printf '%s' ${shellWord(copy)}; exit 0;; esac`; +} + +/** Fails the way a tool that cannot connect does: the message on stderr, then a non-zero exit. */ +export function failsWith(message: string, exitCode = 1): string { + return `printf '%s\\n' ${shellWord(message)} >&2; exit ${exitCode}`; +} + +/** Creates `file`: a marker that the tool ran. */ +export function touches(file: string): string { + return `touch ${shellWord(file)}`; +} + +/** Copies the `--file=` output whose path ends with `suffix` to `destination`, so a test can read a work file the tool has since removed. */ +export function copiesFileEndingWith(suffix: string, destination: string): string { + return `for a in "$@"; do case "$a" in --file=*${suffix}) cp "\${a#--file=}" ${shellWord(destination)};; esac; done`; +} + +/** The function every stand-in uses to find its `--file=` argument, wherever it sits. */ +const FILE_TARGET_FUNCTION = + 'fake_file_target() { for a in "$@"; do case "$a" in --file=*) printf \'%s\' "${a#--file=}";; esac; done; }'; + +/** + * Installs the stand-in `name` in `bin` and returns the path of its call log. + * The script is executable and runs by its absolute path, as TREK runs it. + */ +export function installFakeTool(bin: string, name: PgToolName, options: FakeToolOptions = {}): string { + const { version = '17.11', snippets = [] } = options; + const log = path.join(bin, `${name}.log`); + const script = [ + '#!/bin/sh', + FILE_TARGET_FUNCTION, + `[ "$1" = --version ] && { echo '${name} (PostgreSQL) ${version} (Debian)'; exit 0; }`, + `printf '%s\\n' "$@" > ${shellWord(log)}`, + `env | grep '^PG' | sort >> ${shellWord(log)}`, + ...snippets, + '', + ].join('\n'); + writeFileSync(path.join(bin, name), script); + chmodSync(path.join(bin, name), 0o755); + return log; +} + +/** What the stand-in logged last: its arguments, and the PG* variables it was run with. */ +export function readToolCall(log: string): ToolCall { + const lines = readFileSync(log, 'utf8') + .split('\n') + .filter((line) => line !== ''); + const env: Record = {}; + for (const line of lines.filter((line) => line.startsWith('PG'))) { + const eq = line.indexOf('='); + env[line.slice(0, eq)] = line.slice(eq + 1); + } + return { args: lines.filter((line) => !line.startsWith('PG')), env }; +} + +/** Every argument that starts with `flag`, with the flag removed (`--file=` gives the file paths). */ +export function flagValues(args: readonly string[], flag: string): string[] { + return args.filter((arg) => arg.startsWith(flag)).map((arg) => arg.slice(flag.length)); +} diff --git a/server/tests/unit/db/engine/postgres/pg-tools.test.ts b/server/tests/unit/db/engine/postgres/pg-tools.test.ts index d8f20a8d9..8f3a3f0e1 100644 --- a/server/tests/unit/db/engine/postgres/pg-tools.test.ts +++ b/server/tests/unit/db/engine/postgres/pg-tools.test.ts @@ -1,79 +1,41 @@ /** - * The Postgres client tools (src/db/engine/postgres/pg-tools.ts), run against - * stand-in pg_dump, pg_restore and psql scripts in a temp directory: the exact - * arguments and environment each call hands the binary, the password kept out - * of the arguments, the files a dump and a restore leave behind, and the - * refusal when a tool is missing. The real tools against a real database are + * The Postgres client tools (src/db/engine/postgres/pg-tools.ts, with + * pg-process.ts and restore-safety.ts), run against stand-in pg_dump, + * pg_restore and psql scripts (tests/helpers/fake-pg-tools.ts): the arguments + * and environment each call hands the binary, the password kept out of the + * arguments, the files a dump and a restore leave behind, and the refusal when + * a tool is missing or too old. The real tools against a real database are * exercised by the Postgres lane. */ -import { PgToolMissingError, pgConnectionEnv, resolvePgTool } from '../../../../../src/db/engine/postgres/pg-process'; +import { pgConnectionEnv, PgToolMissingError, resolvePgTool } from '../../../../../src/db/engine/postgres/pg-process'; import { pgDump, pgDumpMigrations, pgRestore } from '../../../../../src/db/engine/postgres/pg-tools'; import { hasRestrictFix } from '../../../../../src/db/engine/postgres/restore-safety'; +import { + answersSchema, + copiesFileEndingWith, + failsWith, + flagValues, + installFakeTool, + listsMigrations, + printsWhen, + readToolCall, + touches, + writesFile, + writesRestrictedScript, +} from '../../../../helpers/fake-pg-tools'; -import fs, { - chmodSync, - existsSync, - mkdtempSync, - readdirSync, - readFileSync, - rmSync, - statSync, - writeFileSync, -} from 'node:fs'; -import { tmpdir } from 'node:os'; +import fs, { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import os, { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const URL_WITH_SECRET = 'postgresql://trek:s3cr%40t@db.example:6543/trek_db?sslmode=require'; +/** The restore's session settings, which psql gets through PGOPTIONS. */ +const RESTORE_OPTIONS = '-c lock_timeout=60s -c client_min_messages=warning'; let bin: string; let out: string; -/** pg_restore writing its --file (the fourth argument) as 17.6+ does: opened with a \\restrict line. */ -const WRITES_RESTRICTED_SCRIPT = - "printf '%s\\n' '\\restrict k1' 'CREATE TABLE public.mikro_orm_migrations (' ');' > \"${4#--file=}\""; -/** What psql answers to the current-schema query: the name, a tab, the name as quote_ident writes it. */ -const PUBLIC_SCHEMA = 'public\tpublic'; - -interface FakeOptions { - stdout?: string; - stderr?: string; - exitCode?: number; - /** Extra shell the tool runs before it exits. */ - body?: string; - /** What `--version` answers. */ - version?: string; -} - -/** A stand-in tool that records its arguments and libpq environment, then prints `stdout`. */ -function fakeTool( - name: string, - { stdout = '', stderr = '', exitCode = 0, body = '', version = '17.11' }: FakeOptions = {}, -): string { - const log = path.join(bin, `${name}.log`); - writeFileSync( - path.join(bin, name), - [ - '#!/bin/sh', - `[ "$1" = --version ] && { echo '${name} (PostgreSQL) ${version} (Debian)'; exit 0; }`, - `printf '%s\\n' "$@" > '${log}'`, - `env | grep '^PG' | sort >> '${log}'`, - body, - `printf '%s' '${stdout}'`, - `printf '%s' '${stderr}' >&2`, - `exit ${exitCode}`, - '', - ].join('\n'), - ); - chmodSync(path.join(bin, name), 0o755); - return log; -} - -const argsOf = (log: string): string[] => - readFileSync(log, 'utf8') - .split('\n') - .filter((line) => !line.startsWith('PG')); - beforeEach(() => { bin = mkdtempSync(path.join(tmpdir(), 'trek-pg-bin-')); out = mkdtempSync(path.join(tmpdir(), 'trek-pg-out-')); @@ -85,7 +47,7 @@ afterEach(() => { describe('pg-tools', () => { it('PGTOOLS-001: finds a tool by absolute path in the configured directory, and nowhere else', () => { - fakeTool('pg_dump'); + installFakeTool(bin, 'pg_dump'); writeFileSync(path.join(bin, 'psql'), 'not executable'); expect(resolvePgTool('pg_dump', bin)).toBe(path.join(bin, 'pg_dump')); expect(resolvePgTool('pg_restore', bin)).toBeNull(); @@ -122,60 +84,70 @@ describe('pg-tools', () => { }); it('PGTOOLS-004: pg_dump writes a private custom-format dump beside the target and renames it into place', async () => { - fakeTool('psql', { stdout: PUBLIC_SCHEMA }); - const log = fakeTool('pg_dump', { body: 'printf dump >> "${4#--file=}"' }); + installFakeTool(bin, 'psql', { snippets: [answersSchema()] }); + const log = installFakeTool(bin, 'pg_dump', { snippets: [writesFile('dump')] }); const target = path.join(out, 'x.pgdump'); await pgDump(URL_WITH_SECRET, target, bin); - expect(argsOf(log).slice(0, 5)).toEqual([ - '--format=custom', - '--no-owner', - '--no-privileges', - `--file=${target}.partial`, - '--schema="public"', - ]); - expect(readFileSync(log, 'utf8')).toContain('PGPASSWORD=s3cr@t'); - expect(argsOf(log).join(' ')).not.toContain('s3cr'); + + const call = readToolCall(log); + expect(call.args).toHaveLength(5); + expect(call.args).toEqual( + expect.arrayContaining([ + '--format=custom', + '--no-owner', + '--no-privileges', + `--file=${target}.partial`, + '--schema="public"', + ]), + ); + expect(call.env.PGPASSWORD).toBe('s3cr@t'); + expect(call.args.join(' ')).not.toContain('s3cr'); expect(readFileSync(target, 'utf8')).toBe('dump'); expect(statSync(target).mode & 0o777).toBe(0o600); expect(readdirSync(out)).toEqual(['x.pgdump']); }); it('PGTOOLS-005: a restore clears the schema and loads the script in one psql transaction, then removes its work files', async () => { - const source = path.join(out, 'in.pgdump'); - const restoreLog = fakeTool('pg_restore', { body: WRITES_RESTRICTED_SCRIPT }); - const psqlLog = fakeTool('psql', { - stdout: PUBLIC_SCHEMA, - body: `[ -n "$6" ] && cp "\${6#--file=}" '${path.join(bin, 'clear.sql')}'`, + const clearCopy = path.join(bin, 'clear.sql'); + const restoreLog = installFakeTool(bin, 'pg_restore', { snippets: [writesRestrictedScript()] }); + const psqlLog = installFakeTool(bin, 'psql', { + snippets: [answersSchema(), copiesFileEndingWith('clear-schema.sql', clearCopy)], }); + const source = path.join(out, 'in.pgdump'); await pgRestore(URL_WITH_SECRET, source, bin); - const restoreArgs = argsOf(restoreLog); - expect(restoreArgs.slice(0, 3)).toEqual(['--no-owner', '--no-privileges', '--schema=public']); - expect(restoreArgs[3]).toMatch(/^--file=.*\.pg-restore-[^/]+\/restore\.sql$/); - expect(restoreArgs.slice(4, 6)).toEqual(['--', source]); - expect(readFileSync(restoreLog, 'utf8')).not.toContain('PGPASSWORD'); + const restore = readToolCall(restoreLog); + expect(restore.args).toEqual(expect.arrayContaining(['--no-owner', '--no-privileges', '--schema=public'])); + const [restoreScript] = flagValues(restore.args, '--file='); + expect(restoreScript).toMatch(/\.pg-restore-[^/]+\/restore\.sql$/); + expect(restore.args.slice(-2)).toEqual(['--', source]); + expect(restore.env).toEqual({}); - const psqlArgs = argsOf(psqlLog); - expect(psqlArgs.slice(0, 5)).toEqual([ - '--no-psqlrc', - '--quiet', - '--single-transaction', - '--set=ON_ERROR_STOP=1', - '--output=/dev/null', - ]); - expect(psqlArgs[5]).toMatch(/clear-schema\.sql$/); - expect(psqlArgs[6]).toBe(restoreArgs[3]); - expect(readFileSync(psqlLog, 'utf8')).toContain('PGOPTIONS=-c lock_timeout=60s -c client_min_messages=warning'); - expect(readFileSync(path.join(bin, 'clear.sql'), 'utf8')).toMatch(/DROP %s IF EXISTS %s CASCADE/); + const psql = readToolCall(psqlLog); + expect(psql.args).toEqual( + expect.arrayContaining([ + '--no-psqlrc', + '--quiet', + '--single-transaction', + '--set=ON_ERROR_STOP=1', + `--output=${os.devNull}`, + ]), + ); + // Order is the point here: the schema is cleared before the script loads. + const [clearFile, loadFile] = flagValues(psql.args, '--file='); + expect(clearFile).toMatch(/clear-schema\.sql$/); + expect(loadFile).toBe(restoreScript); + expect(psql.env.PGOPTIONS).toBe(RESTORE_OPTIONS); + expect(readFileSync(clearCopy, 'utf8')).toMatch(/DROP %s IF EXISTS %s CASCADE/); expect(readdirSync(out)).toEqual([]); }); it('PGTOOLS-005b: the restore script is checked line by line, so its COPY data is never read whole', async () => { const source = path.join(out, 'in.pgdump'); - fakeTool('pg_restore', { - body: `printf '%s\\n' '\\restrict k1' 'CREATE TABLE public.mikro_orm_migrations (' > "\${4#--file=}"; seq 1 200000 >> "\${4#--file=}"`, + installFakeTool(bin, 'pg_restore', { + snippets: [writesRestrictedScript(), 'seq 1 200000 >> "$(fake_file_target "$@")"'], }); - fakeTool('psql', { stdout: PUBLIC_SCHEMA }); + installFakeTool(bin, 'psql', { snippets: [answersSchema()] }); const readWhole = vi.spyOn(fs, 'readFileSync'); try { await pgRestore(URL_WITH_SECRET, source, bin); @@ -186,67 +158,69 @@ describe('pg-tools', () => { }); it("PGTOOLS-006: reads the dump's recorded migrations from its COPY block, and none from a dump without them", async () => { - const copy = [ - 'SET statement_timeout = 0;', - 'COPY public.mikro_orm_migrations (id, name, executed_at) FROM stdin;', - '1\tMigration20200101000000_baseline_schema\t2026-01-01 00:00:00+00', - '2\tMigration20200101000100_second\t2026-01-01 00:00:00+00', - '\\.', - '', - ].join('\n'); - const log = fakeTool('pg_restore', { stdout: copy }); + const log = installFakeTool(bin, 'pg_restore', { + snippets: [listsMigrations(['Migration20200101000000_baseline_schema', 'Migration20200101000100_second'])], + }); await expect(pgDumpMigrations('/data/in.pgdump', bin)).resolves.toEqual([ 'Migration20200101000000_baseline_schema', 'Migration20200101000100_second', ]); - expect(argsOf(log).slice(0, 5)).toEqual([ - '--data-only', - '--table=mikro_orm_migrations', - '--file=-', - '--', - '/data/in.pgdump', - ]); - fakeTool('pg_restore', { stdout: 'SET statement_timeout = 0;\n' }); + const call = readToolCall(log); + expect(call.args).toEqual(expect.arrayContaining(['--data-only', '--table=mikro_orm_migrations', '--file=-'])); + expect(call.args.slice(-2)).toEqual(['--', '/data/in.pgdump']); + + installFakeTool(bin, 'pg_restore', { snippets: [printsWhen('--data-only', 'SET statement_timeout = 0;\n')] }); await expect(pgDumpMigrations('/data/in.pgdump', bin)).resolves.toEqual([]); }); - it('PGTOOLS-007: a failing tool reports its own message without the lines that quote SQL or rows, and leaves no file', async () => { - fakeTool('psql', { stdout: PUBLIC_SCHEMA }); - fakeTool('pg_dump', { - exitCode: 1, + it.each([ + { + id: 'PGTOOLS-007a', stderr: 'pg_dump: error: query failed\nCommand was: SELECT secret_row\nDETAIL: Key (email)=(a@b.c)\n', - }); - const target = path.join(out, 'x.pgdump'); - await expect(pgDump(URL_WITH_SECRET, target, bin)).rejects.toThrow( - /^pg_dump failed: pg_dump: error: query failed$/, - ); - expect(readdirSync(out)).toEqual([]); - - fakeTool('pg_dump', { exitCode: 1, stderr: 'x'.repeat(5000) }); - await expect(pgDump(URL_WITH_SECRET, target, bin)).rejects.toThrow(/^pg_dump failed: x{2000}…$/); - }); + message: /^pg_dump failed: pg_dump: error: query failed$/, + }, + { id: 'PGTOOLS-007b', stderr: 'x'.repeat(5000), message: /^pg_dump failed: x{2000}…$/ }, + ])( + '$id: a failing tool reports its own message without the lines that quote SQL or rows, and leaves no file', + async ({ stderr, message }) => { + installFakeTool(bin, 'psql', { snippets: [answersSchema()] }); + installFakeTool(bin, 'pg_dump', { snippets: [failsWith(stderr)] }); + const target = path.join(out, 'x.pgdump'); + await expect(pgDump(URL_WITH_SECRET, target, bin)).rejects.toThrow(message); + expect(readdirSync(out)).toEqual([]); + }, + ); it('PGTOOLS-008: a missing tool says how to install it, and a restore that cannot run leaves no work files', async () => { const source = path.join(out, 'in.pgdump'); await expect(pgRestore(URL_WITH_SECRET, source, bin)).rejects.toThrow(PgToolMissingError); await expect(pgDump(URL_WITH_SECRET, path.join(out, 'x.pgdump'), bin)).rejects.toThrow(/TREK_DB_PG_BIN_DIR/); - fakeTool('pg_restore', { body: WRITES_RESTRICTED_SCRIPT }); + installFakeTool(bin, 'pg_restore', { snippets: [writesRestrictedScript()] }); await expect(pgRestore(URL_WITH_SECRET, source, bin)).rejects.toThrow(/psql was not found/); expect(existsSync(out) && readdirSync(out)).toEqual([]); }); - it('PGTOOLS-009: client tools without the \\restrict fix (CVE-2025-8714) never turn a dump into a script', async () => { - fakeTool('pg_restore', { version: '16.9', body: `touch '${path.join(bin, 'ran')}'` }); - fakeTool('psql', { body: `touch '${path.join(bin, 'ran')}'` }); - await expect(pgRestore(URL_WITH_SECRET, path.join(out, 'in.pgdump'), bin)).rejects.toThrow( - /pg_restore is too old to restore safely \(pg_restore \(PostgreSQL\) 16\.9 \(Debian\)\): it must be at least 17\.6/, - ); - fakeTool('pg_restore', { body: `touch '${path.join(bin, 'ran')}'` }); - fakeTool('psql', { version: '17.5', body: `touch '${path.join(bin, 'ran')}'` }); - await expect(pgRestore(URL_WITH_SECRET, path.join(out, 'in.pgdump'), bin)).rejects.toThrow(/psql is too old/); - expect(existsSync(path.join(bin, 'ran'))).toBe(false); - expect(readdirSync(out)).toEqual([]); - }); + it.each([ + { + id: 'PGTOOLS-009a', + tool: 'pg_restore' as const, + version: '16.9', + message: + /pg_restore is too old to restore safely \(pg_restore \(PostgreSQL\) 16\.9 \(Debian\)\): it must be at least 17\.6, 16\.10, 15\.14 or 14\.19/, + }, + { id: 'PGTOOLS-009b', tool: 'psql' as const, version: '17.5', message: /psql is too old/ }, + ])( + '$id: client tools without the \\restrict fix (CVE-2025-8714) never turn a dump into a script', + async ({ tool, version, message }) => { + const ran = path.join(bin, 'ran'); + installFakeTool(bin, 'pg_restore', { snippets: [touches(ran)] }); + installFakeTool(bin, 'psql', { snippets: [touches(ran)] }); + installFakeTool(bin, tool, { version, snippets: [touches(ran)] }); + await expect(pgRestore(URL_WITH_SECRET, path.join(out, 'in.pgdump'), bin)).rejects.toThrow(message); + expect(existsSync(ran)).toBe(false); + expect(readdirSync(out)).toEqual([]); + }, + ); it('PGTOOLS-010: knows which client versions carry the \\restrict fix', () => { const fixed = ['14.19', '15.14', '16.10', '17.6', '17.11', '18.0', '19.1']; @@ -257,30 +231,30 @@ describe('pg-tools', () => { }); it('PGTOOLS-011: a dump holds the current schema only, matched by its exact name, which psql reads without the password in an argument', async () => { - const psqlLog = fakeTool('psql', { stdout: 'My"Trek\t"My""Trek"' }); - const log = fakeTool('pg_dump', { body: 'printf dump >> "${4#--file=}"' }); + const psqlLog = installFakeTool(bin, 'psql', { snippets: [answersSchema('My"Trek', '"My""Trek"')] }); + const dumpLog = installFakeTool(bin, 'pg_dump', { snippets: [writesFile('dump')] }); await pgDump(URL_WITH_SECRET, path.join(out, 'x.pgdump'), bin); - expect(argsOf(log)[4]).toBe('--schema="My""Trek"'); - expect(argsOf(psqlLog).join(' ')).toContain('current_schema()'); - expect(argsOf(psqlLog).join(' ')).not.toContain('s3cr'); + expect(readToolCall(dumpLog).args).toContain('--schema="My""Trek"'); + const psql = readToolCall(psqlLog); + expect(psql.args.join(' ')).toContain('current_schema()'); + expect(psql.args.join(' ')).not.toContain('s3cr'); - fakeTool('psql', { stdout: '\n' }); + installFakeTool(bin, 'psql', { snippets: [printsWhen('quote_ident', '\n')] }); await expect(pgDump(URL_WITH_SECRET, path.join(out, 'y.pgdump'), bin)).rejects.toThrow(/no current schema/); expect(readdirSync(out)).toEqual(['x.pgdump']); }); it('PGTOOLS-012: a restore keeps to the current schema, and refuses a dump without TREK tables there before clearing anything', async () => { const source = path.join(out, 'in.pgdump'); - const restoreLog = fakeTool('pg_restore', { - body: "printf '%s\\n' '\\restrict k1' 'CREATE TABLE auth.users (' ');' > \"${4#--file=}\"", + const restoreLog = installFakeTool(bin, 'pg_restore', { + snippets: [writesFile('\\restrict k1\nCREATE TABLE auth.users (\n);\n')], }); - const psqlLog = fakeTool('psql', { stdout: 'trek\ttrek' }); + const psqlLog = installFakeTool(bin, 'psql', { snippets: [answersSchema('trek')] }); await expect(pgRestore(URL_WITH_SECRET, source, bin)).rejects.toThrow( 'The backup holds no TREK tables in the schema "trek"; nothing was replaced.', ); - expect(argsOf(restoreLog)[2]).toBe('--schema=trek'); - // psql only read the schema: it never ran the clear or the load. - expect(argsOf(psqlLog).join(' ')).not.toContain('--single-transaction'); + expect(readToolCall(restoreLog).args).toContain('--schema=trek'); + expect(readToolCall(psqlLog).args.join(' ')).not.toContain('--single-transaction'); expect(readdirSync(out)).toEqual([]); }); });