implementing --use-defaults

This commit is contained in:
Benjamin Diedrichsen
2026-07-28 09:27:05 +02:00
parent 5ed68c0065
commit 30d93dddc5
11 changed files with 474 additions and 42 deletions
+78
View File
@@ -0,0 +1,78 @@
/**
* Tests for the Variables scope container.
*
* The merge order is what makes a non-interactive run configurable, so it is
* pinned down here rather than left to the callers to demonstrate.
*/
import { describe, expect, it } from 'vitest';
import { Variables } from '../src/nopy.common.js';
describe('Variables.assign', () => {
it('creates the scope entry on first assignment and merges afterwards', () => {
const variables = new Variables();
variables.assign('cube-a', 'defaults', { A: 1 });
variables.assign('cube-a', 'defaults', { B: 2 });
expect(variables.get('cube-a', 'defaults')).toEqual({ A: 1, B: 2 });
});
it('defaults to an empty assignment', () => {
const variables = new Variables();
variables.assign('cube-a', 'prompts');
expect(variables.get('cube-a', 'prompts')).toEqual({});
});
it('keeps scopes and cubes apart', () => {
const variables = new Variables();
variables.assign('cube-a', 'params', { A: 1 });
expect(variables.get('cube-a', 'prompts')).toEqual({});
expect(variables.get('cube-b', 'params')).toEqual({});
});
});
describe('Variables.get precedence', () => {
it('lets global env override a schema default', () => {
const variables = new Variables({ PORT: 2222 });
variables.assign('cube-a', 'defaults', { PORT: 22 });
expect(variables.get('cube-a').PORT).toBe(2222);
});
it('lets a prompt override global env', () => {
const variables = new Variables({ PORT: 2222 });
variables.assign('cube-a', 'defaults', { PORT: 22 });
variables.assign('cube-a', 'prompts', { PORT: 8080 });
expect(variables.get('cube-a').PORT).toBe(8080);
});
it('lets a dependency param override everything else', () => {
const variables = new Variables({ PORT: 2222 });
variables.assign('cube-a', 'defaults', { PORT: 22 });
variables.assign('cube-a', 'prompts', { PORT: 8080 });
variables.assign('cube-a', 'params', { PORT: 9090 });
expect(variables.get('cube-a').PORT).toBe(9090);
});
it('merges keys from every scope', () => {
const variables = new Variables({ G: 'g' });
variables.assign('cube-a', 'defaults', { D: 'd' });
variables.assign('cube-a', 'prompts', { P: 'p' });
variables.assign('cube-a', 'params', { X: 'x' });
expect(variables.get('cube-a')).toEqual({ G: 'g', D: 'd', P: 'p', X: 'x' });
});
it('applies global env to every cube', () => {
const variables = new Variables({ SHARED: 'yes' });
expect(variables.get('anything').SHARED).toBe('yes');
});
});
@@ -104,6 +104,99 @@ describe('BuildContext session replay', () => {
});
});
describe('BuildContext --use-defaults', () => {
const withDefaults = (cube: Cube, variables = new Variables(), cfg = config) =>
new BuildContext(
{ [cube.id]: cube },
variables,
session(),
cfg,
{ method: 'ssh' },
{ useDefaults: true }
);
it('skips the prompts and deploys the schema defaults', async () => {
const cube = testCube('cube-a', z.object({ PORT: z.string().default('3000') }));
const context = withDefaults(cube);
await context.resolveCube('cube-a', 'host1');
expect(VariableAssignment).not.toHaveBeenCalled();
expect(context.deployCalls[0].env.PORT).toBe('3000');
});
it('lets global env steer the run', async () => {
const cube = testCube('cube-a', z.object({ PORT: z.string().default('3000') }));
const context = withDefaults(cube, new Variables({ PORT: '8080' }));
await context.resolveCube('cube-a', 'host1');
expect(context.deployCalls[0].command.join(' ')).toContain('--data "PORT=8080"');
});
it('refuses to run a cube whose variable nothing can supply', async () => {
const cube = testCube('cube-a', z.object({ SSID: z.string(), PSK: z.string() }));
const context = withDefaults(cube);
await expect(context.resolveCube('cube-a', 'host1')).rejects.toThrow(
/Cube "cube-a" cannot run with --use-defaults: SSID, PSK have no default values/
);
expect(context.deployCalls).toHaveLength(0);
});
it('names a single missing variable in the singular', async () => {
const cube = testCube('cube-a', z.object({ SSID: z.string() }));
await expect(withDefaults(cube).resolveCube('cube-a', 'host1')).rejects.toThrow(
'SSID has no default value'
);
});
it('accepts a required variable supplied by global env', async () => {
const cube = testCube('cube-a', z.object({ SSID: z.string() }));
const context = withDefaults(cube, new Variables({ SSID: 'home' }));
await context.resolveCube('cube-a', 'host1');
expect(context.deployCalls[0].env.SSID).toBe('home');
});
it('accepts a required variable supplied by a dependency', async () => {
const cube = testCube('cube-a', z.object({ SSID: z.string() }));
const context = withDefaults(cube);
await context.resolveCube('cube-a', 'host1', { SSID: 'from-dep' });
expect(context.deployCalls[0].env.SSID).toBe('from-dep');
});
it('still resolves dependencies and hooks', async () => {
const dep = testCube('dep');
const main = new Cube(
Manifest.create({
id: 'main',
name: 'Main',
schema: z.object({ FLAG: z.boolean().default(true) }),
dependencies: (vars: Record<string, unknown>) => (vars.FLAG ? ['dep'] : []),
}),
'/test/main',
'deploy.py'
);
const context = new BuildContext(
{ dep, main },
new Variables(),
session(),
config,
{ method: 'ssh' },
{ useDefaults: true }
);
await context.resolveCube('main', 'host1');
expect(context.deployCalls.map((c) => c.cube)).toEqual(['dep', 'main']);
});
});
describe('BuildContext command construction', () => {
const build = (auth: { method: string; username?: string; password?: string }) => {
const context = new BuildContext(
+94
View File
@@ -0,0 +1,94 @@
/**
* Tests for the Cube runtime wrapper: default extraction and the required-key
* check that `--use-defaults` relies on.
*/
import { describe, expect, it } from 'vitest';
import { z } from 'zod';
import { Cube, Manifest } from '../src/cubes/types.js';
const cube = (schema: z.ZodObject<any>) =>
new Cube(Manifest.create({ id: 'c', name: 'C', schema }), '/cubes/c', 'deploy.py');
describe('Cube.getDefaults', () => {
it('resolves every default when the whole schema parses', () => {
const c = cube(
z.object({
PORT: z.number().default(8080),
NAME: z.string().default('svc'),
})
);
expect(c.getDefaults()).toEqual({ PORT: 8080, NAME: 'svc' });
});
it('keeps the declared defaults when one field has none', () => {
const c = cube(
z.object({
SSID: z.string(),
PRIORITY: z.number().default(10),
HIDDEN: z.boolean().default(false),
})
);
expect(c.getDefaults()).toEqual({ PRIORITY: 10, HIDDEN: false });
});
it('unwraps a default sitting under optional or nullable', () => {
const c = cube(
z.object({
REQUIRED: z.string(),
A: z.number().default(1).optional(),
B: z.number().default(2).nullable(),
C: z.number().optional().default(3),
})
);
expect(c.getDefaults()).toEqual({ A: 1, B: 2, C: 3 });
});
it('evaluates a lazily declared default', () => {
const c = cube(
z.object({ REQUIRED: z.string(), TOKEN: z.string().default(() => 'generated') })
);
expect(c.getDefaults()).toEqual({ TOKEN: 'generated' });
});
it('omits an optional field that declares no default', () => {
const c = cube(z.object({ REQUIRED: z.string(), MAYBE: z.string().optional() }));
expect(c.getDefaults()).toEqual({});
});
it('returns an empty object for an empty schema', () => {
expect(cube(z.object({})).getDefaults()).toEqual({});
});
});
describe('Cube.requiredKeys', () => {
it('lists the fields with neither a default nor optionality', () => {
const c = cube(
z.object({
SSID: z.string(),
PASSWORD: z.string(),
PRIORITY: z.number().default(10),
NOTE: z.string().optional(),
})
);
expect(c.requiredKeys()).toEqual(['SSID', 'PASSWORD']);
});
it('treats a nullable field without a default as required', () => {
const c = cube(z.object({ MAYBE: z.string().nullable() }));
expect(c.requiredKeys()).toEqual(['MAYBE']);
});
it('is empty when every field can fill itself in', () => {
const c = cube(z.object({ A: z.string().default('a'), B: z.string().optional() }));
expect(c.requiredKeys()).toEqual([]);
});
});
+35 -1
View File
@@ -9,9 +9,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { z } from 'zod';
const { inquirerPrompt, formRun, autoCompleteRun, autoCompleteCtor } = vi.hoisted(() => ({
const { inquirerPrompt, formRun, formCtor, autoCompleteRun, autoCompleteCtor } = vi.hoisted(() => ({
inquirerPrompt: vi.fn(),
formRun: vi.fn(),
formCtor: vi.fn(),
autoCompleteRun: vi.fn(),
autoCompleteCtor: vi.fn(),
}));
@@ -23,6 +24,9 @@ vi.mock('enquirer', () => ({
default: {
Form: class {
run = formRun;
constructor(options: unknown) {
formCtor(options);
}
},
AutoComplete: class {
run = autoCompleteRun;
@@ -50,6 +54,12 @@ const question = (name: string) => questions().find((q) => q.name === name);
/** Grabs the options the last enquirer AutoComplete prompt was constructed with. */
const autoComplete = () => autoCompleteCtor.mock.calls.at(-1)?.[0] as Record<string, any>;
/** Grabs the choices the last enquirer Form prompt was constructed with. */
const formChoices = () => {
const options = formCtor.mock.calls.at(-1)?.[0] as { choices: Record<string, any>[] };
return options.choices;
};
const cube = (id: string, name: string, schema = z.object({})) =>
new Cube(Manifest({ id, name, schema }), `/cubes/${id}`, 'deploy.py');
@@ -240,6 +250,30 @@ describe('VariableAssignment', () => {
expect(variables.get('svc', 'prompts')).toEqual({});
});
it('asks about a field that declares no default, with an empty initial value', async () => {
const required = z.object({
SSID: z.string().describe('Network name'),
PRIORITY: z.number().default(10),
});
formRun.mockResolvedValue({});
await VariableAssignment(cube('wifi', 'WiFi', required), new Variables());
expect(formChoices()).toEqual([
{ name: 'SSID', message: 'Network name', initial: '' },
{ name: 'PRIORITY', message: 'PRIORITY', initial: '10' },
]);
});
it('offers the value the run would use, not the bare schema default', async () => {
const variables = new Variables({ port: 2222 });
formRun.mockResolvedValue({});
await VariableAssignment(cube('svc', 'Service', schema), variables);
expect(formChoices().find((c) => c.name === 'port')?.initial).toBe('2222');
});
it('coerces answers using the schema and stores them under prompts', async () => {
const variables = new Variables();
formRun.mockResolvedValue({ port: '9090', enabled: 'true', name: 'api' });