Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
c918f27
test-postgres: the package's skeleton and the PostgreSQL its tests start
davidjalbers Nov 30, 2026
1332346
test-postgres: a test that starts, uses and stops a server (red)
davidjalbers Nov 30, 2026
8f67a43
test-postgres: start a cluster with initdb and pg_ctl, stop and remov…
davidjalbers Nov 30, 2026
414492c
test-postgres: tests of a database per caller, from a template, and i…
davidjalbers Nov 30, 2026
5063657
test-postgres: createDatabase() and dropDatabase(), a database per ca…
davidjalbers Nov 30, 2026
e6ead73
test-postgres: tests of missing binaries, a client-only install and n…
davidjalbers Nov 30, 2026
34b50ec
test-postgres: find the install on the PATH, or name the mise pin to add
davidjalbers Nov 30, 2026
9ea7f19
test-postgres: a test of a server of another major than asked for (red)
davidjalbers Nov 30, 2026
5aeee48
test-postgres: refuse a server of another major than the one asked for
davidjalbers Nov 30, 2026
35266f1
test-postgres: a test that kills the starting process with SIGKILL (red)
davidjalbers Nov 30, 2026
4217295
test-postgres: a detached supervisor owns the cluster and outlives it…
davidjalbers Nov 30, 2026
7d6aacd
test-postgres: a test of the root case, as root or in a container (red)
davidjalbers Nov 30, 2026
0505edd
test-postgres: as root, run the cluster as nobody, or say why it cannot
davidjalbers Nov 30, 2026
0014f5f
test-postgres: a test of server settings such as max_connections (red)
davidjalbers Nov 30, 2026
e904929
test-postgres: the caller's server settings, in postgresql.conf
davidjalbers Nov 30, 2026
d3f04b3
test-postgres: the changeset that releases it as 0.1.0
davidjalbers Nov 30, 2026
cd489e7
test-postgres: drop the root test; the fixture stays as a script run …
davidjalbers Nov 30, 2026
931c774
test-postgres: no retry of a template copy; PostgreSQL waits on its own
davidjalbers Nov 30, 2026
b01cc11
test-postgres: a test of the package bundled into its caller's file (…
davidjalbers Nov 30, 2026
616b551
test-postgres: refuse to start bundled; mark the supervisor by its en…
davidjalbers Nov 30, 2026
6329790
test-postgres: a test that a marked supervisor starts no server (red)
davidjalbers Nov 30, 2026
d49a533
test-postgres: a marked supervisor refuses to start another server
davidjalbers Nov 30, 2026
c0aea26
test-postgres: the tests share a way to watch a start that must fail
davidjalbers Nov 30, 2026
b2e0110
test-postgres: a test that a failed start says what PostgreSQL said (…
davidjalbers Nov 30, 2026
3ff3bb5
test-postgres: a failed start carries the end of server.log
davidjalbers Nov 30, 2026
eca2306
test-postgres: tests of SIGTERM, SIGINT and SIGHUP to the supervisor …
davidjalbers Nov 30, 2026
adad59a
test-postgres: the supervisor stops on SIGTERM, SIGINT and SIGHUP too
davidjalbers Nov 30, 2026
3e0061a
test-postgres: a test of a database name that needs quoting and encod…
davidjalbers Nov 30, 2026
62552d0
test-postgres: dropDatabase() decodes the name in the URL's path
davidjalbers Nov 30, 2026
11fe26f
test-postgres: a test of a server older than 17, with stand-in binari…
davidjalbers Nov 30, 2026
f9e0bea
test-postgres: refuse a server older than 17 before initdb runs
davidjalbers Nov 30, 2026
147ce0f
test-postgres: a test of the settings that are refused (red)
davidjalbers Nov 30, 2026
973573b
test-postgres: refuse the package's own settings and values of other …
davidjalbers Nov 30, 2026
d8778de
test-postgres: tests of conditions the header states and no test held
davidjalbers Nov 30, 2026
3978182
test-postgres: a failed start's supervisor exits; held-up processes a…
davidjalbers Nov 30, 2026
655562b
test-postgres: the header and the changeset say what the package does…
davidjalbers Nov 30, 2026
ca1e66f
test-postgres: the major the tests ask for is PLX_POSTGRES_MAJOR
davidjalbers Nov 30, 2026
134f1a1
test-postgres: a test of a signal to the supervisor during the start …
davidjalbers Nov 30, 2026
5b5ec9c
test-postgres: a stop asked during the start fails the start
davidjalbers Nov 30, 2026
64a6911
test-postgres: a test of a bundle inside the package directory (red)
davidjalbers Nov 30, 2026
53da2bc
test-postgres: a bundle inside the package directory is refused and l…
davidjalbers Nov 30, 2026
0425943
test-postgres: the header's lines wrapped, and what the session of it…
davidjalbers Nov 30, 2026
c46c5e8
test-postgres: a test of a bundled caller that catches the refusal
davidjalbers Nov 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/test-postgres.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@plexus-ms/test-postgres": minor
---

A new package: a throwaway PostgreSQL server for tests, started from the binary on the PATH and removed afterwards.
`startPostgres({ major })` initialises a cluster in a temporary directory and starts it on a free loopback port; `createDatabase()` gives each test file a database of its own, empty or copied from a template, and `dropDatabase()` drops one.
It fails with a message naming the mise pin to add when no server is on the PATH, and when the server is of another major than the one asked for; it needs PostgreSQL 17 or later.
As root it runs the server as `nobody`, and no server outlives the process that started it, even one killed with SIGKILL.
It must stay external to a bundle, and refuses to start when it is bundled into its caller's file.
5 changes: 5 additions & 0 deletions mise.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ hk = "latest"
# The plx pins are written with each Plexus version, never by the update bot (§ 1 PLX-Updates);
# allow_low_downloads only waives npm's young-package heuristics.
"npm:@plexus-ms/cli" = { version = "0.133.0", allow_low_downloads = true }
# The server @plexus-ms/test-postgres starts in its own tests; PLX_POSTGRES_MAJOR below names its major.
"conda:postgresql" = "18.6"

[settings]
# Not a version source: it lets config_roots match a project without a mise config of its own,
Expand All @@ -21,6 +23,9 @@ postinstall = "if command -v hk >/dev/null; then hk install --mise; fi && npx co

[env]
_.path = ["{{config_root}}/node_modules/.bin"]
# The major the tests ask the server for: that of the conda:postgresql pin, which a wrong one fails.
# Declared in turbo.json, so a new major runs the tests again.
PLX_POSTGRES_MAJOR = "18"

[tasks.dev]
description = "No-op: a package repo has no development environment to start; build builds its packages and test exercises them"
Expand Down
36 changes: 36 additions & 0 deletions packages/test-postgres/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "@plexus-ms/test-postgres",
"version": "0.0.0",
"description": "A throwaway PostgreSQL server for tests, from the binary on the PATH",
"license": "GPL-3.0-or-later",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "git+https://github.com/plexus-ms/libraries.git",
"directory": "packages/test-postgres"
},
"publishConfig": {
"registry": "https://registry.npmjs.org",
"access": "public"
},
"scripts": {
"build": "tsc",
"check": "tsc --noEmit",
"test": "node --test",
"prepack": "tsc"
},
"devDependencies": {
"@types/node": "^24.19.4",
"typescript": "catalog:"
}
}
112 changes: 112 additions & 0 deletions packages/test-postgres/src/binaries.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import assert from 'node:assert/strict';
import { existsSync } from 'node:fs';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, test } from 'node:test';
import { askedMajor, startThatFails } from './fixtures/support.ts';
import { startPostgres } from './index.ts';

