scribase-cli/tests/migrate.test.ts
caelum0x 92f7df83c4 scribase CLI + TypeScript SDK (public edge repo)
Extracted from the private caelum0x/scribase monorepo's
packages/scribase-js with a fresh, single-commit history (no core
history leaks). The npx scribase CLI and the typed /v1 API client,
unchanged except: prepublishOnly simplified (the monorepo-only tarball
gitleaks gate dropped), repository/homepage/bugs fields added, and one
test that cross-checked embedded template strings against the
monorepo's templates/ directory removed (nothing it tested changed;
that directory isn't shipped here).
2026-11-12 18:10:58 +03:00

218 lines
11 KiB
TypeScript

/**
* Tests for `npx scribase migrate`: scaffolding a new file, reading and
* splitting local `.sql` files, which project/token it uses, the plan/lint
* request, dry-run, a BLOCK finding stopping apply, and errors (no network,
* in-memory files).
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { InitError } from '../src/cli/init.js';
import { formatMigrate, MIGRATIONS_DIR, parseMigrateArgs, runMigrate } from '../src/cli/migrate.js';
import type { MigrateIo } from '../src/cli/migrate.js';
const ROOT = '/work/app';
const STATE = JSON.stringify({
organization_id: 'tmp-1',
project_id: 'shop',
environment_id: 'production',
api_url: 'https://api.example.test',
});
interface Seen {
url: string;
auth: string | null;
body: Record<string, unknown>;
}
interface Written {
path: string;
contents: string;
}
function io(
files: Record<string, string>,
migrationFiles: string[],
answer: { status: number; body: unknown } | null,
env: Record<string, string> = {},
stored: { token?: string } = {},
) {
const seen: Seen[] = [];
const written: Written[] = [];
const value: MigrateIo = {
cwd: ROOT,
env,
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
seen.push({
url: String(url),
auth: new Headers(init?.headers).get('authorization'),
body: JSON.parse(String(init?.body)) as Record<string, unknown>,
});
if (!answer) throw new Error('unexpected network call');
return new Response(JSON.stringify(answer.body), { status: answer.status });
}) as typeof fetch,
readFile: (path) => files[path] ?? null,
writeFile: (path, contents) => {
written.push({ path, contents });
files[path] = contents;
},
listMigrationFiles: () => migrationFiles,
credentials: () => stored,
now: () => new Date('2026-10-29T12:34:56Z'),
};
return { io: value, seen, written };
}
const COMMITTED = {
plan: { steps: [{ version: 20261029123456, name: 'add_notes', direction: 'up', checksum: 'abc' }] },
lintFindings: [],
applied: [20261029123456],
};
describe('scribase migrate arguments', () => {
it('parses `new <name>`, the default run, --dry-run and --json', () => {
assert.deepEqual(parseMigrateArgs(['new', 'add notes']), { action: 'new', name: 'add notes', dryRun: false, json: false });
assert.deepEqual(parseMigrateArgs([]), { action: 'run', dryRun: false, json: false });
assert.deepEqual(parseMigrateArgs(['up', '--dry-run', '--json']), { action: 'run', dryRun: true, json: true });
});
it('rejects `new` with no name, an unknown argument and an unknown flag', () => {
assert.throws(() => parseMigrateArgs(['new']), (error: unknown) => error instanceof InitError && error.code === 'invalid_argument' && /name/.test(error.message));
assert.throws(() => parseMigrateArgs(['down']), (error: unknown) => error instanceof InitError && error.code === 'invalid_argument');
assert.throws(() => parseMigrateArgs(['--force']), (error: unknown) => error instanceof InitError && /--force/.test(error.message));
});
});
describe('scribase migrate new', () => {
it('scaffolds a timestamped file with a slugified name and both markers', async () => {
const { io: value, written } = io({}, [], null);
const result = await runMigrate({ action: 'new', name: 'Add Notes!', dryRun: false, json: false }, value);
assert.equal(result.action, 'new');
if (result.action !== 'new') throw new Error('unreachable');
assert.equal(result.version, '20261029123456');
assert.equal(result.name, 'add_notes');
assert.equal(result.path, `${ROOT}/${MIGRATIONS_DIR}/20261029123456_add_notes.sql`);
assert.equal(written.length, 1);
assert.match(written[0]?.contents ?? '', /^-- Add Notes!/);
assert.match(written[0]?.contents ?? '', /missing_rls/);
assert.match(written[0]?.contents ?? '', /\n-- down\n/);
assert.match(written[0]?.contents ?? '', /create table public\.add_notes/);
// Unedited, it is a real no-op: every SQL line is commented out.
for (const line of (written[0]?.contents ?? '').split('\n')) {
if (line.trim().length > 0) assert.match(line, /^--/, `expected a comment line, got: ${line}`);
}
});
it('never produces an empty slug, even from punctuation-only input', async () => {
const { io: value } = io({}, [], null);
const result = await runMigrate({ action: 'new', name: '!!!', dryRun: false, json: false }, value);
if (result.action !== 'new') throw new Error('unreachable');
assert.equal(result.name, 'migration');
});
});
describe('scribase migrate (run)', () => {
it('reports no files without making a network call when the folder has none', async () => {
const { io: value, seen } = io({}, [], null);
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(result.files, 0);
assert.equal(seen.length, 0);
assert.match(formatMigrate(result), /No migration files/);
});
it('reads local files in version order, splits up/down on the marker, and sends them with apply:true', async () => {
const files = {
[`${ROOT}/.scribase/project.json`]: STATE,
[`${ROOT}/.env.local`]: 'SCRIBASE_ACCESS_TOKEN=scb_agt_tmp\n',
[`${ROOT}/${MIGRATIONS_DIR}/2_second.sql`]: 'create table second (id int);\n-- down\ndrop table second;\n',
[`${ROOT}/${MIGRATIONS_DIR}/1_first.sql`]: 'create table first (id int);',
};
const { io: value, seen } = io(files, ['2_second.sql', '1_first.sql', 'README.md'], { status: 200, body: COMMITTED });
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(result.files, 2);
assert.equal(seen[0]?.url, 'https://api.example.test/v1/organizations/tmp-1/projects/shop/environments/production/migrations');
assert.equal(seen[0]?.auth, 'Bearer scb_agt_tmp');
const sent = seen[0]?.body.migrations as { version: string; up: string; down?: string }[];
assert.deepEqual(sent.map((m) => m.version), ['1', '2'], 'oldest version first, regardless of filesystem order');
assert.equal(sent[0]?.up, 'create table first (id int);');
assert.equal(sent[0]?.down, undefined, 'no marker, no down key');
assert.equal(sent[1]?.up, 'create table second (id int);');
assert.equal(sent[1]?.down, 'drop table second;');
assert.equal(seen[0]?.body.apply, true);
assert.equal(result.blocked, false);
const text = formatMigrate(result);
assert.match(text, /1 migration\(s\) ran/);
assert.doesNotMatch(text, /scb_agt_tmp/, 'the token is never printed');
});
it('sends apply:false with --dry-run and never reports anything applied', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' };
const { io: value, seen } = io(files, ['1_x.sql'], { status: 200, body: { plan: COMMITTED.plan, lintFindings: [], applied: [] } }, { SCRIBASE_ACCESS_TOKEN: 't' });
const result = await runMigrate({ action: 'run', dryRun: true, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(seen[0]?.body.apply, false);
assert.equal(result.blocked, false, '--dry-run is never "blocked", it never tried to apply');
assert.match(formatMigrate(result), /Dry run: nothing applied/);
});
it('marks the run blocked when a BLOCK finding stops every pending migration, and exits non-zero', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'create table t (id int);' };
const blocked = {
plan: { steps: [{ version: 1, name: 'x', direction: 'up', checksum: 'c' }] },
lintFindings: [{ rule: 'missing_rls', severity: 'BLOCK', subject: 'public.t', line: 1, message: 'has neither RLS enabled nor any policy' }],
applied: [],
};
const { io: value } = io(files, ['1_x.sql'], { status: 200, body: blocked }, { SCRIBASE_ACCESS_TOKEN: 't' });
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(result.blocked, true);
const text = formatMigrate(result);
assert.match(text, /\[BLOCK\] missing_rls/);
assert.match(text, /Nothing applied/);
});
it('skips the network call and says up to date when every local file is already applied', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' };
const upToDate = { plan: { steps: [] }, lintFindings: [], applied: [] };
const { io: value } = io(files, ['1_x.sql'], { status: 200, body: upToDate }, { SCRIBASE_ACCESS_TOKEN: 't' });
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
assert.match(formatMigrate(result), /Up to date/);
});
it('says what to do when the folder is not initialized, has no token, or the token is refused', async () => {
await assert.rejects(
runMigrate({ action: 'run', dryRun: false, json: false }, io({ [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' }, ['1_x.sql'], { status: 200, body: {} }).io),
(error: unknown) => error instanceof InitError && error.code === 'not_initialized' && /scribase init/.test(error.next ?? ''),
);
await assert.rejects(
runMigrate(
{ action: 'run', dryRun: false, json: false },
io({ [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' }, ['1_x.sql'], { status: 200, body: {} }).io,
),
(error: unknown) => error instanceof InitError && error.code === 'not_signed_in',
);
const refused = io(
{ [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' },
['1_x.sql'],
{ status: 401, body: { code: 'unauthorized', detail: 'token expired' } },
{ SCRIBASE_ACCESS_TOKEN: 'old' },
);
await assert.rejects(
runMigrate({ action: 'run', dryRun: false, json: false }, refused.io),
(error: unknown) => error instanceof InitError && error.code === 'unauthorized' && /HTTP 401/.test(error.message) && /init/.test(error.next ?? ''),
);
});
it('ignores files that do not match <version>_<name>.sql', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' };
const { io: value, seen } = io(files, ['1_x.sql', 'README.md', 'notes.sql', '.gitignore'], { status: 200, body: COMMITTED }, { SCRIBASE_ACCESS_TOKEN: 't' });
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(result.files, 1);
assert.equal((seen[0]?.body.migrations as unknown[]).length, 1);
});
});