const originalPath = process.env.PATH;
const made: string[] = [];
afterEach(async () => {
process.env.PATH = originalPath;
delete process.env.DATABASE_URL;
for (const dir of made.splice(0)) await rm(dir, { recursive: true, force: true });
});

// A directory on its own as the PATH, holding stand-ins for the tools named:
// postgres answers --version with `version`, initdb leaves a file initdb-ran
// beside them, and the others do nothing.
async function pathWith(tools: string[], version = `${askedMajor()}.6`) {
const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-path-'));
made.push(dir);
const scripts: Record<string, string> = {
postgres: `echo "postgres (PostgreSQL) ${version}"`,
initdb: `touch "${dir}/initdb-ran"`,
};
for (const tool of tools) {
await writeFile(path.join(dir, tool), `#!/bin/sh\n${scripts[tool] ?? 'exit 0'}\n`, { mode: 0o755 });
}
process.env.PATH = dir;
return dir;
}

const SERVER = ['initdb', 'pg_ctl', 'postgres', 'psql'];

const namesThePin = (major: number) => (error: Error) => {
assert.match(error.message, new RegExp(`"conda:postgresql" = "${major}\\.`));
assert.match(error.message, /mise\.toml/);
return true;
};

test('without PostgreSQL on the PATH it fails naming the mise pin to add', async () => {
const major = askedMajor();
await pathWith([]);
await assert.rejects(startPostgres({ major }), (error: Error) => {
assert.match(error.message, /initdb/);
return namesThePin(major)(error);
});
});

test('with a client-only install on the PATH it says so and names the mise pin', async () => {
const major = askedMajor();
const dir = await pathWith(['psql', 'pg_dump']);
await assert.rejects(startPostgres({ major }), (error: Error) => {
assert.match(error.message, /client/);
assert.ok(error.message.includes(dir), 'names where the client is');
return namesThePin(major)(error);
});
});

test('with initdb but no server beside it it names what is missing and the mise pin', async () => {
const major = askedMajor();
await pathWith(['initdb', 'psql']);
await assert.rejects(startPostgres({ major }), (error: Error) => {
assert.match(error.message, /pg_ctl/);
assert.match(error.message, /\bpostgres\b/);
return namesThePin(major)(error);
});
});

test('it never falls back to a database from the environment', async () => {
const major = askedMajor();
const running = await startPostgres({ major });
try {
process.env.DATABASE_URL = running.url;
await pathWith([]);
await assert.rejects(startPostgres({ major }), namesThePin(major));
} finally {
process.env.PATH = originalPath;
await running.stop();
}
});

test('a server older than 17 fails before initdb, naming the version found', async () => {
const dir = await pathWith(SERVER, '16.9');
const { error } = await startThatFails(() => startPostgres({ major: 16 }));
assert.match(error?.message ?? 'it started', /PostgreSQL 17 or later/);
assert.match(error?.message ?? '', /16\.9/);
assert.equal(existsSync(path.join(dir, 'initdb-ran')), false, 'initdb did not run');
});

test('an install without psql beside initdb fails naming psql and the mise pin', async () => {
const major = askedMajor();
await pathWith(['initdb', 'pg_ctl', 'postgres']);
await assert.rejects(startPostgres({ major }), (error: Error) => {
assert.match(error.message, /psql/);
return namesThePin(major)(error);
});
});

test('a server of a lower and one of a higher major than asked for both fail', async () => {
for (const version of ['17.4', '19.1']) {
await pathWith(SERVER, version);
const { error } = await startThatFails(() => startPostgres({ major: 18 }));
assert.match(
error?.message ?? `it started with ${version}`,
new RegExp(`PostgreSQL ${version.replace('.', '\\.')}`),
);
assert.match(error?.message ?? '', /"conda:postgresql" = "18\./);
}
});
111 changes: 111 additions & 0 deletions packages/test-postgres/src/bundled.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import assert from 'node:assert/strict';
import { execFileSync, spawn } from 'node:child_process';
import { once } from 'node:events';
import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { test } from 'node:test';
import { askedMajor, startThatFails } from './fixtures/support.ts';
import { startPostgres } from './index.ts';

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const processesNaming = (text: string) =>
execFileSync('ps', ['-A', '-o', 'pid=', '-o', 'command='], { encoding: 'utf8' })
.split('\n')
.filter((line) => line.includes(text))
.map((line) => Number.parseInt(line, 10));

// A bundler puts the package's code and the caller's into one file, as here
// by hand: the package's source with a caller after it, in a directory whose
// package.json names `owner`. Every process that runs the file logs itself,
// and a process three levels down exits at once, so that a regression stays
// small. With `caught`, the caller catches the refusal and lives on for two
// seconds, during which nothing may be created.
async function assertBundleRefused(owner: string, caught = false) {
const app = await mkdtemp(path.join(tmpdir(), 'test-postgres-bundle-'));
const clusters = path.join(app, 'tmp');
const log = path.join(app, 'processes.log');
const file = path.join(app, 'app.ts');
try {
await mkdir(clusters);
await writeFile(path.join(app, 'package.json'), `{ "name": "${owner}", "type": "module" }\n`);
const caller = [
"import { appendFileSync } from 'node:fs';",
'const depth = Number(process.env.TEST_BUNDLE_DEPTH ?? 0);',
`appendFileSync(${JSON.stringify(log)}, \`\${depth}\\n\`);`,
'process.env.TEST_BUNDLE_DEPTH = String(depth + 1);',
'if (depth >= 2) process.exit(0);',
caught ? 'try {' : '',
`const server = await startPostgres({ major: ${askedMajor()} });`,
'await server.stop();',
caught
? '} catch (error) { console.error(String(error)); await new Promise((r) => setTimeout(r, 2_000)); process.exit(1); }'
: '',
].join('\n');
await writeFile(file, `${await readFile(new URL('./index.ts', import.meta.url), 'utf8')}\n${caller}\n`);

const run = spawn(process.execPath, [file], {
env: { ...process.env, TMPDIR: clusters },
stdio: ['ignore', 'ignore', 'pipe'],
});
let stderr = '';
run.stderr.on('data', (chunk) => {
stderr += chunk;
});
let created = false;
let ended = false;
const exited = once(run, 'exit').finally(() => {
ended = true;
});
const watched = (async () => {
while (!ended) {
created ||= (await readdir(clusters)).length > 0;
await sleep(50);
}
})();
const [code] = (await Promise.race([exited, sleep(20_000).then(() => ['timeout'])])) as [number | string];
ended = true;
await watched;
await sleep(1_000);

const depths = (await readFile(log, 'utf8')).trim().split('\n').map(Number);
assert.ok(depths.filter((depth) => depth > 0).length <= 1, `at most one supervisor ever existed: ${depths}`);
assert.notEqual(code, 0);
assert.match(stderr, /bundled/);
assert.match(stderr, /external/);
assert.deepEqual(processesNaming(clusters), [], 'no server runs');
assert.deepEqual(await readdir(clusters), [], 'no cluster directory is left');
assert.equal(created, false, 'no cluster directory was ever made');
} finally {
// What a regression left: its processes, then its servers, then the files.
for (const pid of processesNaming(file)) process.kill(pid, 'SIGKILL');
for (const pid of processesNaming(clusters)) process.kill(pid, 'SIGQUIT');
for (let i = 0; i < 50 && processesNaming(clusters).length > 0; i++) await sleep(100);
await rm(app, { recursive: true, force: true });
}
}

test('bundled into the file of its caller it refuses to start, and starts nothing', { timeout: 60_000 }, () =>
assertBundleRefused('app'),
);

// The own-file check passes there, so the supervisor starts and has to find
// out for itself.
test('bundled into a file inside the package directory it refuses too, and leaves nothing', { timeout: 60_000 }, () =>
assertBundleRefused('@plexus-ms/test-postgres'),
);

test('a caller in such a bundle that catches the refusal and lives on starts nothing either', { timeout: 60_000 }, () =>
assertBundleRefused('@plexus-ms/test-postgres', true),
);

test('a process the package marked as a supervisor refuses to start another server', async () => {
process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR = '{}';
try {
const { error, left } = await startThatFails(() => startPostgres({ major: askedMajor() }));
assert.match(error?.message ?? 'it started', /bundled/);
assert.deepEqual(left, [], 'nothing was started');
} finally {
delete process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR;
}
});
90 changes: 90 additions & 0 deletions packages/test-postgres/src/databases.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { after, before, test } from 'node:test';
import { promisify } from 'node:util';
import { askedMajor, query } from './fixtures/support.ts';
import { createDatabase, dropDatabase, type Postgres, startPostgres } from './index.ts';

let server: Postgres;
before(async () => {
server = await startPostgres({ major: askedMajor() });
});
after(() => server.stop());

const nameOf = (url: string) => new URL(url).pathname.slice(1);

test('createDatabase() gives each caller an empty database of its own, in parallel', async () => {
const [a, b] = await Promise.all([createDatabase(server.url), createDatabase(server.url)]);
assert.notEqual(nameOf(a), nameOf(b));
await Promise.all([
query(a, "create table t (v text); insert into t values ('a')"),
query(b, "create table t (v text); insert into t values ('b')"),
]);
assert.equal(await query(a, 'select v from t'), 'a');
assert.equal(await query(b, 'select v from t'), 'b');
});

test('a database made from a template starts with its contents, even while a session holds the template', async () => {
const template = await createDatabase(server.url);
await query(template, "create table t (v text); insert into t values ('seed')");
// A session still connected to the template, as a migration's pool can be
// for a moment after it ends: PostgreSQL refuses to copy the template meanwhile.
const lingering = promisify(execFile)('psql', ['-X', '-d', template, '-c', 'select pg_sleep(1)']);
await new Promise((resolve) => setTimeout(resolve, 200));
const copies = await Promise.all(
Array.from({ length: 4 }, () => createDatabase(server.url, { template: nameOf(template) })),
);
await lingering;
for (const copy of copies) assert.equal(await query(copy, 'select v from t'), 'seed');
await query(copies[0] ?? '', "insert into t values ('only here')");
assert.equal(await query(copies[1] ?? '', 'select count(*) from t'), '1');
});

test('dropDatabase() drops the database its URL names, even with a session connected', async () => {
const url = await createDatabase(server.url);
// Longer than the five seconds PostgreSQL waits for a session to leave.
const lingering = promisify(execFile)('psql', ['-X', '-d', url, '-c', 'select pg_sleep(30)']).catch(() => {});
await new Promise((resolve) => setTimeout(resolve, 200));
await dropDatabase(url);
await lingering;
assert.equal(await query(server.url, `select count(*) from pg_database where datname = '${nameOf(url)}'`), '0');
});

test('a name with a space and a double quote works as a template, and its URL drops it', async () => {
const name = 'odd "name" here';
await query(server.url, `create database "odd ""name"" here"`);
const url = new URL(server.url);
url.pathname = `/${encodeURIComponent(name)}`;
await query(url.toString(), "create table t (v text); insert into t values ('from the odd one')");
const copy = await createDatabase(server.url, { template: name });
assert.equal(await query(copy, 'select v from t'), 'from the odd one');
await dropDatabase(url.toString());
assert.equal(await query(server.url, `select count(*) from pg_database where datname = 'odd "name" here'`), '0');
});

test('the PG variables of the environment do not change where the calls connect', async () => {
const variables = {
PGHOSTADDR: '127.0.0.2',
PGPORT: '1',
PGDATABASE: 'nowhere',
PGUSER: 'nobody_here',
PGSSLMODE: 'require',
PGCONNECT_TIMEOUT: '2',
};
Object.assign(process.env, variables);
let made: string;
let other: Postgres;
try {
other = await startPostgres({ major: askedMajor() });
made = await createDatabase(server.url);
await dropDatabase(made);
} finally {
for (const name of Object.keys(variables)) delete process.env[name];
}
try {
assert.equal(await query(other.url, 'select 1'), '1');
assert.equal(await query(server.url, `select count(*) from pg_database where datname = '${nameOf(made)}'`), '0');
} finally {
await other.stop();
}
});
Loading