Skip to content
Myr

Add describe wrappers so test output makes sense without filenames (#2472)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by John Gee · committed by GitHub · parent 3dd6086 · Browse files · 100 files+5340 added−5174 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

100 files+5340 added−5174 removed

  • tests:+5340 added−5174 removed

100 files+5340 added−5174 removed

modified:tests/args.literal.test.js+24 added-22 removed
modified:tests/args.variadic.test.js+1 added-1 removed
modified:tests/argument.choices.test.js+22 added-20 removed
modified:tests/argument.custom-processing.test.js+162 added-158 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test } = require('node:test');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56// Testing default value and custom processing behaviours.7// Some double assertions in tests to check action argument and .processedArg89describe('custom processing function for command-argument', () => {9test('when argument not specified then callback not called', (t) => {10 const mockCoercion = t.mock.fn();11 const program = new commander.Command();12 program.argument('[n]', 'number', mockCoercion).action(() => {});13 program.parse([], { from: 'user' });14 assert.equal(mockCoercion.mock.callCount(), 0);15});10 test('when argument not specified then callback not called', (t) => {11 const mockCoercion = t.mock.fn();12 const program = new commander.Command();13 program.argument('[n]', 'number', mockCoercion).action(() => {});14 program.parse([], { from: 'user' });15 assert.equal(mockCoercion.mock.callCount(), 0);16 });1717test('when argument not specified then action argument undefined', () => {18 let actionValue = 'foo';19 const program = new commander.Command();20 program.argument('[n]', 'number', parseFloat).action((arg) => {21 actionValue = arg;18 test('when argument not specified then action argument undefined', () => {19 let actionValue = 'foo';20 const program = new commander.Command();21 program.argument('[n]', 'number', parseFloat).action((arg) => {22 actionValue = arg;23 });24 program.parse([], { from: 'user' });25 assert.equal(actionValue, undefined);26 });23 program.parse([], { from: 'user' });24 assert.equal(actionValue, undefined);25});2727test('when custom with starting value and argument not specified then callback not called', (t) => {28 const mockCoercion = t.mock.fn();29 const program = new commander.Command();30 program.argument('[n]', 'number', parseFloat, 1).action(() => {});31 program.parse([], { from: 'user' });32 assert.equal(mockCoercion.mock.callCount(), 0);33});28 test('when custom with starting value and argument not specified then callback not called', (t) => {29 const mockCoercion = t.mock.fn();30 const program = new commander.Command();31 program.argument('[n]', 'number', parseFloat, 1).action(() => {});32 program.parse([], { from: 'user' });33 assert.equal(mockCoercion.mock.callCount(), 0);34 });3535test('when custom with starting value and argument not specified with action handler then action argument is starting value', () => {36 const startingValue = 1;37 let actionValue;38 const program = new commander.Command();39 program.argument('[n]', 'number', parseFloat, startingValue).action((arg) => {40 actionValue = arg;36 test('when custom with starting value and argument not specified with action handler then action argument is starting value', () => {37 const startingValue = 1;38 let actionValue;39 const program = new commander.Command();40 program41 .argument('[n]', 'number', parseFloat, startingValue)42 .action((arg) => {43 actionValue = arg;44 });45 program.parse([], { from: 'user' });46 assert.equal(actionValue, startingValue);47 assert.deepEqual(program.processedArgs, [startingValue]);48 });42 program.parse([], { from: 'user' });43 assert.equal(actionValue, startingValue);44 assert.deepEqual(program.processedArgs, [startingValue]);45});4947test('when custom with starting value and argument not specified without action handler then .processedArgs has starting value', () => {48 const startingValue = 1;49 const program = new commander.Command();50 program.argument('[n]', 'number', parseFloat, startingValue);51 program.parse([], { from: 'user' });52 assert.deepEqual(program.processedArgs, [startingValue]);53});50 test('when custom with starting value and argument not specified without action handler then .processedArgs has starting value', () => {51 const startingValue = 1;52 const program = new commander.Command();53 program.argument('[n]', 'number', parseFloat, startingValue);54 program.parse([], { from: 'user' });55 assert.deepEqual(program.processedArgs, [startingValue]);56 });5755test('when default value is defined (without custom processing) and argument not specified with action handler then action argument is default value', () => {56 const defaultValue = 1;57 let actionValue;58 const program = new commander.Command();59 program.argument('[n]', 'number', defaultValue).action((arg) => {60 actionValue = arg;58 test('when default value is defined (without custom processing) and argument not specified with action handler then action argument is default value', () => {59 const defaultValue = 1;60 let actionValue;61 const program = new commander.Command();62 program.argument('[n]', 'number', defaultValue).action((arg) => {63 actionValue = arg;64 });65 program.parse([], { from: 'user' });66 assert.equal(actionValue, defaultValue);67 assert.deepEqual(program.processedArgs, [defaultValue]);68 });62 program.parse([], { from: 'user' });63 assert.equal(actionValue, defaultValue);64 assert.deepEqual(program.processedArgs, [defaultValue]);65});6967test('when default value is defined (without custom processing) and argument not specified without action handler then .processedArgs is default value', () => {68 const defaultValue = 1;69 const program = new commander.Command();70 program.argument('[n]', 'number', defaultValue);71 program.parse([], { from: 'user' });72 assert.deepEqual(program.processedArgs, [defaultValue]);73});70 test('when default value is defined (without custom processing) and argument not specified without action handler then .processedArgs is default value', () => {71 const defaultValue = 1;72 const program = new commander.Command();73 program.argument('[n]', 'number', defaultValue);74 program.parse([], { from: 'user' });75 assert.deepEqual(program.processedArgs, [defaultValue]);76 });7775test('when argument specified then callback called with value', (t) => {76 const mockCoercion = t.mock.fn();77 const value = '1';78 const program = new commander.Command();79 program.argument('[n]', 'number', mockCoercion).action(() => {});80 program.parse([value], { from: 'user' });81 assert.deepEqual(mockCoercion.mock.calls[0].arguments, [value, undefined]);82});78 test('when argument specified then callback called with value', (t) => {79 const mockCoercion = t.mock.fn();80 const value = '1';81 const program = new commander.Command();82 program.argument('[n]', 'number', mockCoercion).action(() => {});83 program.parse([value], { from: 'user' });84 assert.deepEqual(mockCoercion.mock.calls[0].arguments, [value, undefined]);85 });8684test('when argument specified with action handler then action value is as returned from callback', () => {85 const callbackResult = 2;86 let actionValue;87 const program = new commander.Command();88 program89 .argument('[n]', 'number', () => {87 test('when argument specified with action handler then action value is as returned from callback', () => {88 const callbackResult = 2;89 let actionValue;90 const program = new commander.Command();91 program92 .argument('[n]', 'number', () => {93 return callbackResult;94 })95 .action((arg) => {96 actionValue = arg;97 });98 program.parse(['node', 'test', 'alpha']);99 assert.equal(actionValue, callbackResult);100 assert.deepEqual(program.processedArgs, [callbackResult]);101 });102103 test('when argument specified without action handler then .processedArgs is as returned from callback', () => {104 const callbackResult = 2;105 const program = new commander.Command();106 program.argument('[n]', 'number', () => {107 return callbackResult;91 })92 .action((arg) => {93 actionValue = arg;108 });95 program.parse(['node', 'test', 'alpha']);96 assert.equal(actionValue, callbackResult);97 assert.deepEqual(program.processedArgs, [callbackResult]);98});109 program.parse(['node', 'test', 'alpha']);110 assert.deepEqual(program.processedArgs, [callbackResult]);111 });112100test('when argument specified without action handler then .processedArgs is as returned from callback', () => {101 const callbackResult = 2;102 const program = new commander.Command();103 program.argument('[n]', 'number', () => {104 return callbackResult;113 test('when argument specified then program.args has original rather than custom', () => {114 // This is as intended, so check behaviour.115 const callbackResult = 2;116 const program = new commander.Command();117 program118 .argument('[n]', 'number', () => {119 return callbackResult;120 })121 .action(() => {});122 program.parse(['node', 'test', 'alpha']);123 assert.deepEqual(program.args, ['alpha']);124 });106 program.parse(['node', 'test', 'alpha']);107 assert.deepEqual(program.processedArgs, [callbackResult]);108});125110test('when argument specified then program.args has original rather than custom', () => {111 // This is as intended, so check behaviour.112 const callbackResult = 2;113 const program = new commander.Command();114 program115 .argument('[n]', 'number', () => {116 return callbackResult;117 })118 .action(() => {});119 program.parse(['node', 'test', 'alpha']);120 assert.deepEqual(program.args, ['alpha']);121});126 test('when custom with starting value and argument specified then callback called with value and starting value', (t) => {127 const mockCoercion = t.mock.fn();128 const startingValue = 1;129 const value = '2';130 const program = new commander.Command()131 .argument('[n]', 'number', mockCoercion, startingValue)132 .action(() => {});133 program.parse(['node', 'test', value]);134 assert.deepEqual(mockCoercion.mock.calls[0].arguments, [135 value,136 startingValue,137 ]);138 });139123test('when custom with starting value and argument specified then callback called with value and starting value', (t) => {124 const mockCoercion = t.mock.fn();125 const startingValue = 1;126 const value = '2';127 const program = new commander.Command()128 .argument('[n]', 'number', mockCoercion, startingValue)129 .action(() => {});130 program.parse(['node', 'test', value]);131 assert.deepEqual(mockCoercion.mock.calls[0].arguments, [132 value,133 startingValue,134 ]);135});140 test('when variadic argument specified multiple times then callback called with value and previousValue', (t) => {141 const mockCoercion = t.mock.fn(() => {142 return 'callback';143 });144 const program = new commander.Command();145 program.argument('<n...>', 'number', mockCoercion).action(() => {});146 program.parse(['1', '2'], { from: 'user' });147 assert.equal(mockCoercion.mock.callCount(), 2);148 assert.deepEqual(mockCoercion.mock.calls[0].arguments, ['1', undefined]);149 assert.deepEqual(mockCoercion.mock.calls[1].arguments, ['2', 'callback']);150 });151137test('when variadic argument specified multiple times then callback called with value and previousValue', (t) => {138 const mockCoercion = t.mock.fn(() => {139 return 'callback';152 test('when variadic argument without action handler then .processedArg has array', () => {153 const program = new commander.Command();154 program.argument('<n...>', 'number');155 program.parse(['1', '2'], { from: 'user' });156 assert.deepEqual(program.processedArgs, [['1', '2']]);157 });141 const program = new commander.Command();142 program.argument('<n...>', 'number', mockCoercion).action(() => {});143 program.parse(['1', '2'], { from: 'user' });144 assert.equal(mockCoercion.mock.callCount(), 2);145 assert.deepEqual(mockCoercion.mock.calls[0].arguments, ['1', undefined]);146 assert.deepEqual(mockCoercion.mock.calls[1].arguments, ['2', 'callback']);147});158149test('when variadic argument without action handler then .processedArg has array', () => {150 const program = new commander.Command();151 program.argument('<n...>', 'number');152 program.parse(['1', '2'], { from: 'user' });153 assert.deepEqual(program.processedArgs, [['1', '2']]);154});155156test('when parseFloat "1e2" then action argument is 100', () => {157 let actionValue;158 const program = new commander.Command();159 program.argument('<number>', 'float argument', parseFloat).action((arg) => {160 actionValue = arg;159 test('when parseFloat "1e2" then action argument is 100', () => {160 let actionValue;161 const program = new commander.Command();162 program.argument('<number>', 'float argument', parseFloat).action((arg) => {163 actionValue = arg;164 });165 program.parse(['1e2'], { from: 'user' });166 assert.equal(actionValue, 100);167 assert.deepEqual(program.processedArgs, [actionValue]);168 });162 program.parse(['1e2'], { from: 'user' });163 assert.equal(actionValue, 100);164 assert.deepEqual(program.processedArgs, [actionValue]);165});169167test('when defined default value for required argument then throw', () => {168 const program = new commander.Command();169 assert.throws(() => {170 program.argument('<number>', 'float argument', 4);170 test('when defined default value for required argument then throw', () => {171 const program = new commander.Command();172 assert.throws(() => {173 program.argument('<number>', 'float argument', 4);174 });175 });172});176174test('when custom processing for argument throws plain error then not CommanderError caught', () => {175 function justSayNo(value) {176 throw new Error('plain error');177 }178 const program = createTestCommand();179 program.argument('[n]', 'number', justSayNo).action(() => {});177 test('when custom processing for argument throws plain error then not CommanderError caught', () => {178 function justSayNo(value) {179 throw new Error('plain error');180 }181 const program = createTestCommand();182 program.argument('[n]', 'number', justSayNo).action(() => {});183181 assert.throws(182 () => {183 program.parse(['green'], { from: 'user' });184 },185 (err) => {186 assert.equal(err instanceof Error, true);187 assert.equal(err instanceof commander.CommanderError, false);188 return true;189 },190 );184 assert.throws(185 () => {186 program.parse(['green'], { from: 'user' });187 },188 (err) => {189 assert.equal(err instanceof Error, true);190 assert.equal(err instanceof commander.CommanderError, false);191 return true;192 },193 );194 });195});
modified:tests/argument.required.test.js+27 added-25 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45// Low-level tests of setting Argument.required.6// Higher level tests of optional/required arguments elsewhere.78describe('Argument required/optional', () => {8test('when name with surrounding <> then argument required', () => {9 const argument = new commander.Argument('<name>');10 assert.equal(argument.required, true);11});9 test('when name with surrounding <> then argument required', () => {10 const argument = new commander.Argument('<name>');11 assert.equal(argument.required, true);12 });1313test('when name with surrounding [] then argument optional', () => {14 const argument = new commander.Argument('[name]');15 assert.equal(argument.required, false);16});14 test('when name with surrounding [] then argument optional', () => {15 const argument = new commander.Argument('[name]');16 assert.equal(argument.required, false);17 });1818test('when name without surrounding brackets then argument required', () => {19 // default behaviour, allowed from Commander 820 const argument = new commander.Argument('name');21 assert.equal(argument.required, true);22});19 test('when name without surrounding brackets then argument required', () => {20 // default behaviour, allowed from Commander 821 const argument = new commander.Argument('name');22 assert.equal(argument.required, true);23 });2424test('when call .argRequired() then argument required', () => {25 const argument = new commander.Argument('name');26 argument.required = false;27 argument.argRequired();28 assert.equal(argument.required, true);29});25 test('when call .argRequired() then argument required', () => {26 const argument = new commander.Argument('name');27 argument.required = false;28 argument.argRequired();29 assert.equal(argument.required, true);30 });3131test('when call .argOptional() then argument optional', () => {32 const argument = new commander.Argument('name');33 argument.required = true;34 argument.argOptional();35 assert.equal(argument.required, false);32 test('when call .argOptional() then argument optional', () => {33 const argument = new commander.Argument('name');34 argument.required = true;35 argument.argOptional();36 assert.equal(argument.required, false);37 });38});
modified:tests/argument.variadic.test.js+1 added-1 removed
2 unmodified lines
3const assert = require('node:assert/strict');45// Testing variadic arguments. Testing all the action arguments, but could test just variadicArg.67describe('variadic argument', (t) => {7describe('Command variadic argument using .argument()', (t) => {8 test('when no extra arguments specified for program then variadic arg is empty array', (t) => {9 const actionMock = t.mock.fn();10 const program = new commander.Command();11 program.argument('<id>').argument('[variadicArg...]').action(actionMock);
96 unmodified lines
modified:tests/command.action.test.js+129 added-127 removed
3 unmodified lines
4const assert = require('node:assert/strict');56// Test some behaviours of .action not covered in more specific tests.78describe('Command.action()', () => {8test('when .action called then command passed to action', (t) => {9 const actionMock = t.mock.fn();10 const program = new commander.Command();11 const cmd = program.command('info').action(actionMock);12 program.parse(['node', 'test', 'info']);13 const callArgs = actionMock.mock.calls[0].arguments;14 assert.equal(callArgs[0], cmd.opts());15 assert.equal(callArgs[1], cmd);16});9 test('when .action called then command passed to action', (t) => {10 const actionMock = t.mock.fn();11 const program = new commander.Command();12 const cmd = program.command('info').action(actionMock);13 program.parse(['node', 'test', 'info']);14 const callArgs = actionMock.mock.calls[0].arguments;15 assert.equal(callArgs[0], cmd.opts());16 assert.equal(callArgs[1], cmd);17 });1818test('when .action called then this is set to command', () => {19 const program = new commander.Command();20 let actionThis;21 const cmd = program.command('info').action(function () {22 actionThis = this;19 test('when .action called then this is set to command', () => {20 const program = new commander.Command();21 let actionThis;22 const cmd = program.command('info').action(function () {23 actionThis = this;24 });25 program.parse(['node', 'test', 'info']);26 assert.equal(actionThis, cmd);27 });24 program.parse(['node', 'test', 'info']);25 assert.equal(actionThis, cmd);26});2828test('when .action called then program.args only contains args', () => {29 // At one time program.args was being modified to contain the same args as the call to .action30 // and so included the command as an extra and unexpected complex item in array.31 const program = new commander.Command();32 program.command('info <file>').action(() => {});33 program.parse(['node', 'test', 'info', 'my-file']);34 assert.deepEqual(program.args, ['info', 'my-file']);35});29 test('when .action called then program.args only contains args', () => {30 // At one time program.args was being modified to contain the same args as the call to .action31 // and so included the command as an extra and unexpected complex item in array.32 const program = new commander.Command();33 program.command('info <file>').action(() => {});34 program.parse(['node', 'test', 'info', 'my-file']);35 assert.deepEqual(program.args, ['info', 'my-file']);36 });3737describe('when .action on program with required argument and argument supplied then action called', () => {38 getTestCases('<file>').forEach(([methodName, program]) => {39 test(`via ${methodName}`, (t) => {40 const actionMock = t.mock.fn();41 program.action(actionMock);42 program.parse(['node', 'test', 'my-file']);43 const callArgs = actionMock.mock.calls[0].arguments;44 assert.equal(callArgs[0], 'my-file');45 assert.equal(callArgs[1], program.opts());46 assert.equal(callArgs[2], program);38 describe('when .action on program with required argument and argument supplied then action called', () => {39 getTestCases('<file>').forEach(([methodName, program]) => {40 test(`via ${methodName}`, (t) => {41 const actionMock = t.mock.fn();42 program.action(actionMock);43 program.parse(['node', 'test', 'my-file']);44 const callArgs = actionMock.mock.calls[0].arguments;45 assert.equal(callArgs[0], 'my-file');46 assert.equal(callArgs[1], program.opts());47 assert.equal(callArgs[2], program);48 });49 });50 });49});5151describe('when .action on program with required argument and argument not supplied then action not called', () => {52 getTestCases('<file>').forEach(([methodName, program]) => {53 test(`via ${methodName}`, (t) => {54 const actionMock = t.mock.fn();55 program.action(actionMock);56 assert.throws(() => {57 program.parse(['node', 'test']);52 describe('when .action on program with required argument and argument not supplied then action not called', () => {53 getTestCases('<file>').forEach(([methodName, program]) => {54 test(`via ${methodName}`, (t) => {55 const actionMock = t.mock.fn();56 program.action(actionMock);57 assert.throws(() => {58 program.parse(['node', 'test']);59 });60 assert.equal(actionMock.mock.callCount(), 0);61 });59 assert.equal(actionMock.mock.callCount(), 0);62 });63 });62});6464// Changes made in #729 to call program action handler65test('when .action on program and no arguments then action called', (t) => {66 const actionMock = t.mock.fn();67 const program = new commander.Command();68 program.action(actionMock);69 program.parse(['node', 'test']);70 const callArgs = actionMock.mock.calls[0].arguments;71 assert.equal(callArgs[0], program.opts());72 assert.equal(callArgs[1], program);73});65 // Changes made in #729 to call program action handler66 test('when .action on program and no arguments then action called', (t) => {67 const actionMock = t.mock.fn();68 const program = new commander.Command();69 program.action(actionMock);70 program.parse(['node', 'test']);71 const callArgs = actionMock.mock.calls[0].arguments;72 assert.equal(callArgs[0], program.opts());73 assert.equal(callArgs[1], program);74 });7575describe('when .action on program with optional argument supplied then action called', () => {76 getTestCases('[file]').forEach(([methodName, program]) => {77 test(`via ${methodName}`, (t) => {78 const actionMock = t.mock.fn();79 program.action(actionMock);80 program.parse(['node', 'test', 'my-file']);81 const callArgs = actionMock.mock.calls[0].arguments;82 assert.equal(callArgs[0], 'my-file');83 assert.equal(callArgs[1], program.opts());84 assert.equal(callArgs[2], program);76 describe('when .action on program with optional argument supplied then action called', () => {77 getTestCases('[file]').forEach(([methodName, program]) => {78 test(`via ${methodName}`, (t) => {79 const actionMock = t.mock.fn();80 program.action(actionMock);81 program.parse(['node', 'test', 'my-file']);82 const callArgs = actionMock.mock.calls[0].arguments;83 assert.equal(callArgs[0], 'my-file');84 assert.equal(callArgs[1], program.opts());85 assert.equal(callArgs[2], program);86 });87 });88 });87});8989describe('when .action on program without optional argument supplied then action called', () => {90 getTestCases('[file]').forEach(([methodName, program]) => {91 test(`via ${methodName}`, (t) => {92 const actionMock = t.mock.fn();93 program.action(actionMock);94 program.parse(['node', 'test']);95 const callArgs = actionMock.mock.calls[0].arguments;96 assert.equal(callArgs[0], undefined);97 assert.equal(callArgs[1], program.opts());98 assert.equal(callArgs[2], program);90 describe('when .action on program without optional argument supplied then action called', () => {91 getTestCases('[file]').forEach(([methodName, program]) => {92 test(`via ${methodName}`, (t) => {93 const actionMock = t.mock.fn();94 program.action(actionMock);95 program.parse(['node', 'test']);96 const callArgs = actionMock.mock.calls[0].arguments;97 assert.equal(callArgs[0], undefined);98 assert.equal(callArgs[1], program.opts());99 assert.equal(callArgs[2], program);100 });101 });102 });101});103103describe('when .action on program with optional argument and subcommand and program argument then program action called', () => {104 getTestCases('[file]').forEach(([methodName, program]) => {105 test(`via ${methodName}`, (t) => {106 const actionMock = t.mock.fn();107 program.action(actionMock);108 program.command('subcommand');104 describe('when .action on program with optional argument and subcommand and program argument then program action called', () => {105 getTestCases('[file]').forEach(([methodName, program]) => {106 test(`via ${methodName}`, (t) => {107 const actionMock = t.mock.fn();108 program.action(actionMock);109 program.command('subcommand');110110 program.parse(['node', 'test', 'a']);111 program.parse(['node', 'test', 'a']);112112 const callArgs = actionMock.mock.calls[0].arguments;113 assert.equal(callArgs[0], 'a');114 assert.equal(callArgs[1], program.opts());115 assert.equal(callArgs[2], program);113 const callArgs = actionMock.mock.calls[0].arguments;114 assert.equal(callArgs[0], 'a');115 assert.equal(callArgs[1], program.opts());116 assert.equal(callArgs[2], program);117 });118 });119 });118});120120// Changes made in #1062 to allow this case121describe('when .action on program with optional argument and subcommand and no program argument then program action called', () => {122 getTestCases('[file]').forEach(([methodName, program]) => {123 test(`via ${methodName}`, (t) => {124 const actionMock = t.mock.fn();125 program.action(actionMock);126 program.command('subcommand');121 // Changes made in #1062 to allow this case122 describe('when .action on program with optional argument and subcommand and no program argument then program action called', () => {123 getTestCases('[file]').forEach(([methodName, program]) => {124 test(`via ${methodName}`, (t) => {125 const actionMock = t.mock.fn();126 program.action(actionMock);127 program.command('subcommand');128128 program.parse(['node', 'test']);129 program.parse(['node', 'test']);130130 const callArgs = actionMock.mock.calls[0].arguments;131 assert.equal(callArgs[0], undefined);132 assert.equal(callArgs[1], program.opts());133 assert.equal(callArgs[2], program);131 const callArgs = actionMock.mock.calls[0].arguments;132 assert.equal(callArgs[0], undefined);133 assert.equal(callArgs[1], program.opts());134 assert.equal(callArgs[2], program);135 });136 });137 });136});138138test('when action is async then can await parseAsync', async () => {139 let asyncFinished = false;140 async function delay() {141 await new Promise((resolve) => setTimeout(resolve, 100));142 asyncFinished = true;143 }144 const program = new commander.Command();145 program.action(delay);139 test('when action is async then can await parseAsync', async () => {140 let asyncFinished = false;141 async function delay() {142 await new Promise((resolve) => setTimeout(resolve, 100));143 asyncFinished = true;144 }145 const program = new commander.Command();146 program.action(delay);147147 const later = program.parseAsync(['node', 'test']);148 assert.equal(asyncFinished, false);149 await later;150 assert.equal(asyncFinished, true);151});148 const later = program.parseAsync(['node', 'test']);149 assert.equal(asyncFinished, false);150 await later;151 assert.equal(asyncFinished, true);152 });153153function getTestCases(arg) {154 const withArguments = createTestCommand().arguments(arg);155 const withArgument = createTestCommand().argument(arg);156 const withAddArgument = createTestCommand().addArgument(157 new commander.Argument(arg),158 );159 return [160 ['.arguments', withArguments],161 ['.argument', withArgument],162 ['.addArgument', withAddArgument],163 ];164}154 function getTestCases(arg) {155 const withArguments = createTestCommand().arguments(arg);156 const withArgument = createTestCommand().argument(arg);157 const withAddArgument = createTestCommand().addArgument(158 new commander.Argument(arg),159 );160 return [161 ['.arguments', withArguments],162 ['.argument', withArgument],163 ['.addArgument', withAddArgument],164 ];165 }166});
modified:tests/command.addCommand.test.js+47 added-45 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Command.addCommand()', () => {5// simple sanity check subcommand works6test('when addCommand and specify subcommand then called', (t) => {7 const program = new commander.Command();8 const leafAction = t.mock.fn();9 const sub = new commander.Command();10 sub.name('sub').action(leafAction);11 program.addCommand(sub);6 // simple sanity check subcommand works7 test('when addCommand and specify subcommand then called', (t) => {8 const program = new commander.Command();9 const leafAction = t.mock.fn();10 const sub = new commander.Command();11 sub.name('sub').action(leafAction);12 program.addCommand(sub);1313 program.parse('node test.js sub'.split(' '));14 assert.equal(leafAction.mock.callCount(), 1);15});14 program.parse('node test.js sub'.split(' '));15 assert.equal(leafAction.mock.callCount(), 1);16 });1717test('when commands added using .addCommand and .command then internals similar', () => {18 const program1 = new commander.Command();19 program1.command('sub');20 const program2 = new commander.Command();21 program2.addCommand(new commander.Command('sub'));18 test('when commands added using .addCommand and .command then internals similar', () => {19 const program1 = new commander.Command();20 program1.command('sub');21 const program2 = new commander.Command();22 program2.addCommand(new commander.Command('sub'));2323 // This is a bit of a cheat to check using .addCommand() produces similar result to .command(),24 // since .command() is well tested and understood.24 // This is a bit of a cheat to check using .addCommand() produces similar result to .command(),25 // since .command() is well tested and understood.2626 const cmd1 = program1.commands[0];27 const cmd2 = program2.commands[0];28 assert.equal(cmd1.parent, program1);29 assert.equal(cmd2.parent, program2);27 const cmd1 = program1.commands[0];28 const cmd2 = program2.commands[0];29 assert.equal(cmd1.parent, program1);30 assert.equal(cmd2.parent, program2);3131 for (const key of Object.keys(cmd1)) {32 switch (typeof cmd1[key]) {33 case 'string':34 case 'boolean':35 case 'number':36 case 'undefined':37 // Compare values in a way that will be readable in test failure message.38 assert.equal(`${key}:${cmd1[key]}`, `${key}:${cmd2[key]}`);39 break;32 for (const key of Object.keys(cmd1)) {33 switch (typeof cmd1[key]) {34 case 'string':35 case 'boolean':36 case 'number':37 case 'undefined':38 // Compare values in a way that will be readable in test failure message.39 assert.equal(`${key}:${cmd1[key]}`, `${key}:${cmd2[key]}`);40 break;41 }42 }41 }42});43 });4444test('when command without name passed to .addCommand then throw', () => {45 const program = new commander.Command();46 const cmd = new commander.Command();47 assert.throws(() => {48 program.addCommand(cmd);45 test('when command without name passed to .addCommand then throw', () => {46 const program = new commander.Command();47 const cmd = new commander.Command();48 assert.throws(() => {49 program.addCommand(cmd);50 });51 });50});5252test('when executable command with custom executableFile passed to .addCommand then ok', () => {53 const program = new commander.Command();54 const cmd = new commander.Command('sub');55 cmd.command('exec', 'exec description', { executableFile: 'custom' });56 assert.doesNotThrow(() => {57 program.addCommand(cmd);53 test('when executable command with custom executableFile passed to .addCommand then ok', () => {54 const program = new commander.Command();55 const cmd = new commander.Command('sub');56 cmd.command('exec', 'exec description', { executableFile: 'custom' });57 assert.doesNotThrow(() => {58 program.addCommand(cmd);59 });60 });61});
modified:tests/command.addHelpOption.test.js+1 added-1 removed
3 unmodified lines
4const assert = require('node:assert/strict');56// More complete tests are in command.helpOption.test.js.78describe('addHelpOption', () => {8describe('Command.addHelpOption()', () => {9 test('when addHelpOption has custom flags then custom short flag invokes help', () => {10 const program = createTestCommand();11 program.addHelpOption(new Option('-c,--custom-help'));12
29 unmodified lines
modified:tests/command.addHelpText.test.js+3 added-3 removed
2 unmodified lines
3const assert = require('node:assert/strict');45// Using outputHelp to simplify testing.67describe('program calls to addHelpText', () => {7describe('Command.addHelpText(): program calls to addHelpText', () => {8 let writeSpy;910 beforeEach((t) => {11 writeSpy = t.mock.method(process.stdout, 'write', () => {});
88 unmodified lines
100 });101 });102});103104describe('program and subcommand calls to addHelpText', () => {104describe('Command.addHelpText(): program and subcommand calls to addHelpText', () => {105 let writeSpy;106107 beforeEach((t) => {108 writeSpy = t.mock.method(process.stdout, 'write', () => {});
35 unmodified lines
144 assert.equal(testMock.mock.callCount(), 1);145 });146});147148describe('context checks with full parse', () => {148describe('Command.addHelpText(): context checks with full parse', () => {149 let stdoutSpy;150 let stderrSpy;151152 beforeEach((t) => {
87 unmodified lines
modified:tests/command.alias.test.js+71 added-69 removed
3 unmodified lines
45// Running alias commands is tested in command.executableSubcommand.lookup.test.js6// Test various other behaviours for .alias78describe('Command aliases using .alias() and .aliases()', () => {8test('when command has alias then appears in help', () => {9 const program = new commander.Command();10 program.command('info [thing]').alias('i');11 const helpInformation = program.helpInformation();12 assert.match(helpInformation, /info\|i/);13});9 test('when command has alias then appears in help', () => {10 const program = new commander.Command();11 program.command('info [thing]').alias('i');12 const helpInformation = program.helpInformation();13 assert.match(helpInformation, /info\|i/);14 });1515test('when command has aliases added separately then only first appears in help', () => {16 const program = new commander.Command();17 program.command('list [thing]').alias('ls').alias('dir');18 const helpInformation = program.helpInformation();19 assert.match(helpInformation, /list\|ls /);20});16 test('when command has aliases added separately then only first appears in help', () => {17 const program = new commander.Command();18 program.command('list [thing]').alias('ls').alias('dir');19 const helpInformation = program.helpInformation();20 assert.match(helpInformation, /list\|ls /);21 });2222test('when command has aliases then only first appears in help', () => {23 const program = new commander.Command();24 program.command('list [thing]').aliases(['ls', 'dir']);25 const helpInformation = program.helpInformation();26 assert.match(helpInformation, /list\|ls /);27});23 test('when command has aliases then only first appears in help', () => {24 const program = new commander.Command();25 program.command('list [thing]').aliases(['ls', 'dir']);26 const helpInformation = program.helpInformation();27 assert.match(helpInformation, /list\|ls /);28 });2929test('when command name = alias then error', () => {30 const program = new commander.Command();31 assert.throws(32 () => {33 program.command('fail').alias('fail');34 },35 { message: "Command alias can't be the same as its name" },36 );37});30 test('when command name = alias then error', () => {31 const program = new commander.Command();32 assert.throws(33 () => {34 program.command('fail').alias('fail');35 },36 { message: "Command alias can't be the same as its name" },37 );38 });3939test('when use alias then action handler called', (t) => {40 const program = new commander.Command();41 const actionMock = t.mock.fn();42 program.command('list').alias('ls').action(actionMock);43 program.parse(['ls'], { from: 'user' });44 assert.equal(actionMock.mock.callCount(), 1);45});40 test('when use alias then action handler called', (t) => {41 const program = new commander.Command();42 const actionMock = t.mock.fn();43 program.command('list').alias('ls').action(actionMock);44 program.parse(['ls'], { from: 'user' });45 assert.equal(actionMock.mock.callCount(), 1);46 });4747test('when use second alias added separately then action handler called', (t) => {48 const program = new commander.Command();49 const actionMock = t.mock.fn();50 program.command('list').alias('ls').alias('dir').action(actionMock);51 program.parse(['dir'], { from: 'user' });52 assert.equal(actionMock.mock.callCount(), 1);53});48 test('when use second alias added separately then action handler called', (t) => {49 const program = new commander.Command();50 const actionMock = t.mock.fn();51 program.command('list').alias('ls').alias('dir').action(actionMock);52 program.parse(['dir'], { from: 'user' });53 assert.equal(actionMock.mock.callCount(), 1);54 });5555test('when use second of aliases then action handler called', (t) => {56 const program = new commander.Command();57 const actionMock = t.mock.fn();58 program.command('list').aliases(['ls', 'dir']).action(actionMock);59 program.parse(['dir'], { from: 'user' });60 assert.equal(actionMock.mock.callCount(), 1);61});56 test('when use second of aliases then action handler called', (t) => {57 const program = new commander.Command();58 const actionMock = t.mock.fn();59 program.command('list').aliases(['ls', 'dir']).action(actionMock);60 program.parse(['dir'], { from: 'user' });61 assert.equal(actionMock.mock.callCount(), 1);62 });6363test('when set alias then can get alias', () => {64 const program = new commander.Command();65 const alias = 'abcde';66 program.alias(alias);67 assert.equal(program.alias(), alias);68});64 test('when set alias then can get alias', () => {65 const program = new commander.Command();66 const alias = 'abcde';67 program.alias(alias);68 assert.equal(program.alias(), alias);69 });7070test('when set aliases then can get aliases', () => {71 const program = new commander.Command();72 const aliases = ['a', 'b'];73 program.aliases(aliases);74 assert.deepEqual(program.aliases(), aliases);75});71 test('when set aliases then can get aliases', () => {72 const program = new commander.Command();73 const aliases = ['a', 'b'];74 program.aliases(aliases);75 assert.deepEqual(program.aliases(), aliases);76 });7777test('when set alias on executable then can get alias', () => {78 const program = new commander.Command();79 const alias = 'abcde';80 program.command('external', 'external command').alias(alias);81 assert.equal(program.commands[0].alias(), alias);78 test('when set alias on executable then can get alias', () => {79 const program = new commander.Command();80 const alias = 'abcde';81 program.command('external', 'external command').alias(alias);82 assert.equal(program.commands[0].alias(), alias);83 });84});8584describe('aliases parameter is treated as readonly, per TypeScript declaration', () => {85 test('when aliases called then parameter does not change', () => {86describe('Command.aliases() parameter is treated as readonly, per TypeScript declaration', () => {87 test('when .aliases() called then parameter does not change', () => {88 // Unlikely this could break, but check the API we are declaring in TypeScript.89 const original = ['b', 'bld'];90 const param = original.slice();91 new commander.Command('build').aliases(param);92 assert.deepEqual(param, original);93 });9493 test('when aliases called and aliases later changed then parameter does not change', () => {95 test('when .aliases() called and aliases later changed then parameter does not change', () => {96 const original = ['b', 'bld'];97 const param = original.slice();98 const cmd = new commander.Command('build').aliases(param);99 cmd.alias('BBB');100 assert.deepEqual(param, original);101 });102101 test('when aliases called and parameter later changed then aliases does not change', () => {103 test('when .aliases() called and parameter later changed then aliases does not change', () => {104 const original = ['b', 'bld'];105 const param = original.slice();106 const cmd = new commander.Command('build').aliases(param);107 param.length = 0;
3 unmodified lines
modified:tests/command.allowExcessArguments.test.js+1 added-1 removed
2 unmodified lines
3const assert = require('node:assert/strict');45// Not testing output, just testing whether an error is detected.67describe('allowExcessArguments', () => {7describe('Command.allowExcessArguments()', () => {8 const cases = [true, false];9 cases.forEach((hasActionHandler) => {10 describe(`when ${hasActionHandler ? 'has' : 'no'} action handler`, () => {11 function configureCommand(cmd) {
104 unmodified lines
modified:tests/command.allowUnknownOption.test.js+1 added-1 removed
2 unmodified lines
3const assert = require('node:assert/strict');45// Not testing output, just testing whether an error is detected.67describe('allowUnknownOption', () => {7describe('Command.allowUnknownOption()', () => {8 test('when specify unknown program option then error', () => {9 const program = createTestCommand();10 program.option('-p, --pepper', 'add pepper');11
68 unmodified lines
modified:tests/command.argumentVariations.test.js+104 added-95 removed
3 unmodified lines
45// Do some low-level checks that the multiple ways of specifying command arguments produce same internal result,6// and not exhaustively testing all methods elsewhere.78describe('Command arguments added using different methods', () => {8describe('when add "<arg>" then argument required', () => {9 getSingleArgCases('<explicit-required>').forEach(([methodName, cmd]) => {10 test(`using ${methodName}`, () => {11 const argument = cmd.registeredArguments[0];12 assert.equal(argument._name, 'explicit-required');13 assert.equal(argument.required, true);14 assert.equal(argument.variadic, false);15 assert.equal(argument.description, '');9 describe('when add "<arg>" then argument required', () => {10 getSingleArgCases('<explicit-required>').forEach(([methodName, cmd]) => {11 test(`using ${methodName}`, () => {12 const argument = cmd.registeredArguments[0];13 assert.equal(argument._name, 'explicit-required');14 assert.equal(argument.required, true);15 assert.equal(argument.variadic, false);16 assert.equal(argument.description, '');17 });18 });19 });18});2020describe('when add "arg" then argument required', () => {21 getSingleArgCases('implicit-required').forEach(([methodName, cmd]) => {22 test(`using ${methodName}`, () => {23 const argument = cmd.registeredArguments[0];24 assert.equal(argument._name, 'implicit-required');25 assert.equal(argument.required, true);26 assert.equal(argument.variadic, false);27 assert.equal(argument.description, '');21 describe('when add "arg" then argument required', () => {22 getSingleArgCases('implicit-required').forEach(([methodName, cmd]) => {23 test(`using ${methodName}`, () => {24 const argument = cmd.registeredArguments[0];25 assert.equal(argument._name, 'implicit-required');26 assert.equal(argument.required, true);27 assert.equal(argument.variadic, false);28 assert.equal(argument.description, '');29 });30 });31 });30});3232describe('when add "[arg]" then argument optional', () => {33 getSingleArgCases('[optional]').forEach(([methodName, cmd]) => {34 test(`using ${methodName}`, () => {35 const argument = cmd.registeredArguments[0];36 assert.equal(argument._name, 'optional');37 assert.equal(argument.required, false);38 assert.equal(argument.variadic, false);39 assert.equal(argument.description, '');33 describe('when add "[arg]" then argument optional', () => {34 getSingleArgCases('[optional]').forEach(([methodName, cmd]) => {35 test(`using ${methodName}`, () => {36 const argument = cmd.registeredArguments[0];37 assert.equal(argument._name, 'optional');38 assert.equal(argument.required, false);39 assert.equal(argument.variadic, false);40 assert.equal(argument.description, '');41 });42 });43 });42});4444describe('when add "<arg...>" then argument required and variadic', () => {45 getSingleArgCases('<explicit-required...>').forEach(([methodName, cmd]) => {46 test(`using ${methodName}`, () => {47 const argument = cmd.registeredArguments[0];48 assert.equal(argument._name, 'explicit-required');49 assert.equal(argument.required, true);50 assert.equal(argument.variadic, true);51 assert.equal(argument.description, '');45 describe('when add "<arg...>" then argument required and variadic', () => {46 getSingleArgCases('<explicit-required...>').forEach(([methodName, cmd]) => {47 test(`using ${methodName}`, () => {48 const argument = cmd.registeredArguments[0];49 assert.equal(argument._name, 'explicit-required');50 assert.equal(argument.required, true);51 assert.equal(argument.variadic, true);52 assert.equal(argument.description, '');53 });54 });55 });54});5656describe('when add "arg..." then argument required and variadic', () => {57 getSingleArgCases('implicit-required...').forEach(([methodName, cmd]) => {58 test(`using ${methodName}`, () => {59 const argument = cmd.registeredArguments[0];60 assert.equal(argument._name, 'implicit-required');61 assert.equal(argument.required, true);62 assert.equal(argument.variadic, true);63 assert.equal(argument.description, '');57 describe('when add "arg..." then argument required and variadic', () => {58 getSingleArgCases('implicit-required...').forEach(([methodName, cmd]) => {59 test(`using ${methodName}`, () => {60 const argument = cmd.registeredArguments[0];61 assert.equal(argument._name, 'implicit-required');62 assert.equal(argument.required, true);63 assert.equal(argument.variadic, true);64 assert.equal(argument.description, '');65 });66 });67 });66});6868describe('when add "[arg...]" then argument optional and variadic', () => {69 getSingleArgCases('[optional...]').forEach(([methodName, cmd]) => {70 test(`using ${methodName}`, () => {71 const argument = cmd.registeredArguments[0];72 assert.equal(argument._name, 'optional');73 assert.equal(argument.required, false);74 assert.equal(argument.variadic, true);75 assert.equal(argument.description, '');69 describe('when add "[arg...]" then argument optional and variadic', () => {70 getSingleArgCases('[optional...]').forEach(([methodName, cmd]) => {71 test(`using ${methodName}`, () => {72 const argument = cmd.registeredArguments[0];73 assert.equal(argument._name, 'optional');74 assert.equal(argument.required, false);75 assert.equal(argument.variadic, true);76 assert.equal(argument.description, '');77 });78 });79 });78});8080function getSingleArgCases(arg) {81 return [82 ['.arguments', new commander.Command().arguments(arg)],83 ['.argument', new commander.Command().argument(arg)],84 [85 '.addArgument',86 new commander.Command('add-argument').addArgument(87 new commander.Argument(arg),88 ),89 ],90 ['.command', new commander.Command().command(`command ${arg}`)],91 ];92}81 function getSingleArgCases(arg) {82 return [83 ['.arguments', new commander.Command().arguments(arg)],84 ['.argument', new commander.Command().argument(arg)],85 [86 '.addArgument',87 new commander.Command('add-argument').addArgument(88 new commander.Argument(arg),89 ),90 ],91 ['.command', new commander.Command().command(`command ${arg}`)],92 ];93 }9494describe('when add two arguments then two arguments', () => {95 getMultipleArgCases('<first>', '[second]').forEach(([methodName, cmd]) => {96 test(`using ${methodName}`, () => {97 assert.equal(cmd.registeredArguments[0].name(), 'first');98 assert.equal(cmd.registeredArguments[1].name(), 'second');95 describe('when add two arguments then two arguments', () => {96 getMultipleArgCases('<first>', '[second]').forEach(([methodName, cmd]) => {97 test(`using ${methodName}`, () => {98 assert.equal(cmd.registeredArguments[0].name(), 'first');99 assert.equal(cmd.registeredArguments[1].name(), 'second');100 });101 });102 });101});103103function getMultipleArgCases(arg1, arg2) {104 return [105 ['.arguments', new commander.Command().arguments(`${arg1} ${arg2}`)],106 ['.argument', new commander.Command().argument(arg1).argument(arg2)],107 [108 '.addArgument',109 new commander.Command('add-argument')110 .addArgument(new commander.Argument(arg1))111 .addArgument(new commander.Argument(arg2)),112 ],113 ['.command', new commander.Command().command(`command ${arg1} ${arg2}`)],114 ];115}104 function getMultipleArgCases(arg1, arg2) {105 return [106 ['.arguments', new commander.Command().arguments(`${arg1} ${arg2}`)],107 ['.argument', new commander.Command().argument(arg1).argument(arg2)],108 [109 '.addArgument',110 new commander.Command('add-argument')111 .addArgument(new commander.Argument(arg1))112 .addArgument(new commander.Argument(arg2)),113 ],114 ['.command', new commander.Command().command(`command ${arg1} ${arg2}`)],115 ];116 }117117test('when add arguments using multiple methods then all added', () => {118 // This is not a key use case, but explicitly test that additive behaviour.119 const program = new commander.Command();120 const cmd = program.command('sub <arg1> <arg2>');121 cmd.arguments('<arg3> <arg4>');122 cmd.argument('<arg5>');123 cmd.addArgument(new commander.Argument('arg6'));124 const argNames = cmd.registeredArguments.map((arg) => arg.name());125 assert.deepEqual(argNames, ['arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6']);118 test('when add arguments using multiple methods then all added', () => {119 // This is not a key use case, but explicitly test that additive behaviour.120 const program = new commander.Command();121 const cmd = program.command('sub <arg1> <arg2>');122 cmd.arguments('<arg3> <arg4>');123 cmd.argument('<arg5>');124 cmd.addArgument(new commander.Argument('arg6'));125 const argNames = cmd.registeredArguments.map((arg) => arg.name());126 assert.deepEqual(argNames, [127 'arg1',128 'arg2',129 'arg3',130 'arg4',131 'arg5',132 'arg6',133 ]);134 });135});
modified:tests/command.asterisk.test.js+2 added-2 removed
11 unmodified lines
12// due to an example in the README.13//14// Historical: the event 'command:*' used to also be shared by the action handler on the program.1516describe(".command('*')", () => {16describe("Command.command('*')", () => {17 test('when no arguments then asterisk action not called', (t) => {18 const mockAction = t.mock.fn();19 const program = createTestCommand();20 program.command('*').action(mockAction);
63 unmodified lines
84 });85});8687// Test .on explicitly rather than assuming covered by .command88describe(".on('command:*')", () => {88describe("Command.on('command:*')", () => {89 test('when no arguments then listener not called', (t) => {90 const mockAction = t.mock.fn();91 const program = new commander.Command();92 program.on('command:*', mockAction);
42 unmodified lines
modified:tests/command.configureHelp.test.js+33 added-31 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Command.configureHelp()', () => {5test('when configure program then affects program helpInformation', () => {6 const program = new commander.Command();7 program.configureHelp({8 formatHelp: () => {9 return 'custom';10 },6 test('when configure program then affects program helpInformation', () => {7 const program = new commander.Command();8 program.configureHelp({9 formatHelp: () => {10 return 'custom';11 },12 });13 assert.equal(program.helpInformation(), 'custom');14 });12 assert.equal(program.helpInformation(), 'custom');13});1515test('when configure program then affects subcommand helpInformation', () => {16 const program = new commander.Command();17 program.configureHelp({18 formatHelp: () => {19 return 'custom';20 },16 test('when configure program then affects subcommand helpInformation', () => {17 const program = new commander.Command();18 program.configureHelp({19 formatHelp: () => {20 return 'custom';21 },22 });23 const sub = program.command('sub');24 assert.equal(sub.helpInformation(), 'custom');25 });22 const sub = program.command('sub');23 assert.equal(sub.helpInformation(), 'custom');24});2626test('when configure with unknown property then createHelp has unknown property', () => {27 const program = new commander.Command();28 program.configureHelp({ mySecretValue: 'secret' });29 assert.equal(program.createHelp().mySecretValue, 'secret');30});27 test('when configure with unknown property then createHelp has unknown property', () => {28 const program = new commander.Command();29 program.configureHelp({ mySecretValue: 'secret' });30 assert.equal(program.createHelp().mySecretValue, 'secret');31 });3232test('when configure with unknown property then helper passed to formatHelp has unknown property', () => {33 const program = new commander.Command();34 program.configureHelp({35 mySecretValue: 'secret',36 formatHelp: (cmd, helper) => {37 return helper.mySecretValue;38 },33 test('when configure with unknown property then helper passed to formatHelp has unknown property', () => {34 const program = new commander.Command();35 program.configureHelp({36 mySecretValue: 'secret',37 formatHelp: (cmd, helper) => {38 return helper.mySecretValue;39 },40 });41 assert.equal(program.helpInformation(), 'secret');42 });40 assert.equal(program.helpInformation(), 'secret');43});
modified:tests/command.configureOutput.test.js+276 added-274 removed
1 unmodified line
2const assert = require('node:assert/strict');3const commander = require('../');4const process = require('node:process');56describe('Command.configureOutput()', () => {6test('when default writeErr() then error on stderr', (t) => {7 const writeSpy = t.mock.method(process.stderr, 'write', () => {});8 const program = new commander.Command();9 program.exitOverride();7 test('when default writeErr() then error on stderr', (t) => {8 const writeSpy = t.mock.method(process.stderr, 'write', () => {});9 const program = new commander.Command();10 program.exitOverride();1111 try {12 program.parse(['--unknown'], { from: 'user' });13 } catch (err) {14 /* empty */15 }12 try {13 program.parse(['--unknown'], { from: 'user' });14 } catch (err) {15 /* empty */16 }1717 assert.equal(writeSpy.mock.callCount(), 1);18});18 assert.equal(writeSpy.mock.callCount(), 1);19 });2020test('when custom writeErr() then error on custom output', (t) => {21 const writeSpy = t.mock.method(process.stderr, 'write', () => {});22 const customWrite = t.mock.fn();23 const program = new commander.Command();24 program.exitOverride().configureOutput({ writeErr: customWrite });21 test('when custom writeErr() then error on custom output', (t) => {22 const writeSpy = t.mock.method(process.stderr, 'write', () => {});23 const customWrite = t.mock.fn();24 const program = new commander.Command();25 program.exitOverride().configureOutput({ writeErr: customWrite });2626 try {27 program.parse(['--unknown'], { from: 'user' });28 } catch (err) {29 /* empty */30 }27 try {28 program.parse(['--unknown'], { from: 'user' });29 } catch (err) {30 /* empty */31 }3232 assert.equal(writeSpy.mock.callCount(), 0);33 assert.equal(customWrite.mock.callCount(), 1);34});3536test('when default write() then version on stdout', (t) => {37 const writeSpy = t.mock.method(process.stdout, 'write', () => {});38 const program = new commander.Command();39 program.exitOverride().version('1.2.3');4041 assert.throws(() => {42 program.parse(['--version'], { from: 'user' });33 assert.equal(writeSpy.mock.callCount(), 0);34 assert.equal(customWrite.mock.callCount(), 1);35 });3645 assert.equal(writeSpy.mock.callCount(), 1);46});37 test('when default write() then version on stdout', (t) => {38 const writeSpy = t.mock.method(process.stdout, 'write', () => {});39 const program = new commander.Command();40 program.exitOverride().version('1.2.3');4148test('when custom write() then version on custom output', (t) => {49 const writeSpy = t.mock.method(process.stdout, 'write', () => {});50 const customWrite = t.mock.fn();51 const program = new commander.Command();52 program53 .exitOverride()54 .version('1.2.3')55 .configureOutput({ writeOut: customWrite });42 assert.throws(() => {43 program.parse(['--version'], { from: 'user' });44 });4557 assert.throws(() => {58 program.parse(['--version'], { from: 'user' });46 assert.equal(writeSpy.mock.callCount(), 1);47 });4861 assert.equal(writeSpy.mock.callCount(), 0);62 assert.equal(customWrite.mock.callCount(), 1);63});49 test('when custom write() then version on custom output', (t) => {50 const writeSpy = t.mock.method(process.stdout, 'write', () => {});51 const customWrite = t.mock.fn();52 const program = new commander.Command();53 program54 .exitOverride()55 .version('1.2.3')56 .configureOutput({ writeOut: customWrite });5765test('when default write() then help on stdout', (t) => {66 const writeSpy = t.mock.method(process.stdout, 'write', () => {});67 const program = new commander.Command();68 program.outputHelp();58 assert.throws(() => {59 program.parse(['--version'], { from: 'user' });60 });6170 assert.equal(writeSpy.mock.callCount(), 1);71});62 assert.equal(writeSpy.mock.callCount(), 0);63 assert.equal(customWrite.mock.callCount(), 1);64 });6573test('when custom write() then help error on custom output', (t) => {74 const writeSpy = t.mock.method(process.stdout, 'write', () => {});75 const customWrite = t.mock.fn();76 const program = new commander.Command();77 program.configureOutput({ writeOut: customWrite });78 program.outputHelp();66 test('when default write() then help on stdout', (t) => {67 const writeSpy = t.mock.method(process.stdout, 'write', () => {});68 const program = new commander.Command();69 program.outputHelp();7080 assert.equal(writeSpy.mock.callCount(), 0);81 assert.equal(customWrite.mock.callCount(), 1);82});71 assert.equal(writeSpy.mock.callCount(), 1);72 });7384test('when default writeErr then help error on stderr', (t) => {85 const writeSpy = t.mock.method(process.stderr, 'write', () => {});86 const program = new commander.Command();87 program.outputHelp({ error: true });74 test('when custom write() then help error on custom output', (t) => {75 const writeSpy = t.mock.method(process.stdout, 'write', () => {});76 const customWrite = t.mock.fn();77 const program = new commander.Command();78 program.configureOutput({ writeOut: customWrite });79 program.outputHelp();8089 assert.equal(writeSpy.mock.callCount(), 1);90});81 assert.equal(writeSpy.mock.callCount(), 0);82 assert.equal(customWrite.mock.callCount(), 1);83 });8492test('when custom writeErr then help error on custom output', (t) => {93 const writeSpy = t.mock.method(process.stderr, 'write', () => {});94 const customWrite = t.mock.fn();95 const program = new commander.Command();96 program.configureOutput({ writeErr: customWrite });97 program.outputHelp({ error: true });85 test('when default writeErr then help error on stderr', (t) => {86 const writeSpy = t.mock.method(process.stderr, 'write', () => {});87 const program = new commander.Command();88 program.outputHelp({ error: true });8999 assert.equal(writeSpy.mock.callCount(), 0);100 assert.equal(customWrite.mock.callCount(), 1);101});90 assert.equal(writeSpy.mock.callCount(), 1);91 });92103test('when default getOutHelpWidth then help helpWidth from stdout', () => {104 const expectedColumns = 123;105 const holdIsTTY = process.stdout.isTTY;106 const holdColumns = process.stdout.columns;107 let helpWidth;93 test('when custom writeErr then help error on custom output', (t) => {94 const writeSpy = t.mock.method(process.stderr, 'write', () => {});95 const customWrite = t.mock.fn();96 const program = new commander.Command();97 program.configureOutput({ writeErr: customWrite });98 program.outputHelp({ error: true });99109 process.stderr.isTTY = true;110 process.stdout.columns = expectedColumns;111 process.stdout.isTTY = true;112 const program = new commander.Command();113 program.configureHelp({114 formatHelp: (cmd, helper) => {115 helpWidth = helper.helpWidth;116 return '';117 },100 assert.equal(writeSpy.mock.callCount(), 0);101 assert.equal(customWrite.mock.callCount(), 1);102 });119 program.outputHelp();103121 assert.equal(helpWidth, expectedColumns);122 process.stdout.columns = holdColumns;123 process.stdout.isTTY = holdIsTTY;124});104 test('when default getOutHelpWidth then help helpWidth from stdout', () => {105 const expectedColumns = 123;106 const holdIsTTY = process.stdout.isTTY;107 const holdColumns = process.stdout.columns;108 let helpWidth;109126test('when custom getOutHelpWidth then help helpWidth custom', () => {127 const expectedColumns = 123;128 let helpWidth;129130 const program = new commander.Command();131 program132 .configureHelp({110 process.stderr.isTTY = true;111 process.stdout.columns = expectedColumns;112 process.stdout.isTTY = true;113 const program = new commander.Command();114 program.configureHelp({115 formatHelp: (cmd, helper) => {116 helpWidth = helper.helpWidth;117 return '';118 },137 })138 .configureOutput({139 getOutHelpWidth: () => expectedColumns,119 });141 program.outputHelp();120 program.outputHelp();121143 assert.equal(helpWidth, expectedColumns);144});122 assert.equal(helpWidth, expectedColumns);123 process.stdout.columns = holdColumns;124 process.stdout.isTTY = holdIsTTY;125 });126146test('when default getErrHelpWidth then help error helpWidth from stderr', () => {147 const expectedColumns = 123;148 const holdIsTTY = process.stderr.isTTY;149 const holdColumns = process.stderr.columns;150 let helpWidth;127 test('when custom getOutHelpWidth then help helpWidth custom', () => {128 const expectedColumns = 123;129 let helpWidth;130152 process.stderr.isTTY = true;153 process.stderr.columns = expectedColumns;154 const program = new commander.Command();155 program.configureHelp({156 formatHelp: (cmd, helper) => {157 helpWidth = helper.helpWidth;158 return '';159 },131 const program = new commander.Command();132 program133 .configureHelp({134 formatHelp: (cmd, helper) => {135 helpWidth = helper.helpWidth;136 return '';137 },138 })139 .configureOutput({140 getOutHelpWidth: () => expectedColumns,141 });142 program.outputHelp();143144 assert.equal(helpWidth, expectedColumns);145 });161 program.outputHelp({ error: true });146163 assert.equal(helpWidth, expectedColumns);164 process.stderr.isTTY = holdIsTTY;165 process.stderr.columns = holdColumns;166});147 test('when default getErrHelpWidth then help error helpWidth from stderr', () => {148 const expectedColumns = 123;149 const holdIsTTY = process.stderr.isTTY;150 const holdColumns = process.stderr.columns;151 let helpWidth;152168test('when custom getErrHelpWidth then help error helpWidth custom', () => {169 const expectedColumns = 123;170 let helpWidth;171172 const program = new commander.Command();173 program174 .configureHelp({153 process.stderr.isTTY = true;154 process.stderr.columns = expectedColumns;155 const program = new commander.Command();156 program.configureHelp({157 formatHelp: (cmd, helper) => {158 helpWidth = helper.helpWidth;159 return '';160 },179 })180 .configureOutput({181 getErrHelpWidth: () => expectedColumns,161 });183 program.outputHelp({ error: true });162 program.outputHelp({ error: true });163185 assert.equal(helpWidth, expectedColumns);186});164 assert.equal(helpWidth, expectedColumns);165 process.stderr.isTTY = holdIsTTY;166 process.stderr.columns = holdColumns;167 });168188test('when custom getOutHelpWidth and configureHelp:helpWidth then help helpWidth from configureHelp', () => {189 const expectedColumns = 123;190 let helpWidth;169 test('when custom getErrHelpWidth then help error helpWidth custom', () => {170 const expectedColumns = 123;171 let helpWidth;172192 const program = new commander.Command();193 program194 .configureHelp({195 formatHelp: (cmd, helper) => {196 helpWidth = helper.helpWidth;197 return '';198 },199 helpWidth: expectedColumns,200 })201 .configureOutput({202 getOutHelpWidth: () => 999,203 });204 program.outputHelp();173 const program = new commander.Command();174 program175 .configureHelp({176 formatHelp: (cmd, helper) => {177 helpWidth = helper.helpWidth;178 return '';179 },180 })181 .configureOutput({182 getErrHelpWidth: () => expectedColumns,183 });184 program.outputHelp({ error: true });185206 assert.equal(helpWidth, expectedColumns);207});186 assert.equal(helpWidth, expectedColumns);187 });188209test('when custom getErrHelpWidth and configureHelp:helpWidth then help error helpWidth from configureHelp', () => {210 const expectedColumns = 123;211 let helpWidth;189 test('when custom getOutHelpWidth and configureHelp:helpWidth then help helpWidth from configureHelp', () => {190 const expectedColumns = 123;191 let helpWidth;192213 const program = new commander.Command();214 program215 .configureHelp({216 formatHelp: (cmd, helper) => {217 helpWidth = helper.helpWidth;218 return '';219 },220 helpWidth: expectedColumns,221 })222 .configureOutput({223 getErrHelpWidth: () => 999,224 });225 program.outputHelp({ error: true });193 const program = new commander.Command();194 program195 .configureHelp({196 formatHelp: (cmd, helper) => {197 helpWidth = helper.helpWidth;198 return '';199 },200 helpWidth: expectedColumns,201 })202 .configureOutput({203 getOutHelpWidth: () => 999,204 });205 program.outputHelp();206227 assert.equal(helpWidth, expectedColumns);228});207 assert.equal(helpWidth, expectedColumns);208 });209230test('when no custom setup and call formatHelp direct then effective helpWidth is fallback 80', () => {231 // Not an important case, but filling out testing coverage.232 const helper = new commander.Help();233 let wrapWidth;234 helper.boxWrap = (str, width) => {235 wrapWidth = wrapWidth ?? width;236 return '';237 };238 const program = new commander.Command()239 .description('description')240 .helpOption(false);241 helper.formatHelp(program, helper);242 assert.equal(wrapWidth, 80);243});210 test('when custom getErrHelpWidth and configureHelp:helpWidth then help error helpWidth from configureHelp', () => {211 const expectedColumns = 123;212 let helpWidth;213245test('when no custom setup and call formatItem direct then effective helpWidth is fallback 80', () => {246 // Not an important case, but filling out testing coverage.247 const helper = new commander.Help();248 let wrapWidth;249 helper.boxWrap = (str, width) => {250 wrapWidth = wrapWidth ?? width;251 return '';252 };214 const program = new commander.Command();215 program216 .configureHelp({217 formatHelp: (cmd, helper) => {218 helpWidth = helper.helpWidth;219 return '';220 },221 helpWidth: expectedColumns,222 })223 .configureOutput({224 getErrHelpWidth: () => 999,225 });226 program.outputHelp({ error: true });227254 const termWidth = 8;255 helper.formatItem('term', termWidth, 'description', helper);256 const itemIndent = 2;257 const spacerWidth = 2; // between term and description258 const remainingWidth = 80 - termWidth - spacerWidth - itemIndent;228 assert.equal(helpWidth, expectedColumns);229 });230231 test('when no custom setup and call formatHelp direct then effective helpWidth is fallback 80', () => {232 // Not an important case, but filling out testing coverage.233 const helper = new commander.Help();234 let wrapWidth;235 helper.boxWrap = (str, width) => {236 wrapWidth = wrapWidth ?? width;237 return '';238 };239 const program = new commander.Command()240 .description('description')241 .helpOption(false);242 helper.formatHelp(program, helper);260 assert.equal(wrapWidth, remainingWidth);261});243 assert.equal(wrapWidth, 80);244 });245263test('when set configureOutput then get configureOutput', (t) => {264 const outputOptions = {265 writeOut: t.mock.fn(),266 writeErr: t.mock.fn(),267 getOutHelpWidth: t.mock.fn(),268 getErrHelpWidth: t.mock.fn(),269 getOutHasColors: t.mock.fn(),270 getErrHasColors: t.mock.fn(),271 outputError: t.mock.fn(),272 stripColor: t.mock.fn(),273 };274 const program = new commander.Command();275 program.configureOutput(outputOptions);276 assert.deepEqual(program.configureOutput(), outputOptions);277});246 test('when no custom setup and call formatItem direct then effective helpWidth is fallback 80', () => {247 // Not an important case, but filling out testing coverage.248 const helper = new commander.Help();249 let wrapWidth;250 helper.boxWrap = (str, width) => {251 wrapWidth = wrapWidth ?? width;252 return '';253 };254279test('when custom outputErr and error then outputErr called', (t) => {280 const outputError = t.mock.fn();281 const program = new commander.Command();282 program.exitOverride().configureOutput({283 outputError,255 const termWidth = 8;256 helper.formatItem('term', termWidth, 'description', helper);257 const itemIndent = 2;258 const spacerWidth = 2; // between term and description259 const remainingWidth = 80 - termWidth - spacerWidth - itemIndent;260261 assert.equal(wrapWidth, remainingWidth);262 });263286 assert.throws(() => {287 program.parse(['--unknownOption'], { from: 'user' });264 test('when set configureOutput then get configureOutput', (t) => {265 const outputOptions = {266 writeOut: t.mock.fn(),267 writeErr: t.mock.fn(),268 getOutHelpWidth: t.mock.fn(),269 getErrHelpWidth: t.mock.fn(),270 getOutHasColors: t.mock.fn(),271 getErrHasColors: t.mock.fn(),272 outputError: t.mock.fn(),273 stripColor: t.mock.fn(),274 };275 const program = new commander.Command();276 program.configureOutput(outputOptions);277 assert.deepEqual(program.configureOutput(), outputOptions);278 });289 assert.equal(290 outputError.mock.calls[0].arguments[0],291 "error: unknown option '--unknownOption'\n",292 );293 assert.equal(294 outputError.mock.calls[0].arguments[1],295 program._outputConfiguration.writeErr,296 );297});279299test('when custom outputErr and writeErr and error then outputErr passed writeErr', (t) => {300 const writeErr = () => t.mock.fn();301 const outputError = t.mock.fn();302 const program = new commander.Command();303 program.exitOverride().configureOutput({ writeErr, outputError });280 test('when custom outputErr and error then outputErr called', (t) => {281 const outputError = t.mock.fn();282 const program = new commander.Command();283 program.exitOverride().configureOutput({284 outputError,285 });286305 assert.throws(() => {306 program.parse(['--unknownOption'], { from: 'user' });287 assert.throws(() => {288 program.parse(['--unknownOption'], { from: 'user' });289 });290 assert.equal(291 outputError.mock.calls[0].arguments[0],292 "error: unknown option '--unknownOption'\n",293 );294 assert.equal(295 outputError.mock.calls[0].arguments[1],296 program._outputConfiguration.writeErr,297 );298 });308 assert.equal(309 outputError.mock.calls[0].arguments[0],310 "error: unknown option '--unknownOption'\n",311 );312 assert.equal(outputError.mock.calls[0].arguments[1], writeErr);313});299315test('when configureOutput after copyInheritedSettings then original unchanged', () => {316 const program = new commander.Command();317 program.configureOutput({ getOutHelpWidth: () => 80 });318 const copy = program.createCommand('copy');319 copy.copyInheritedSettings(program);320 assert.equal(copy.configureOutput().getOutHelpWidth(), 80);321 copy.configureOutput({ getOutHelpWidth: () => 40 });322 assert.equal(copy.configureOutput().getOutHelpWidth(), 40);323 assert.equal(program.configureOutput().getOutHelpWidth(), 80);324});300 test('when custom outputErr and writeErr and error then outputErr passed writeErr', (t) => {301 const writeErr = () => t.mock.fn();302 const outputError = t.mock.fn();303 const program = new commander.Command();304 program.exitOverride().configureOutput({ writeErr, outputError });305326describe('environment variable tests', () => {327 [328 ['NO_COLOR', false],329 ['FORCE_COLOR', true],330 ['CLICOLOR_FORCE', true],331 ].forEach(([envvar, expected]) => {332 test(`when ${envvar} then getFooHasColors returns ${expected}`, () => {333 // Would like to vary process.istty too, but too hard, so tests here provide only partial cover.334 const holdEnv = process.env[envvar];335 process.env[envvar] = '1';336 const config = new commander.Command().configureOutput();337 assert.equal(config.getOutHasColors(), expected);338 assert.equal(config.getErrHasColors(), expected);339 if (holdEnv === undefined) delete process.env[envvar];340 else process.env[envvar] = holdEnv;306 assert.throws(() => {307 program.parse(['--unknownOption'], { from: 'user' });308 });309 assert.equal(310 outputError.mock.calls[0].arguments[0],311 "error: unknown option '--unknownOption'\n",312 );313 assert.equal(outputError.mock.calls[0].arguments[1], writeErr);314 });315316 test('when configureOutput after copyInheritedSettings then original unchanged', () => {317 const program = new commander.Command();318 program.configureOutput({ getOutHelpWidth: () => 80 });319 const copy = program.createCommand('copy');320 copy.copyInheritedSettings(program);321 assert.equal(copy.configureOutput().getOutHelpWidth(), 80);322 copy.configureOutput({ getOutHelpWidth: () => 40 });323 assert.equal(copy.configureOutput().getOutHelpWidth(), 40);324 assert.equal(program.configureOutput().getOutHelpWidth(), 80);325 });326327 describe('environment variable tests', () => {328 [329 ['NO_COLOR', false],330 ['FORCE_COLOR', true],331 ['CLICOLOR_FORCE', true],332 ].forEach(([envvar, expected]) => {333 test(`when ${envvar} then getFooHasColors returns ${expected}`, () => {334 // Would like to vary process.istty too, but too hard, so tests here provide only partial cover.335 const holdEnv = process.env[envvar];336 process.env[envvar] = '1';337 const config = new commander.Command().configureOutput();338 assert.equal(config.getOutHasColors(), expected);339 assert.equal(config.getErrHasColors(), expected);340 if (holdEnv === undefined) delete process.env[envvar];341 else process.env[envvar] = holdEnv;342 });343 });344 });345});
modified:tests/command.copySettings.test.js+14 added-14 removed
3 unmodified lines
45// Tests some private properties as simpler than pure tests of observable behaviours.6// Testing before and after values in some cases, to ensure value actually changes (when copied).78describe('Command.copyInheritedSettings()', () => {8test('when add subcommand with .command() then calls copyInheritedSettings from parent', (t) => {9 const program = new commander.Command();9 test('when add subcommand with .command() then calls copyInheritedSettings from parent', (t) => {10 const program = new commander.Command();1111 // This is a bit intrusive, but check expectation that copyInheritedSettings is called internally.12 const copySettingMock = t.mock.fn();13 program.createCommand = (name) => {14 const cmd = new commander.Command(name);15 cmd.copyInheritedSettings = copySettingMock;16 return cmd;17 };18 program.command('sub');12 // This is a bit intrusive, but check expectation that copyInheritedSettings is called internally.13 const copySettingMock = t.mock.fn();14 program.createCommand = (name) => {15 const cmd = new commander.Command(name);16 cmd.copyInheritedSettings = copySettingMock;17 return cmd;18 };19 program.command('sub');2020 const callArgs = copySettingMock.mock.calls[0].arguments;21 assert.equal(callArgs[0], program);22});21 const callArgs = copySettingMock.mock.calls[0].arguments;22 assert.equal(callArgs[0], program);23 });2424describe('copyInheritedSettings property tests', () => {25 test('when copyInheritedSettings then copies outputConfiguration(config)', () => {26 const source = new commander.Command();27 const cmd = new commander.Command();28
122 unmodified lines
modified:tests/command.createArgument.test.js+20 added-18 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45class MyArgument extends commander.Argument {6 constructor(name, description) {
12 unmodified lines
19 return new MyCommand(name);20 }21}2223describe('Command.createArgument() override in subclass', () => {23test('when override createArgument then used for argument()', () => {24 const program = new MyCommand();25 program.argument('<file>');26 assert.equal(program.registeredArguments.length, 1);27 assert.equal(program.registeredArguments[0].myProperty, 'MyArgument');28});24 test('when override createArgument then used for argument()', () => {25 const program = new MyCommand();26 program.argument('<file>');27 assert.equal(program.registeredArguments.length, 1);28 assert.equal(program.registeredArguments[0].myProperty, 'MyArgument');29 });3030test('when override createArgument then used for arguments()', () => {31 const program = new MyCommand();32 program.arguments('<file>');33 assert.equal(program.registeredArguments.length, 1);34 assert.equal(program.registeredArguments[0].myProperty, 'MyArgument');35});31 test('when override createArgument then used for arguments()', () => {32 const program = new MyCommand();33 program.arguments('<file>');34 assert.equal(program.registeredArguments.length, 1);35 assert.equal(program.registeredArguments[0].myProperty, 'MyArgument');36 });3737test('when override createArgument and createCommand then used for argument of command()', () => {38 const program = new MyCommand();39 const sub = program.command('sub <file>');40 assert.equal(sub.registeredArguments.length, 1);41 assert.equal(sub.registeredArguments[0].myProperty, 'MyArgument');38 test('when override createArgument and createCommand then used for argument of command()', () => {39 const program = new MyCommand();40 const sub = program.command('sub <file>');41 assert.equal(sub.registeredArguments.length, 1);42 assert.equal(sub.registeredArguments[0].myProperty, 'MyArgument');43 });44});
modified:tests/command.createHelp.test.js+14 added-12 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Command.createHelp() override in subclass', () => {5test('when override createCommand then affects help', () => {6 class MyHelp extends commander.Help {7 formatHelp(cmd, helper) {8 return 'custom';6 test('when override createCommand then affects help', () => {7 class MyHelp extends commander.Help {8 formatHelp(cmd, helper) {9 return 'custom';10 }11 }10 }1212 class MyCommand extends commander.Command {13 createHelp() {14 return Object.assign(new MyHelp(), this.configureHelp());13 class MyCommand extends commander.Command {14 createHelp() {15 return Object.assign(new MyHelp(), this.configureHelp());16 }17 }16 }1818 const program = new MyCommand();19 assert.equal(program.helpInformation(), 'custom');19 const program = new MyCommand();20 assert.equal(program.helpInformation(), 'custom');21 });22});
modified:tests/command.createOption.test.js+26 added-24 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45class MyOption extends commander.Option {6 constructor(flags, description) {
7 unmodified lines
14 return new MyOption(flags, description);15 }16}1718describe('Command.createOption() override in subclass', () => {18test('when override createOption then used for option()', () => {19 const program = new MyCommand();20 program.option('-a, --alpha');21 assert.equal(program.options.length, 1);22 assert.equal(program.options[0].myProperty, 'MyOption');23});19 test('when override createOption then used for option()', () => {20 const program = new MyCommand();21 program.option('-a, --alpha');22 assert.equal(program.options.length, 1);23 assert.equal(program.options[0].myProperty, 'MyOption');24 });2525test('when override createOption then used for requiredOption()', () => {26 const program = new MyCommand();27 program.requiredOption('-a, --alpha');28 assert.equal(program.options.length, 1);29 assert.equal(program.options[0].myProperty, 'MyOption');30});26 test('when override createOption then used for requiredOption()', () => {27 const program = new MyCommand();28 program.requiredOption('-a, --alpha');29 assert.equal(program.options.length, 1);30 assert.equal(program.options[0].myProperty, 'MyOption');31 });3232test('when override createOption then used for version()', () => {33 const program = new MyCommand();34 program.version('1.2.3');35 assert.equal(program.options.length, 1);36 assert.equal(program.options[0].myProperty, 'MyOption');37});33 test('when override createOption then used for version()', () => {34 const program = new MyCommand();35 program.version('1.2.3');36 assert.equal(program.options.length, 1);37 assert.equal(program.options[0].myProperty, 'MyOption');38 });3939test('when override createOption then used for help option in visibleOptions', () => {40 const program = new MyCommand();41 const visibleOptions = program.createHelp().visibleOptions(program);42 assert.equal(visibleOptions.length, 1);43 assert.equal(visibleOptions[0].myProperty, 'MyOption');40 test('when override createOption then used for help option in visibleOptions', () => {41 const program = new MyCommand();42 const visibleOptions = program.createHelp().visibleOptions(program);43 assert.equal(visibleOptions.length, 1);44 assert.equal(visibleOptions[0].myProperty, 'MyOption');45 });46});
modified:tests/command.description.test.js+8 added-6 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Command description()', () => {5test('when set description then get description', () => {6 const program = new commander.Command();7 const description = 'abcdef';8 program.description(description);9 assert.equal(program.description(), description);6 test('when set description then get description', () => {7 const program = new commander.Command();8 const description = 'abcdef';9 program.description(description);10 assert.equal(program.description(), description);11 });12});
modified:tests/command.error.test.js+43 added-41 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Command.error()', () => {5test('when error called with message then message displayed on stderr', (t) => {6 t.mock.method(process, 'exit', () => {});7 const stderrSpy = t.mock.method(process.stderr, 'write', () => {});6 test('when error called with message then message displayed on stderr', (t) => {7 t.mock.method(process, 'exit', () => {});8 const stderrSpy = t.mock.method(process.stderr, 'write', () => {});99 const program = new commander.Command();10 const message = 'Goodbye';11 program.error(message);10 const program = new commander.Command();11 const message = 'Goodbye';12 program.error(message);1313 const callArgs = stderrSpy.mock.calls[0].arguments;14 assert.equal(callArgs[0], `${message}\n`);15});1617test('when error called with no exitCode then process.exit(1)', (t) => {18 const exitSpy = t.mock.method(process, 'exit', () => {});1920 const program = new commander.Command();21 program.configureOutput({22 writeErr: () => {},14 const callArgs = stderrSpy.mock.calls[0].arguments;15 assert.equal(callArgs[0], `${message}\n`);16 });1725 program.error('Goodbye');18 test('when error called with no exitCode then process.exit(1)', (t) => {19 const exitSpy = t.mock.method(process, 'exit', () => {});2027 const callArgs = exitSpy.mock.calls[0].arguments;28 assert.equal(callArgs[0], 1);29});21 const program = new commander.Command();22 program.configureOutput({23 writeErr: () => {},24 });2531test('when error called with exitCode 2 then process.exit(2)', (t) => {32 const exitSpy = t.mock.method(process, 'exit', () => {});26 program.error('Goodbye');2734 const program = new commander.Command();35 program.configureOutput({36 writeErr: () => {},28 const callArgs = exitSpy.mock.calls[0].arguments;29 assert.equal(callArgs[0], 1);30 });38 program.error('Goodbye', { exitCode: 2 });3140 const callArgs = exitSpy.mock.calls[0].arguments;41 assert.equal(callArgs[0], 2);42});32 test('when error called with exitCode 2 then process.exit(2)', (t) => {33 const exitSpy = t.mock.method(process, 'exit', () => {});3444test('when error called with code and exitOverride then throws with code', () => {45 const program = new commander.Command();46 program.exitOverride().configureOutput({47 writeErr: () => {},35 const program = new commander.Command();36 program.configureOutput({37 writeErr: () => {},38 });39 program.error('Goodbye', { exitCode: 2 });4041 const callArgs = exitSpy.mock.calls[0].arguments;42 assert.equal(callArgs[0], 2);43 });4445 test('when error called with code and exitOverride then throws with code', () => {46 const program = new commander.Command();47 program.exitOverride().configureOutput({48 writeErr: () => {},49 });5050 const code = 'commander.mytest';51 assert.throws(52 () => {53 program.error('Goodbye', { code });54 },55 { code },56 );51 const code = 'commander.mytest';52 assert.throws(53 () => {54 program.error('Goodbye', { code });55 },56 { code },57 );58 });59});
modified:tests/command.executableSubcommand.inspect.test.js+68 added-66 removed
1const childProcess = require('child_process');2const path = require('path');3const util = require('util');4const { test } = require('node:test');4const { test, describe } = require('node:test');5const assert = require('node:assert/strict');67const execFileAsync = util.promisify(childProcess.execFile);8
1 unmodified line
10// If we reuse port we can get conflicts because port not released fast enough.1112const inspectCommand = path.join(__dirname, './fixtures', 'inspect.js');1314describe('executable subcommand support for --inspect ', () => {14test('when execArgv empty then spawn execArgs empty', async () => {15 const { stdout } = await execFileAsync('node', [inspectCommand, 'sub']);16 assert.equal(stdout, '[]\n');17});15 test('when execArgv empty then spawn execArgs empty', async () => {16 const { stdout } = await execFileAsync('node', [inspectCommand, 'sub']);17 assert.equal(stdout, '[]\n');18 });1919test('when execArgv --harmony then spawn execArgs --harmony', async () => {20 const { stdout } = await execFileAsync('node', [21 '--harmony',22 inspectCommand,23 'sub',24 ]);25 assert.equal(stdout, "[ '--harmony' ]\n");26});20 test('when execArgv --harmony then spawn execArgs --harmony', async () => {21 const { stdout } = await execFileAsync('node', [22 '--harmony',23 inspectCommand,24 'sub',25 ]);26 assert.equal(stdout, "[ '--harmony' ]\n");27 });2828// --inspect defaults to 127.0.0.1:9229, port should be incremented29test('when execArgv --inspect then spawn execArgs using port 9230', async () => {30 const { stdout } = await execFileAsync('node', [31 '--inspect',32 inspectCommand,33 'sub',34 ]);35 assert.equal(stdout, "[ '--inspect=127.0.0.1:9230' ]\n");36});29 // --inspect defaults to 127.0.0.1:9229, port should be incremented30 test('when execArgv --inspect then spawn execArgs using port 9230', async () => {31 const { stdout } = await execFileAsync('node', [32 '--inspect',33 inspectCommand,34 'sub',35 ]);36 assert.equal(stdout, "[ '--inspect=127.0.0.1:9230' ]\n");37 });3838// custom port39test('when execArgv --inspect=9240 then spawn execArgs using port 9241', async () => {40 const { stdout } = await execFileAsync('node', [41 '--inspect=9240',42 inspectCommand,43 'sub',44 ]);45 assert.equal(stdout, "[ '--inspect=127.0.0.1:9241' ]\n");46});39 // custom port40 test('when execArgv --inspect=9240 then spawn execArgs using port 9241', async () => {41 const { stdout } = await execFileAsync('node', [42 '--inspect=9240',43 inspectCommand,44 'sub',45 ]);46 assert.equal(stdout, "[ '--inspect=127.0.0.1:9241' ]\n");47 });4848// zero is special, random port49test('when execArgv --inspect=0 then spawn execArgs --inspect=0', async () => {50 const { stdout } = await execFileAsync('node', [51 '--inspect=0',52 inspectCommand,53 'sub',54 ]);55 assert.equal(stdout, "[ '--inspect=0' ]\n");56});49 // zero is special, random port50 test('when execArgv --inspect=0 then spawn execArgs --inspect=0', async () => {51 const { stdout } = await execFileAsync('node', [52 '--inspect=0',53 inspectCommand,54 'sub',55 ]);56 assert.equal(stdout, "[ '--inspect=0' ]\n");57 });5858// ip address59test('when execArgv --inspect=127.0.0.1:9250 then spawn execArgs --inspect=127.0.0.1:9251', async () => {60 const { stdout } = await execFileAsync('node', [61 '--inspect=127.0.0.1:9250',62 inspectCommand,63 'sub',64 ]);65 assert.equal(stdout, "[ '--inspect=127.0.0.1:9251' ]\n");66});59 // ip address60 test('when execArgv --inspect=127.0.0.1:9250 then spawn execArgs --inspect=127.0.0.1:9251', async () => {61 const { stdout } = await execFileAsync('node', [62 '--inspect=127.0.0.1:9250',63 inspectCommand,64 'sub',65 ]);66 assert.equal(stdout, "[ '--inspect=127.0.0.1:9251' ]\n");67 });6868// localhost69test('when execArgv --inspect=localhost:9260 then spawn execArgs --inspect=localhost:9261', async () => {70 const { stdout } = await execFileAsync('node', [71 '--inspect=localhost:9260',72 inspectCommand,73 'sub',74 ]);75 assert.equal(stdout, "[ '--inspect=localhost:9261' ]\n");76});69 // localhost70 test('when execArgv --inspect=localhost:9260 then spawn execArgs --inspect=localhost:9261', async () => {71 const { stdout } = await execFileAsync('node', [72 '--inspect=localhost:9260',73 inspectCommand,74 'sub',75 ]);76 assert.equal(stdout, "[ '--inspect=localhost:9261' ]\n");77 });7878// --inspect-port, just test most likely format79test('when execArgv --inspect-port=9270 then spawn execArgs --inspect-port=127.0.0.1:9271', async () => {80 const { stdout } = await execFileAsync('node', [81 '--inspect-port=9270',82 inspectCommand,83 'sub',84 ]);85 assert.equal(stdout, "[ '--inspect-port=127.0.0.1:9271' ]\n");79 // --inspect-port, just test most likely format80 test('when execArgv --inspect-port=9270 then spawn execArgs --inspect-port=127.0.0.1:9271', async () => {81 const { stdout } = await execFileAsync('node', [82 '--inspect-port=9270',83 inspectCommand,84 'sub',85 ]);86 assert.equal(stdout, "[ '--inspect-port=127.0.0.1:9271' ]\n");87 });88});
modified:tests/command.executableSubcommand.lookup.test.js+82 added-80 removed
1const childProcess = require('child_process');2const path = require('path');3const util = require('util');4const execFileAsync = util.promisify(childProcess.execFile);5const { test } = require('node:test');5const { test, describe } = require('node:test');6const assert = require('node:assert/strict');78// Calling node explicitly so pm works without file suffix cross-platform.9// This file does end-to-end tests actually spawning program.
3 unmodified lines
1314const testOrSkipOnWindows = process.platform === 'win32' ? test.skip : test;15const pm = path.join(__dirname, './fixtures/pm');1617describe('executable subcommand lookup ', () => {17test('when subcommand file missing then error', () => {18 return execFileAsync('node', [pm, 'list']).catch((err) => {19 if (process.platform === 'win32') {20 // Get uncaught thrown error on Windows21 assert.ok(err.stderr !== undefined);22 } else {23 assert.match(err.stderr, /Error: 'pm-list' does not exist/);24 }18 test('when subcommand file missing then error', () => {19 return execFileAsync('node', [pm, 'list']).catch((err) => {20 if (process.platform === 'win32') {21 // Get uncaught thrown error on Windows22 assert.ok(err.stderr !== undefined);23 } else {24 assert.match(err.stderr, /Error: 'pm-list' does not exist/);25 }26 });27 });26});2828test('when alias subcommand file missing then error', () => {29 return execFileAsync('node', [pm, 'lst']).catch((err) => {30 if (process.platform === 'win32') {31 // Get uncaught thrown error on Windows32 assert.ok(err.stderr !== undefined);33 } else {34 assert.match(err.stderr, /Error: 'pm-list' does not exist/);35 }29 test('when alias subcommand file missing then error', () => {30 return execFileAsync('node', [pm, 'lst']).catch((err) => {31 if (process.platform === 'win32') {32 // Get uncaught thrown error on Windows33 assert.ok(err.stderr !== undefined);34 } else {35 assert.match(err.stderr, /Error: 'pm-list' does not exist/);36 }37 });38 });37});3939test('when subcommand file has no suffix then lookup succeeds', async () => {40 const { stdout } = await execFileAsync('node', [pm, 'install']);41 assert.equal(stdout, 'install\n');42});40 test('when subcommand file has no suffix then lookup succeeds', async () => {41 const { stdout } = await execFileAsync('node', [pm, 'install']);42 assert.equal(stdout, 'install\n');43 });4444test('when alias subcommand file has no suffix then lookup succeeds', async () => {45 const { stdout } = await execFileAsync('node', [pm, 'i']);46 assert.equal(stdout, 'install\n');47});45 test('when alias subcommand file has no suffix then lookup succeeds', async () => {46 const { stdout } = await execFileAsync('node', [pm, 'i']);47 assert.equal(stdout, 'install\n');48 });4949test('when subcommand target executablefile has no suffix then lookup succeeds', async () => {50 const { stdout } = await execFileAsync('node', [pm, 'specifyInstall']);51 assert.equal(stdout, 'install\n');52});50 test('when subcommand target executablefile has no suffix then lookup succeeds', async () => {51 const { stdout } = await execFileAsync('node', [pm, 'specifyInstall']);52 assert.equal(stdout, 'install\n');53 });5454test('when subcommand file suffix .js then lookup succeeds', async () => {55 const { stdout } = await execFileAsync('node', [pm, 'publish']);56 assert.equal(stdout, 'publish\n');57});55 test('when subcommand file suffix .js then lookup succeeds', async () => {56 const { stdout } = await execFileAsync('node', [pm, 'publish']);57 assert.equal(stdout, 'publish\n');58 });5959test('when alias subcommand file suffix .js then lookup succeeds', async () => {60 const { stdout } = await execFileAsync('node', [pm, 'p']);61 assert.equal(stdout, 'publish\n');62});60 test('when alias subcommand file suffix .js then lookup succeeds', async () => {61 const { stdout } = await execFileAsync('node', [pm, 'p']);62 assert.equal(stdout, 'publish\n');63 });6464test('when subcommand target executablefile has suffix .js then lookup succeeds', async () => {65 const { stdout } = await execFileAsync('node', [pm, 'specifyPublish']);66 assert.equal(stdout, 'publish\n');67});65 test('when subcommand target executablefile has suffix .js then lookup succeeds', async () => {66 const { stdout } = await execFileAsync('node', [pm, 'specifyPublish']);67 assert.equal(stdout, 'publish\n');68 });6969testOrSkipOnWindows(70 'when subcommand file is symlink then lookup succeeds',71 async () => {72 const pmlink = path.join(__dirname, 'fixtures', 'pmlink');73 const { stdout } = await execFileAsync('node', [pmlink, 'install']);74 assert.equal(stdout, 'install\n');75 },76);70 testOrSkipOnWindows(71 'when subcommand file is symlink then lookup succeeds',72 async () => {73 const pmlink = path.join(__dirname, 'fixtures', 'pmlink');74 const { stdout } = await execFileAsync('node', [pmlink, 'install']);75 assert.equal(stdout, 'install\n');76 },77 );7878testOrSkipOnWindows(79 'when subcommand file is double symlink then lookup succeeds',80 async () => {81 const pmlink = path.join(__dirname, 'fixtures', 'another-dir', 'pm');82 const { stdout } = await execFileAsync('node', [pmlink, 'install']);83 assert.equal(stdout, 'install\n');84 },85);79 testOrSkipOnWindows(80 'when subcommand file is double symlink then lookup succeeds',81 async () => {82 const pmlink = path.join(__dirname, 'fixtures', 'another-dir', 'pm');83 const { stdout } = await execFileAsync('node', [pmlink, 'install']);84 assert.equal(stdout, 'install\n');85 },86 );8787test('when subcommand suffix is .ts then lookup succeeds', async () => {88 // We support looking for ts files for ts-node in particular, but don't need to test ts-node itself.89 // The subcommand is both plain JavaScript code for this test.90 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');91 // childProcess.execFile('node', ['-r', 'ts-node/register', binLinkTs, 'install'], function(_error, stdout, stderr) {92 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-ts']);93 assert.equal(stdout, 'found .ts\n');94});88 test('when subcommand suffix is .ts then lookup succeeds', async () => {89 // We support looking for ts files for ts-node in particular, but don't need to test ts-node itself.90 // The subcommand is both plain JavaScript code for this test.91 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');92 // childProcess.execFile('node', ['-r', 'ts-node/register', binLinkTs, 'install'], function(_error, stdout, stderr) {93 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-ts']);94 assert.equal(stdout, 'found .ts\n');95 });9696test('when subcommand suffix is .cjs then lookup succeeds', async () => {97 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');98 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-cjs']);99 assert.equal(stdout, 'found .cjs\n');100});97 test('when subcommand suffix is .cjs then lookup succeeds', async () => {98 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');99 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-cjs']);100 assert.equal(stdout, 'found .cjs\n');101 });102102test('when subcommand suffix is .mjs then lookup succeeds', async () => {103 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');104 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-mjs']);105 assert.equal(stdout, 'found .mjs\n');106});103 test('when subcommand suffix is .mjs then lookup succeeds', async () => {104 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');105 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-mjs']);106 assert.equal(stdout, 'found .mjs\n');107 });108108test('when subsubcommand then lookup sub-sub-command', async () => {109 const { stdout } = await execFileAsync('node', [pm, 'cache', 'clear']);110 assert.equal(stdout, 'cache-clear\n');109 test('when subsubcommand then lookup sub-sub-command', async () => {110 const { stdout } = await execFileAsync('node', [pm, 'cache', 'clear']);111 assert.equal(stdout, 'cache-clear\n');112 });113});
modified:tests/command.executableSubcommand.mock.test.js+65 added-63 removed
1const commander = require('../');2const childProcess = require('child_process');3const EventEmitter = require('events');4const { test } = require('node:test');4const { test, describe } = require('node:test');5const assert = require('node:assert/strict');67// Using mock to allow try/catch around what is otherwise out-of-stack error handling.8// Injecting errors, these are not end-to-end tests.
8 unmodified lines
17// Suppress false positive warnings due to use of testOrSkipOnWindows1819const testOrSkipOnWindows = process.platform === 'win32' ? test.skip : test;2021describe('executable subcommand missing file handling ', () => {21testOrSkipOnWindows(22 'when subcommand executable missing (ENOENT) then throw custom message',23 (t) => {24 // If the command is not found, we show a custom error with an explanation and offer25 // some advice for possible fixes.22 testOrSkipOnWindows(23 'when subcommand executable missing (ENOENT) then throw custom message',24 (t) => {25 // If the command is not found, we show a custom error with an explanation and offer26 // some advice for possible fixes.27 const mockProcess = new EventEmitter();28 t.mock.method(childProcess, 'spawn', () => {29 return mockProcess;30 });31 const program = new commander.Command();32 program.exitOverride();33 program.command('executable', 'executable description');34 program.parse(['executable'], { from: 'user' });35 assert.throws(() => {36 mockProcess.emit('error', makeSystemError('ENOENT'));37 }, /use the executableFile option to supply a custom name/); // part of custom message38 },39 );4041 testOrSkipOnWindows(42 'when subcommand executable not executable (EACCES) then throw custom message',43 (t) => {44 const mockProcess = new EventEmitter();45 t.mock.method(childProcess, 'spawn', () => {46 return mockProcess;47 });48 const program = new commander.Command();49 program.exitOverride();50 program.command('executable', 'executable description');51 program.parse(['executable'], { from: 'user' });52 assert.throws(() => {53 mockProcess.emit('error', makeSystemError('EACCES'));54 }, /not executable/); // part of custom message55 },56 );5758 test('when subcommand executable fails with other error and exitOverride then return in custom wrapper', (t) => {59 // The existing behaviour is to just silently fail for unexpected errors, as it is happening60 // asynchronously in spawned process and client can not catch errors.61 const mockProcess = new EventEmitter();62 t.mock.method(childProcess, 'spawn', () => {63 return mockProcess;64 });65 const program = new commander.Command();66 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn31 program.exitOverride();67 program.exitOverride((err) => {68 throw err;69 });70 program.command('executable', 'executable description');71 program.parse(['executable'], { from: 'user' });34 assert.throws(() => {35 mockProcess.emit('error', makeSystemError('ENOENT'));36 }, /use the executableFile option to supply a custom name/); // part of custom message37 },38);72 assert.throws(73 () => {74 mockProcess.emit('error', makeSystemError('OTHER'));75 },76 (err) => {77 assert.equal(err.code, 'commander.executeSubCommandAsync');78 assert.equal(err.nestedError.code, 'OTHER');79 return true;80 },81 );82 });8340testOrSkipOnWindows(41 'when subcommand executable not executable (EACCES) then throw custom message',42 (t) => {84 test('when subcommand executable fails with other error then exit', (t) => {85 // The existing behaviour is to just silently fail for unexpected errors, as it is happening86 // asynchronously in spawned process and client can not catch errors.87 const mockProcess = new EventEmitter();88 t.mock.method(childProcess, 'spawn', () => {89 return mockProcess;90 });91 const exitSpy = t.mock.method(process, 'exit', () => {});92 const program = new commander.Command();48 program.exitOverride();93 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn94 program.command('executable', 'executable description');95 program.parse(['executable'], { from: 'user' });51 assert.throws(() => {52 mockProcess.emit('error', makeSystemError('EACCES'));53 }, /not executable/); // part of custom message54 },55);5657test('when subcommand executable fails with other error and exitOverride then return in custom wrapper', (t) => {58 // The existing behaviour is to just silently fail for unexpected errors, as it is happening59 // asynchronously in spawned process and client can not catch errors.60 const mockProcess = new EventEmitter();61 t.mock.method(childProcess, 'spawn', () => {62 return mockProcess;96 mockProcess.emit('error', makeSystemError('OTHER'));97 assert.equal(exitSpy.mock.callCount(), 1);98 const callArgs = exitSpy.mock.calls[0].arguments;99 assert.equal(callArgs[0], 1);100 });64 const program = new commander.Command();65 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn66 program.exitOverride((err) => {67 throw err;68 });69 program.command('executable', 'executable description');70 program.parse(['executable'], { from: 'user' });71 assert.throws(72 () => {73 mockProcess.emit('error', makeSystemError('OTHER'));74 },75 (err) => {76 assert.equal(err.code, 'commander.executeSubCommandAsync');77 assert.equal(err.nestedError.code, 'OTHER');78 return true;79 },80 );101});8283test('when subcommand executable fails with other error then exit', (t) => {84 // The existing behaviour is to just silently fail for unexpected errors, as it is happening85 // asynchronously in spawned process and client can not catch errors.86 const mockProcess = new EventEmitter();87 t.mock.method(childProcess, 'spawn', () => {88 return mockProcess;89 });90 const exitSpy = t.mock.method(process, 'exit', () => {});91 const program = new commander.Command();92 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn93 program.command('executable', 'executable description');94 program.parse(['executable'], { from: 'user' });95 mockProcess.emit('error', makeSystemError('OTHER'));96 assert.equal(exitSpy.mock.callCount(), 1);97 const callArgs = exitSpy.mock.calls[0].arguments;98 assert.equal(callArgs[0], 1);99});
modified:tests/command.executableSubcommand.search.test.js+1 added-1 removed
29 unmodified lines
3031const describeOrSkipOnWindows =32 process.platform === 'win32' ? describe.skip : describe;3334describe('search for subcommand', () => {34describe('executable subcommand search behaviour', () => {35 function makeSpies(t, existsFn) {36 const spawnSpy = t.mock.method(childProcess, 'spawn', () => {37 return {38 on: () => {},
277 unmodified lines
modified:tests/command.executableSubcommand.signals.test.js+1 added-1 removed
9 unmodified lines
10// https://nodejs.org/api/process.html#process_signal_events11const describeOrSkipOnWindows =12 process.platform === 'win32' ? describe.skip : describe;1314describeOrSkipOnWindows('signals', () => {14describeOrSkipOnWindows('executable subcommand signals', () => {15 describe('signal forwarding tests', () => {16 const signals = ['SIGINT', 'SIGHUP', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'];17 for (const signal of signals) {18 test(`when program sent ${signal} then executableSubcommand sent signal too`, (t, done) => {
44 unmodified lines
modified:tests/command.executableSubcommand.test.js+1 added-1 removed
3 unmodified lines
45// Executable subcommand tests that didn't fit in elsewhere.67// This is the default behaviour when no default command and no action handlers8test('when no command specified and executable then display help', (t) => {8test('when no command specified and executable subcommand then display help', (t) => {9 const program = createTestCommand();10 program.command('install', 'install description');11 assert.throws(12 () => {
7 unmodified lines
modified:tests/command.exitOverride.test.js+1 added-1 removed
13 unmodified lines
14 assert.equal(err.code, code);15 assert.equal(err.message, message);16}1718describe('.exitOverride and error details', () => {18describe('Command.exitOverride', () => {19 // Use internal knowledge to suppress output to keep test output clean.2021 test('when specify unknown program option then throw CommanderError', (t) => {22 const stderrSpy = t.mock.method(process.stderr, 'write', () => {});
435 unmodified lines
modified:tests/command.help.test.js+266 added-260 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test } = require('node:test');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56// Testing various help incantations.7//8// Note there are also specific help tests included in many of the feature tests,9// such as the alias, version, usage, name, helpOption, and commandHelp tests.1011describe('help handling', () => {11// Avoid doing many full format tests as will be broken by any layout changes!12test('when call helpInformation for program then help format is as expected (usage, options, commands)', () => {13 const program = new commander.Command();14 program.command('my-command <file>');15 const expectedHelpInformation = `Usage: test [options] [command]12 // Avoid doing many full format tests as will be broken by any layout changes!13 test('when call helpInformation for program then help format is as expected (usage, options, commands)', () => {14 const program = new commander.Command();15 program.command('my-command <file>');16 const expectedHelpInformation = `Usage: test [options] [command]1718Options:19 -h, --help display help for command20
1 unmodified line
22 my-command <file>23 help [command] display help for command24`;2525 program.name('test');26 const helpInformation = program.helpInformation();27 assert.equal(helpInformation, expectedHelpInformation);28});26 program.name('test');27 const helpInformation = program.helpInformation();28 assert.equal(helpInformation, expectedHelpInformation);29 });3030test('when use .description for command then help includes description', () => {31 const program = new commander.Command();32 program.command('simple-command').description('custom-description');33 program._help = 'test';34 const helpInformation = program.helpInformation();35 assert.match(helpInformation, /simple-command +custom-description/);36});31 test('when use .description for command then help includes description', () => {32 const program = new commander.Command();33 program.command('simple-command').description('custom-description');34 program._help = 'test';35 const helpInformation = program.helpInformation();36 assert.match(helpInformation, /simple-command +custom-description/);37 });3838test('when call .help then exit', (t) => {39 const program = createTestCommand();40 assert.throws(41 () => {42 program.help();43 },44 { message: '(outputHelp)' },45 );46});39 test('when call .help then exit', (t) => {40 const program = createTestCommand();41 assert.throws(42 () => {43 program.help();44 },45 { message: '(outputHelp)' },46 );47 });4848test('when specify --help then exit', (t) => {49 const program = createTestCommand();50 assert.throws(51 () => {52 program.parse(['node', 'test', '--help']);53 },54 { message: '(outputHelp)' },55 );56});49 test('when specify --help then exit', (t) => {50 const program = createTestCommand();51 assert.throws(52 () => {53 program.parse(['node', 'test', '--help']);54 },55 { message: '(outputHelp)' },56 );57 });5858test('when call help(cb) then display cb output and exit', (t) => {59 // Using spy to detect custom output60 const writeSpy = t.mock.method(process.stdout, 'write', () => {});61 const helpReplacement = 'reformatted help';62 const program = new commander.Command();63 program.exitOverride();64 assert.throws(65 () => {66 program.help((helpInformation) => {67 return helpReplacement;68 });69 },70 { message: '(outputHelp)' },71 );72 assert.equal(writeSpy.mock.callCount(), 1);73 assert.deepEqual(writeSpy.mock.calls[0].arguments, [helpReplacement]);74});59 test('when call help(cb) then display cb output and exit', (t) => {60 // Using spy to detect custom output61 const writeSpy = t.mock.method(process.stdout, 'write', () => {});62 const helpReplacement = 'reformatted help';63 const program = new commander.Command();64 program.exitOverride();65 assert.throws(66 () => {67 program.help((helpInformation) => {68 return helpReplacement;69 });70 },71 { message: '(outputHelp)' },72 );73 assert.equal(writeSpy.mock.callCount(), 1);74 assert.deepEqual(writeSpy.mock.calls[0].arguments, [helpReplacement]);75 });7676test('when call outputHelp(cb) then display cb output', (t) => {77 // Using spy to detect custom output78 const writeSpy = t.mock.method(process.stdout, 'write', () => {});79 const helpReplacement = 'reformatted help';80 const program = new commander.Command();81 program.outputHelp((helpInformation) => {82 return helpReplacement;77 test('when call outputHelp(cb) then display cb output', (t) => {78 // Using spy to detect custom output79 const writeSpy = t.mock.method(process.stdout, 'write', () => {});80 const helpReplacement = 'reformatted help';81 const program = new commander.Command();82 program.outputHelp((helpInformation) => {83 return helpReplacement;84 });85 assert.equal(writeSpy.mock.callCount(), 1);86 assert.deepEqual(writeSpy.mock.calls[0].arguments, [helpReplacement]);87 });84 assert.equal(writeSpy.mock.callCount(), 1);85 assert.deepEqual(writeSpy.mock.calls[0].arguments, [helpReplacement]);86});8888test('when call deprecated outputHelp(cb) with wrong callback return type then throw', () => {89 const program = new commander.Command();90 assert.throws(() => {91 program.outputHelp((helpInformation) => 3);89 test('when call deprecated outputHelp(cb) with wrong callback return type then throw', () => {90 const program = new commander.Command();91 assert.throws(() => {92 program.outputHelp((helpInformation) => 3);93 });94 });93});9595test('when command sets deprecated noHelp then not displayed in helpInformation', () => {96 const program = new commander.Command();97 program.command('secret', 'secret description', { noHelp: true });98 const helpInformation = program.helpInformation();99 assert(!helpInformation.includes('secret'));100});96 test('when command sets deprecated noHelp then not displayed in helpInformation', () => {97 const program = new commander.Command();98 program.command('secret', 'secret description', { noHelp: true });99 const helpInformation = program.helpInformation();100 assert(!helpInformation.includes('secret'));101 });102102test('when command sets hidden then not displayed in helpInformation', () => {103 const program = new commander.Command();104 program.command('secret', 'secret description', { hidden: true });105 const helpInformation = program.helpInformation();106 assert(!helpInformation.includes('secret'));107});103 test('when command sets hidden then not displayed in helpInformation', () => {104 const program = new commander.Command();105 program.command('secret', 'secret description', { hidden: true });106 const helpInformation = program.helpInformation();107 assert(!helpInformation.includes('secret'));108 });109109test('when addCommand with hidden:true then not displayed in helpInformation', () => {110 const secretCmd = new commander.Command('secret');110 test('when addCommand with hidden:true then not displayed in helpInformation', () => {111 const secretCmd = new commander.Command('secret');112112 const program = new commander.Command();113 program.addCommand(secretCmd, { hidden: true });114 const helpInformation = program.helpInformation();115 assert(!helpInformation.includes('secret'));116});113 const program = new commander.Command();114 program.addCommand(secretCmd, { hidden: true });115 const helpInformation = program.helpInformation();116 assert(!helpInformation.includes('secret'));117 });118118test('when help short flag masked then not displayed in helpInformation', () => {119 const program = new commander.Command();120 program.option('-h, --host', 'select host');121 const helpInformation = program.helpInformation();122 assert(!/\W-h\W.*display help/.test(helpInformation));123});119 test('when help short flag masked then not displayed in helpInformation', () => {120 const program = new commander.Command();121 program.option('-h, --host', 'select host');122 const helpInformation = program.helpInformation();123 assert(!/\W-h\W.*display help/.test(helpInformation));124 });125125test('when both help flags masked then not displayed in helpInformation', () => {126 const program = new commander.Command();127 program.option('-h, --help', 'custom');128 const helpInformation = program.helpInformation();129 assert(!helpInformation.includes('display help'));130});126 test('when both help flags masked then not displayed in helpInformation', () => {127 const program = new commander.Command();128 program.option('-h, --help', 'custom');129 const helpInformation = program.helpInformation();130 assert(!helpInformation.includes('display help'));131 });132132test('when call .help then output on stdout', (t) => {133 const writeSpy = t.mock.method(process.stdout, 'write', () => {});134 const program = new commander.Command();135 program.exitOverride();136 assert.throws(137 () => {138 program.help();139 },140 { message: '(outputHelp)' },141 );142 assert.equal(writeSpy.mock.callCount(), 1);143 assert.deepEqual(writeSpy.mock.calls[0].arguments, [144 program.helpInformation(),145 ]);146});133 test('when call .help then output on stdout', (t) => {134 const writeSpy = t.mock.method(process.stdout, 'write', () => {});135 const program = new commander.Command();136 program.exitOverride();137 assert.throws(138 () => {139 program.help();140 },141 { message: '(outputHelp)' },142 );143 assert.equal(writeSpy.mock.callCount(), 1);144 assert.deepEqual(writeSpy.mock.calls[0].arguments, [145 program.helpInformation(),146 ]);147 });148148test('when call .help with { error: true } then output on stderr', (t) => {149 const writeSpy = t.mock.method(process.stderr, 'write', () => {});150 const program = new commander.Command();151 program.exitOverride();152 assert.throws(153 () => {154 program.help({ error: true });155 },156 { message: '(outputHelp)' },157 );158 assert.equal(writeSpy.mock.callCount(), 1);159 assert.deepEqual(writeSpy.mock.calls[0].arguments, [160 program.helpInformation(),161 ]);162});149 test('when call .help with { error: true } then output on stderr', (t) => {150 const writeSpy = t.mock.method(process.stderr, 'write', () => {});151 const program = new commander.Command();152 program.exitOverride();153 assert.throws(154 () => {155 program.help({ error: true });156 },157 { message: '(outputHelp)' },158 );159 assert.equal(writeSpy.mock.callCount(), 1);160 assert.deepEqual(writeSpy.mock.calls[0].arguments, [161 program.helpInformation(),162 ]);163 });164164test('when no options then Options not included in helpInformation', () => {165 const program = new commander.Command();166 // No custom options, no version option, no help option167 program.helpOption(false);168 const helpInformation = program.helpInformation();169 assert(!helpInformation.includes('Options'));170});165 test('when no options then Options not included in helpInformation', () => {166 const program = new commander.Command();167 // No custom options, no version option, no help option168 program.helpOption(false);169 const helpInformation = program.helpInformation();170 assert(!helpInformation.includes('Options'));171 });172172test('when negated option then option included in helpInformation', () => {173 const program = new commander.Command();174 program.option('-C, --no-colour', 'colourless');175 const helpInformation = program.helpInformation();176 assert(helpInformation.includes('--no-colour'));177 assert(helpInformation.includes('colourless'));178});173 test('when negated option then option included in helpInformation', () => {174 const program = new commander.Command();175 program.option('-C, --no-colour', 'colourless');176 const helpInformation = program.helpInformation();177 assert(helpInformation.includes('--no-colour'));178 assert(helpInformation.includes('colourless'));179 });180180test('when option.hideHelp() then option not included in helpInformation', () => {181 const program = new commander.Command();182 program.addOption(183 new commander.Option('-s,--secret', 'secret option').hideHelp(),184 );185 const helpInformation = program.helpInformation();186 assert(!helpInformation.includes('secret'));187});181 test('when option.hideHelp() then option not included in helpInformation', () => {182 const program = new commander.Command();183 program.addOption(184 new commander.Option('-s,--secret', 'secret option').hideHelp(),185 );186 const helpInformation = program.helpInformation();187 assert(!helpInformation.includes('secret'));188 });189189test('when option.hideHelp(true) then option not included in helpInformation', () => {190 const program = new commander.Command();191 program.addOption(192 new commander.Option('-s,--secret', 'secret option').hideHelp(true),193 );194 const helpInformation = program.helpInformation();195 assert(!helpInformation.includes('secret'));196});190 test('when option.hideHelp(true) then option not included in helpInformation', () => {191 const program = new commander.Command();192 program.addOption(193 new commander.Option('-s,--secret', 'secret option').hideHelp(true),194 );195 const helpInformation = program.helpInformation();196 assert(!helpInformation.includes('secret'));197 });198198test('when option.hideHelp(false) then option included in helpInformation', () => {199 const program = new commander.Command();200 program.addOption(201 new commander.Option('-s,--secret', 'secret option').hideHelp(false),202 );203 const helpInformation = program.helpInformation();204 assert(helpInformation.includes('secret'));205});199 test('when option.hideHelp(false) then option included in helpInformation', () => {200 const program = new commander.Command();201 program.addOption(202 new commander.Option('-s,--secret', 'secret option').hideHelp(false),203 );204 const helpInformation = program.helpInformation();205 assert(helpInformation.includes('secret'));206 });207207test('when option has default value then default included in helpInformation', () => {208 const program = new commander.Command();209 program.option('-p, --port <portNumber>', 'port number', 80);210 const helpInformation = program.helpInformation();211 assert(helpInformation.includes('(default: 80)'));212});208 test('when option has default value then default included in helpInformation', () => {209 const program = new commander.Command();210 program.option('-p, --port <portNumber>', 'port number', 80);211 const helpInformation = program.helpInformation();212 assert(helpInformation.includes('(default: 80)'));213 });214214test('when option has default value description then default description included in helpInformation', () => {215 const program = new commander.Command();216 program.addOption(217 new commander.Option('-a, --address <dotted>', 'ip address').default(218 '127.0.0.1',219 'home',220 ),221 );222 const helpInformation = program.helpInformation();223 assert(helpInformation.includes('(default: home)'));224});215 test('when option has default value description then default description included in helpInformation', () => {216 const program = new commander.Command();217 program.addOption(218 new commander.Option('-a, --address <dotted>', 'ip address').default(219 '127.0.0.1',220 'home',221 ),222 );223 const helpInformation = program.helpInformation();224 assert(helpInformation.includes('(default: home)'));225 });226226test('when option has choices then choices included in helpInformation', () => {227 const program = new commander.Command();228 program.addOption(229 new commander.Option('-c, --colour <colour>').choices(['red', 'blue']),230 );231 const helpInformation = program.helpInformation();232 assert(helpInformation.includes('(choices: "red", "blue")'));233});227 test('when option has choices then choices included in helpInformation', () => {228 const program = new commander.Command();229 program.addOption(230 new commander.Option('-c, --colour <colour>').choices(['red', 'blue']),231 );232 const helpInformation = program.helpInformation();233 assert(helpInformation.includes('(choices: "red", "blue")'));234 });235235test('when option has choices and default then both included in helpInformation', () => {236 const program = new commander.Command();237 program.addOption(238 new commander.Option('-c, --colour <colour>')239 .choices(['red', 'blue'])240 .default('red'),241 );242 const helpInformation = program.helpInformation();243 assert(helpInformation.includes('(choices: "red", "blue", default: "red")'));244});236 test('when option has choices and default then both included in helpInformation', () => {237 const program = new commander.Command();238 program.addOption(239 new commander.Option('-c, --colour <colour>')240 .choices(['red', 'blue'])241 .default('red'),242 );243 const helpInformation = program.helpInformation();244 assert(245 helpInformation.includes('(choices: "red", "blue", default: "red")'),246 );247 });248246test('when argument then included in helpInformation', () => {247 const program = new commander.Command();248 program.name('foo').argument('<file>');249 const helpInformation = program.helpInformation();250 assert(helpInformation.includes('Usage: foo [options] <file>'));251});249 test('when argument then included in helpInformation', () => {250 const program = new commander.Command();251 program.name('foo').argument('<file>');252 const helpInformation = program.helpInformation();253 assert(helpInformation.includes('Usage: foo [options] <file>'));254 });255253test('when argument described then included in helpInformation', () => {254 const program = new commander.Command();255 program.argument('<file>', 'input source').helpOption(false);256 const helpInformation = program.helpInformation();257 assert.match(helpInformation, /Arguments:\n +file +input source/);258});256 test('when argument described then included in helpInformation', () => {257 const program = new commander.Command();258 program.argument('<file>', 'input source').helpOption(false);259 const helpInformation = program.helpInformation();260 assert.match(helpInformation, /Arguments:\n +file +input source/);261 });262260test('when argument described with default then included in helpInformation', () => {261 const program = new commander.Command();262 program.argument('[file]', 'input source', 'test.txt').helpOption(false);263 const helpInformation = program.helpInformation();264 assert.match(265 helpInformation,266 /Arguments:\n +file +input source \(default: "test.txt"\)/,267 );268});263 test('when argument described with default then included in helpInformation', () => {264 const program = new commander.Command();265 program.argument('[file]', 'input source', 'test.txt').helpOption(false);266 const helpInformation = program.helpInformation();267 assert.match(268 helpInformation,269 /Arguments:\n +file +input source \(default: "test.txt"\)/,270 );271 });272270test('when arguments described in deprecated way then included in helpInformation', () => {271 const program = new commander.Command();272 program273 .arguments('<file>')274 .helpOption(false)275 .description('description', { file: 'input source' });276 const helpInformation = program.helpInformation();277 assert.match(helpInformation, /Arguments:\n +file +input source/);278});273 test('when arguments described in deprecated way then included in helpInformation', () => {274 const program = new commander.Command();275 program276 .arguments('<file>')277 .helpOption(false)278 .description('description', { file: 'input source' });279 const helpInformation = program.helpInformation();280 assert.match(helpInformation, /Arguments:\n +file +input source/);281 });282280test('when arguments described in deprecated way and empty description then arguments still included in helpInformation', () => {281 const program = new commander.Command();282 program283 .arguments('<file>')284 .helpOption(false)285 .description('', { file: 'input source' });286 const helpInformation = program.helpInformation();287 assert.match(helpInformation, /Arguments:\n +file +input source/);288});283 test('when arguments described in deprecated way and empty description then arguments still included in helpInformation', () => {284 const program = new commander.Command();285 program286 .arguments('<file>')287 .helpOption(false)288 .description('', { file: 'input source' });289 const helpInformation = program.helpInformation();290 assert.match(helpInformation, /Arguments:\n +file +input source/);291 });292290test('when argument has choices then choices included in helpInformation', () => {291 const program = new commander.Command();292 program.addArgument(293 new commander.Argument('<colour>', 'preferred colour').choices([294 'red',295 'blue',296 ]),297 );298 const helpInformation = program.helpInformation();299 assert(helpInformation.includes('(choices: "red", "blue")'));300});293 test('when argument has choices then choices included in helpInformation', () => {294 const program = new commander.Command();295 program.addArgument(296 new commander.Argument('<colour>', 'preferred colour').choices([297 'red',298 'blue',299 ]),300 );301 const helpInformation = program.helpInformation();302 assert(helpInformation.includes('(choices: "red", "blue")'));303 });304302test('when argument has choices and default then both included in helpInformation', () => {303 const program = new commander.Command();304 program.addArgument(305 new commander.Argument('<colour>', 'preferred colour')306 .choices(['red', 'blue'])307 .default('red'),308 );309 const helpInformation = program.helpInformation();310 assert(helpInformation.includes('(choices: "red", "blue", default: "red")'));305 test('when argument has choices and default then both included in helpInformation', () => {306 const program = new commander.Command();307 program.addArgument(308 new commander.Argument('<colour>', 'preferred colour')309 .choices(['red', 'blue'])310 .default('red'),311 );312 const helpInformation = program.helpInformation();313 assert(314 helpInformation.includes('(choices: "red", "blue", default: "red")'),315 );316 });317});
modified:tests/command.helpCommand.test.js+143 added-141 removed
1 unmodified line
2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56describe('help handling of subcommands', () => {6describe('help command listed in helpInformation', () => {7 test('when program has no subcommands then no automatic help command', () => {8 const program = new commander.Command();9 const helpInformation = program.helpInformation();10 assert.doesNotMatch(helpInformation, /help \[command\]/);11 });7 describe('help command listed in helpInformation', () => {8 test('when program has no subcommands then no automatic help command', () => {9 const program = new commander.Command();10 const helpInformation = program.helpInformation();11 assert.doesNotMatch(helpInformation, /help \[command\]/);12 });1313 test('when program has no subcommands and add help command then has help command', () => {14 const program = new commander.Command();15 program.addHelpCommand(true);16 const helpInformation = program.helpInformation();17 assert.match(helpInformation, /help \[command\]/);18 });14 test('when program has no subcommands and add help command then has help command', () => {15 const program = new commander.Command();16 program.addHelpCommand(true);17 const helpInformation = program.helpInformation();18 assert.match(helpInformation, /help \[command\]/);19 });2020 test('when program has subcommands then has automatic help command', () => {21 const program = new commander.Command();22 program.command('foo');23 const helpInformation = program.helpInformation();24 assert.match(helpInformation, /help \[command\]/);25 });21 test('when program has subcommands then has automatic help command', () => {22 const program = new commander.Command();23 program.command('foo');24 const helpInformation = program.helpInformation();25 assert.match(helpInformation, /help \[command\]/);26 });2727 test('when program has subcommands and specify only unknown option then display help', () => {28 const program = createTestCommand();29 program.allowUnknownOption().command('foo');30 assert.throws(31 () => {32 program.parse(['--unknown'], { from: 'user' });33 },34 {35 code: 'commander.help',36 },37 );38 });28 test('when program has subcommands and specify only unknown option then display help', () => {29 const program = createTestCommand();30 program.allowUnknownOption().command('foo');31 assert.throws(32 () => {33 program.parse(['--unknown'], { from: 'user' });34 },35 {36 code: 'commander.help',37 },38 );39 });4040 test('when program has subcommands and suppress help command then no help command', () => {41 const program = new commander.Command();42 program.addHelpCommand(false);43 program.command('foo');44 const helpInformation = program.helpInformation();45 assert.doesNotMatch(helpInformation, /help \[command\]/);46 });41 test('when program has subcommands and suppress help command then no help command', () => {42 const program = new commander.Command();43 program.addHelpCommand(false);44 program.command('foo');45 const helpInformation = program.helpInformation();46 assert.doesNotMatch(helpInformation, /help \[command\]/);47 });4848 test('when add custom help command then custom help command', () => {49 const program = new commander.Command();50 program.addHelpCommand('myHelp', 'help description');51 const helpInformation = program.helpInformation();52 assert.match(helpInformation, /myHelp +help description/);49 test('when add custom help command then custom help command', () => {50 const program = new commander.Command();51 program.addHelpCommand('myHelp', 'help description');52 const helpInformation = program.helpInformation();53 assert.match(helpInformation, /myHelp +help description/);54 });55 });54});5656describe('help command processed on correct command', () => {57 function makeCommand() {58 const program = new commander.Command();59 program.configureOutput({60 writeOut: () => {},61 writeErr: () => {},62 });57 describe('help command processed on correct command', () => {58 function makeCommand() {59 const program = new commander.Command();60 program.configureOutput({61 writeOut: () => {},62 writeErr: () => {},63 });6464 return program;65 }65 return program;66 }6767 test('when "program help" then program', () => {68 const program = makeCommand();69 program.exitOverride();70 program.command('sub1');71 program.exitOverride(() => {72 throw new Error('program');68 test('when "program help" then program', () => {69 const program = makeCommand();70 program.exitOverride();71 program.command('sub1');72 program.exitOverride(() => {73 throw new Error('program');74 });75 assert.throws(() => {76 program.parse('node test.js help'.split(' '));77 }, /program/);78 });74 assert.throws(() => {75 program.parse('node test.js help'.split(' '));76 }, /program/);77 });7979 test('when "program help unknown" then program', () => {80 const program = makeCommand();81 program.exitOverride();82 program.command('sub1');83 program.exitOverride(() => {84 throw new Error('program');80 test('when "program help unknown" then program', () => {81 const program = makeCommand();82 program.exitOverride();83 program.command('sub1');84 program.exitOverride(() => {85 throw new Error('program');86 });87 assert.throws(() => {88 program.parse('node test.js help unknown'.split(' '));89 }, /program/);90 });86 assert.throws(() => {87 program.parse('node test.js help unknown'.split(' '));88 }, /program/);89 });9191 test('when "program help sub1" then sub1', () => {92 const program = makeCommand();93 program.exitOverride();94 const sub1 = program.command('sub1');95 sub1.exitOverride(() => {96 throw new Error('sub1');92 test('when "program help sub1" then sub1', () => {93 const program = makeCommand();94 program.exitOverride();95 const sub1 = program.command('sub1');96 sub1.exitOverride(() => {97 throw new Error('sub1');98 });99 assert.throws(() => {100 program.parse('node test.js help sub1'.split(' '));101 }, /sub1/);102 });98 assert.throws(() => {99 program.parse('node test.js help sub1'.split(' '));100 }, /sub1/);101 });103103 test('when "program sub1 help sub2" then sub2', () => {104 const program = makeCommand();105 program.exitOverride();106 const sub1 = program.command('sub1');107 const sub2 = sub1.command('sub2');108 sub2.exitOverride(() => {109 throw new Error('sub2');104 test('when "program sub1 help sub2" then sub2', () => {105 const program = makeCommand();106 program.exitOverride();107 const sub1 = program.command('sub1');108 const sub2 = sub1.command('sub2');109 sub2.exitOverride(() => {110 throw new Error('sub2');111 });112 assert.throws(() => {113 program.parse('node test.js sub1 help sub2'.split(' '));114 }, /sub2/);115 });111 assert.throws(() => {112 program.parse('node test.js sub1 help sub2'.split(' '));113 }, /sub2/);114 });116116 test('when default command and "program help" then program', () => {117 const program = makeCommand();118 program.exitOverride();119 program.command('sub1', { isDefault: true });120 program.exitOverride(() => {121 throw new Error('program');117 test('when default command and "program help" then program', () => {118 const program = makeCommand();119 program.exitOverride();120 program.command('sub1', { isDefault: true });121 program.exitOverride(() => {122 throw new Error('program');123 });124 assert.throws(() => {125 program.parse('node test.js help'.split(' '));126 }, /program/);127 });123 assert.throws(() => {124 program.parse('node test.js help'.split(' '));125 }, /program/);126 });128128 test('when no long help flag then "help sub" works', () => {129 const program = makeCommand();130 program.exitOverride();131 program.helpOption('-H');132 const sub = program.command('sub');133 // Patch help for easy way to check called.134 sub.help = () => {135 throw new Error('sub help');136 };137 assert.throws(() => {138 program.parse(['help', 'sub'], { from: 'user' });139 }, /sub help/);140 });129 test('when no long help flag then "help sub" works', () => {130 const program = makeCommand();131 program.exitOverride();132 program.helpOption('-H');133 const sub = program.command('sub');134 // Patch help for easy way to check called.135 sub.help = () => {136 throw new Error('sub help');137 };138 assert.throws(() => {139 program.parse(['help', 'sub'], { from: 'user' });140 }, /sub help/);141 });142142 test('when no help options in sub then "help sub" works', () => {143 const program = makeCommand();144 program.exitOverride();145 const sub = program.command('sub').helpOption(false);146 // Patch help for easy way to check called.147 sub.help = () => {148 throw new Error('sub help');149 };150 assert.throws(() => {151 program.parse(['help', 'sub'], { from: 'user' });152 }, /sub help/);153 });143 test('when no help options in sub then "help sub" works', () => {144 const program = makeCommand();145 program.exitOverride();146 const sub = program.command('sub').helpOption(false);147 // Patch help for easy way to check called.148 sub.help = () => {149 throw new Error('sub help');150 };151 assert.throws(() => {152 program.parse(['help', 'sub'], { from: 'user' });153 }, /sub help/);154 });155155 test('when different help options in sub then "help sub" works', () => {156 const program = makeCommand();157 program.exitOverride();158 const sub = program.command('sub');159 program.helpOption('-h, --help');160 sub.helpOption('-a, --assist');161 // Patch help for easy way to check called.162 sub.help = () => {163 throw new Error('sub help');164 };165 assert.throws(() => {166 program.parse(['help', 'sub'], { from: 'user' });167 }, /sub help/);156 test('when different help options in sub then "help sub" works', () => {157 const program = makeCommand();158 program.exitOverride();159 const sub = program.command('sub');160 program.helpOption('-h, --help');161 sub.helpOption('-a, --assist');162 // Patch help for easy way to check called.163 sub.help = () => {164 throw new Error('sub help');165 };166 assert.throws(() => {167 program.parse(['help', 'sub'], { from: 'user' });168 }, /sub help/);169 });170 });171});
modified:tests/command.helpOption.test.js+1 added-1 removed
1 unmodified line
2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56describe('helpOption', () => {6describe('Command.helpOption()', () => {7 test('when helpOption has custom flags then custom short flag invokes help', (t) => {8 const program = createTestCommand();9 program.helpOption('-c,--custom-help', 'custom help output');10 assert.throws(
117 unmodified lines
modified:tests/command.hook.test.js+370 added-352 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45test('when hook event wrong then throw', () => {6 const program = new commander.Command();7 assert.throws(() => {8 program.hook('silly', () => {});9 });10});1112test('when no action then action hooks not called', (t) => {13 const hook = t.mock.fn();14 const program = new commander.Command();15 program.hook('preAction', hook).hook('postAction', hook);16 program.parse([], { from: 'user' });17 assert.equal(hook.mock.callCount(), 0);18});1920describe('action hooks with synchronous hooks, order', () => {21 test('when hook preAction then hook called before action', () => {22 const calls = [];5describe('Command.hook()', () => {6 test('when hook event wrong then throw', () => {7 const program = new commander.Command();24 program25 .hook('preAction', () => calls.push('before'))26 .action(() => calls.push('action'));27 program.parse([], { from: 'user' });28 assert.deepEqual(calls, ['before', 'action']);8 assert.throws(() => {9 program.hook('silly', () => {});10 });11 });1231 test('when hook postAction then hook called after action', () => {32 const calls = [];13 test('when no action then action hooks not called', (t) => {14 const hook = t.mock.fn();15 const program = new commander.Command();34 program35 .hook('postAction', () => calls.push('after'))36 .action(() => calls.push('action'));16 program.hook('preAction', hook).hook('postAction', hook);17 program.parse([], { from: 'user' });38 assert.deepEqual(calls, ['action', 'after']);18 assert.equal(hook.mock.callCount(), 0);19 });2041 test('when hook preAction twice then hooks called FIFO', () => {42 const calls = [];43 const program = new commander.Command();44 program45 .hook('preAction', () => calls.push('1'))46 .hook('preAction', () => calls.push('2'))47 .action(() => calls.push('action'));48 program.parse([], { from: 'user' });49 assert.deepEqual(calls, ['1', '2', 'action']);50 });21 describe('action hooks with synchronous hooks, order', () => {22 test('when hook preAction then hook called before action', () => {23 const calls = [];24 const program = new commander.Command();25 program26 .hook('preAction', () => calls.push('before'))27 .action(() => calls.push('action'));28 program.parse([], { from: 'user' });29 assert.deepEqual(calls, ['before', 'action']);30 });3152 test('when hook postAction twice then hooks called LIFO', () => {53 const calls = [];54 const program = new commander.Command();55 program56 .hook('postAction', () => calls.push('1'))57 .hook('postAction', () => calls.push('2'))58 .action(() => calls.push('action'));59 program.parse([], { from: 'user' });60 assert.deepEqual(calls, ['action', '2', '1']);61 });32 test('when hook postAction then hook called after action', () => {33 const calls = [];34 const program = new commander.Command();35 program36 .hook('postAction', () => calls.push('after'))37 .action(() => calls.push('action'));38 program.parse([], { from: 'user' });39 assert.deepEqual(calls, ['action', 'after']);40 });4163 test('when hook preAction at program and sub then hooks called program then sub', () => {64 const calls = [];65 const program = new commander.Command();66 program.hook('preAction', () => calls.push('program'));67 program68 .command('sub')69 .hook('preAction', () => calls.push('sub'))70 .action(() => calls.push('action'));71 program.parse(['sub'], { from: 'user' });72 assert.deepEqual(calls, ['program', 'sub', 'action']);73 });42 test('when hook preAction twice then hooks called FIFO', () => {43 const calls = [];44 const program = new commander.Command();45 program46 .hook('preAction', () => calls.push('1'))47 .hook('preAction', () => calls.push('2'))48 .action(() => calls.push('action'));49 program.parse([], { from: 'user' });50 assert.deepEqual(calls, ['1', '2', 'action']);51 });5275 test('when hook postAction at program and sub then hooks called sub then program', () => {76 const calls = [];77 const program = new commander.Command();78 program.hook('postAction', () => calls.push('program'));79 program80 .command('sub')81 .hook('postAction', () => calls.push('sub'))82 .action(() => calls.push('action'));83 program.parse(['sub'], { from: 'user' });84 assert.deepEqual(calls, ['action', 'sub', 'program']);85 });53 test('when hook postAction twice then hooks called LIFO', () => {54 const calls = [];55 const program = new commander.Command();56 program57 .hook('postAction', () => calls.push('1'))58 .hook('postAction', () => calls.push('2'))59 .action(() => calls.push('action'));60 program.parse([], { from: 'user' });61 assert.deepEqual(calls, ['action', '2', '1']);62 });6387 test('when hook everything then hooks called nested', () => {88 const calls = [];89 const program = new commander.Command();90 program91 .hook('preAction', () => calls.push('pb1'))92 .hook('postAction', () => calls.push('pa1'));93 program94 .hook('preAction', () => calls.push('pb2'))95 .hook('postAction', () => calls.push('pa2'));96 program97 .command('sub')98 .hook('preAction', () => calls.push('sb'))99 .hook('postAction', () => calls.push('sa'))100 .action(() => calls.push('action'));101 program.parse(['sub'], { from: 'user' });102 assert.deepEqual(calls, ['pb1', 'pb2', 'sb', 'action', 'sa', 'pa2', 'pa1']);103 });104});64 test('when hook preAction at program and sub then hooks called program then sub', () => {65 const calls = [];66 const program = new commander.Command();67 program.hook('preAction', () => calls.push('program'));68 program69 .command('sub')70 .hook('preAction', () => calls.push('sub'))71 .action(() => calls.push('action'));72 program.parse(['sub'], { from: 'user' });73 assert.deepEqual(calls, ['program', 'sub', 'action']);74 });75106describe('action hooks context', () => {107 test('when hook on program then passed program/program', (t) => {108 const hook = t.mock.fn();109 const program = new commander.Command();110 program.hook('preAction', hook).action(() => {});111 program.parse([], { from: 'user' });112 assert.equal(hook.mock.callCount(), 1);113 const callArgs = hook.mock.calls[0].arguments;114 assert.equal(callArgs[0], program);115 assert.equal(callArgs[1], program);116 });76 test('when hook postAction at program and sub then hooks called sub then program', () => {77 const calls = [];78 const program = new commander.Command();79 program.hook('postAction', () => calls.push('program'));80 program81 .command('sub')82 .hook('postAction', () => calls.push('sub'))83 .action(() => calls.push('action'));84 program.parse(['sub'], { from: 'user' });85 assert.deepEqual(calls, ['action', 'sub', 'program']);86 });87118 test('when hook on program and call sub then passed program/sub', (t) => {119 const hook = t.mock.fn();120 const program = new commander.Command();121 program.hook('preAction', hook);122 const sub = program.command('sub').action(() => {});123 program.parse(['sub'], { from: 'user' });124 assert.equal(hook.mock.callCount(), 1);125 const callArgs = hook.mock.calls[0].arguments;126 assert.equal(callArgs[0], program);127 assert.equal(callArgs[1], sub);88 test('when hook everything then hooks called nested', () => {89 const calls = [];90 const program = new commander.Command();91 program92 .hook('preAction', () => calls.push('pb1'))93 .hook('postAction', () => calls.push('pa1'));94 program95 .hook('preAction', () => calls.push('pb2'))96 .hook('postAction', () => calls.push('pa2'));97 program98 .command('sub')99 .hook('preAction', () => calls.push('sb'))100 .hook('postAction', () => calls.push('sa'))101 .action(() => calls.push('action'));102 program.parse(['sub'], { from: 'user' });103 assert.deepEqual(calls, [104 'pb1',105 'pb2',106 'sb',107 'action',108 'sa',109 'pa2',110 'pa1',111 ]);112 });113 });114130 test('when hook on sub and call sub then passed sub/sub', (t) => {131 const hook = t.mock.fn();132 const program = new commander.Command();133 const sub = program134 .command('sub')135 .hook('preAction', hook)136 .action(() => {});137 program.parse(['sub'], { from: 'user' });138 assert.equal(hook.mock.callCount(), 1);139 const callArgs = hook.mock.calls[0].arguments;140 assert.equal(callArgs[0], sub);141 assert.equal(callArgs[1], sub);142 });115 describe('action hooks context', () => {116 test('when hook on program then passed program/program', (t) => {117 const hook = t.mock.fn();118 const program = new commander.Command();119 program.hook('preAction', hook).action(() => {});120 program.parse([], { from: 'user' });121 assert.equal(hook.mock.callCount(), 1);122 const callArgs = hook.mock.calls[0].arguments;123 assert.equal(callArgs[0], program);124 assert.equal(callArgs[1], program);125 });126127 test('when hook on program and call sub then passed program/sub', (t) => {128 const hook = t.mock.fn();129 const program = new commander.Command();130 program.hook('preAction', hook);131 const sub = program.command('sub').action(() => {});132 program.parse(['sub'], { from: 'user' });133 assert.equal(hook.mock.callCount(), 1);134 const callArgs = hook.mock.calls[0].arguments;135 assert.equal(callArgs[0], program);136 assert.equal(callArgs[1], sub);137 });138139 test('when hook on sub and call sub then passed sub/sub', (t) => {140 const hook = t.mock.fn();141 const program = new commander.Command();142 const sub = program143 .command('sub')144 .hook('preAction', hook)145 .action(() => {});146 program.parse(['sub'], { from: 'user' });147 assert.equal(hook.mock.callCount(), 1);148 const callArgs = hook.mock.calls[0].arguments;149 assert.equal(callArgs[0], sub);150 assert.equal(callArgs[1], sub);151 });152144 test('when hook program on preAction then thisCommand has options set', () => {145 const program = new commander.Command();146 program147 .option('--debug')148 .hook('preAction', (thisCommand) => {153 test('when hook program on preAction then thisCommand has options set', () => {154 const program = new commander.Command();155 program156 .option('--debug')157 .hook('preAction', (thisCommand) => {158 assert.equal(thisCommand.opts().debug, true);159 })160 .action(() => {});161 program.parse(['--debug'], { from: 'user' });162 });163164 test('when hook program on preAction and call sub then thisCommand has program options set', () => {165 const program = new commander.Command();166 program.option('--debug').hook('preAction', (thisCommand) => {167 assert.equal(thisCommand.opts().debug, true);150 })151 .action(() => {});152 program.parse(['--debug'], { from: 'user' });153 });168 });169 program.command('sub').action(() => {});170 program.parse(['sub', '--debug'], { from: 'user' });171 });172155 test('when hook program on preAction and call sub then thisCommand has program options set', () => {156 const program = new commander.Command();157 program.option('--debug').hook('preAction', (thisCommand) => {158 assert.equal(thisCommand.opts().debug, true);173 test('when hook program on preAction and call sub then actionCommand has sub options set', () => {174 const program = new commander.Command();175 program.hook('preAction', (thisCommand, actionCommand) => {176 assert.equal(actionCommand.opts().debug, true);177 });178 program179 .command('sub')180 .option('--debug')181 .action(() => {});182 program.parse(['sub', '--debug'], { from: 'user' });183 });160 program.command('sub').action(() => {});161 program.parse(['sub', '--debug'], { from: 'user' });162 });184164 test('when hook program on preAction and call sub then actionCommand has sub options set', () => {165 const program = new commander.Command();166 program.hook('preAction', (thisCommand, actionCommand) => {167 assert.equal(actionCommand.opts().debug, true);185 test('when hook program on preAction then actionCommand has args set', () => {186 const program = new commander.Command();187 program188 .argument('[arg]')189 .hook('preAction', (thisCommand, actionCommand) => {190 assert.deepEqual(actionCommand.args, ['value']);191 })192 .action(() => {});193 program.parse(['value'], { from: 'user' });194 });169 program170 .command('sub')171 .option('--debug')172 .action(() => {});173 program.parse(['sub', '--debug'], { from: 'user' });174 });195176 test('when hook program on preAction then actionCommand has args set', () => {177 const program = new commander.Command();178 program179 .argument('[arg]')180 .hook('preAction', (thisCommand, actionCommand) => {181 assert.deepEqual(actionCommand.args, ['value']);182 })183 .action(() => {});184 program.parse(['value'], { from: 'user' });185 });196 test('when hook program on preAction then actionCommand has args set with options removed', () => {197 const program = new commander.Command();198 program199 .argument('[arg]')200 .option('--debug')201 .hook('preAction', (thisCommand, actionCommand) => {202 assert.deepEqual(actionCommand.args, ['value']);203 })204 .action(() => {});205 program.parse(['value', '--debug'], { from: 'user' });206 });207187 test('when hook program on preAction then actionCommand has args set with options removed', () => {188 const program = new commander.Command();189 program190 .argument('[arg]')191 .option('--debug')192 .hook('preAction', (thisCommand, actionCommand) => {208 test('when hook program on preAction and call sub then thisCommand has program args set', () => {209 const program = new commander.Command();210 program.argument('[arg]').hook('preAction', (thisCommand) => {211 assert.deepEqual(thisCommand.args, ['sub', 'value']);212 });213 program214 .command('sub')215 .argument('<arg>')216 .action(() => {});217 program.parse(['sub', 'value'], { from: 'user' });218 });219220 test('when hook program on preAction and call sub then actionCommand has sub args set', () => {221 const program = new commander.Command();222 program.hook('preAction', (thisCommand, actionCommand) => {223 assert.deepEqual(actionCommand.args, ['value']);194 })195 .action(() => {});196 program.parse(['value', '--debug'], { from: 'user' });224 });225 program226 .command('sub')227 .argument('<arg>')228 .action(() => {});229 program.parse(['sub', 'value'], { from: 'user' });230 });231 });232199 test('when hook program on preAction and call sub then thisCommand has program args set', () => {200 const program = new commander.Command();201 program.argument('[arg]').hook('preAction', (thisCommand) => {202 assert.deepEqual(thisCommand.args, ['sub', 'value']);233 describe('action hooks async', () => {234 test('when async preAction then async from preAction', async () => {235 const calls = [];236 const program = new commander.Command();237 program238 .hook('preAction', async () => {239 await 0;240 calls.push('before');241 })242 .action(() => calls.push('action'));243 const result = program.parseAsync([], { from: 'user' });244 assert.deepEqual(calls, []);245 await result;246 assert.deepEqual(calls, ['before', 'action']);247 });204 program205 .command('sub')206 .argument('<arg>')207 .action(() => {});208 program.parse(['sub', 'value'], { from: 'user' });209 });248211 test('when hook program on preAction and call sub then actionCommand has sub args set', () => {212 const program = new commander.Command();213 program.hook('preAction', (thisCommand, actionCommand) => {214 assert.deepEqual(actionCommand.args, ['value']);249 test('when async postAction then async from postAction', async () => {250 const calls = [];251 const program = new commander.Command();252 program253 .hook('postAction', async () => {254 await 0;255 calls.push('after');256 })257 .action(() => calls.push('action'));258 const result = program.parseAsync([], { from: 'user' });259 assert.deepEqual(calls, ['action']);260 await result;261 assert.deepEqual(calls, ['action', 'after']);262 });216 program217 .command('sub')218 .argument('<arg>')219 .action(() => {});220 program.parse(['sub', 'value'], { from: 'user' });221 });222});263224describe('action hooks async', () => {225 test('when async preAction then async from preAction', async () => {226 const calls = [];227 const program = new commander.Command();228 program229 .hook('preAction', async () => {230 await 0;231 calls.push('before');232 })233 .action(() => calls.push('action'));234 const result = program.parseAsync([], { from: 'user' });235 assert.deepEqual(calls, []);236 await result;237 assert.deepEqual(calls, ['before', 'action']);238 });264 test('when async action then async from action', async () => {265 const calls = [];266 const program = new commander.Command();267 program268 .hook('preAction', () => calls.push('before'))269 .hook('postAction', () => calls.push('after'))270 .action(async () => {271 await 0;272 calls.push('action');273 });274 const result = program.parseAsync([], { from: 'user' });275 assert.deepEqual(calls, ['before']);276 await result;277 assert.deepEqual(calls, ['before', 'action', 'after']);278 });279240 test('when async postAction then async from postAction', async () => {241 const calls = [];242 const program = new commander.Command();243 program244 .hook('postAction', async () => {245 await 0;246 calls.push('after');247 })248 .action(() => calls.push('action'));249 const result = program.parseAsync([], { from: 'user' });250 assert.deepEqual(calls, ['action']);251 await result;252 assert.deepEqual(calls, ['action', 'after']);253 });280 test('when async first preAction then async from first preAction', async () => {281 const calls = [];282 const program = new commander.Command();283 program284 .hook('preAction', async () => {285 await 0;286 calls.push('1');287 })288 .hook('preAction', () => calls.push('2'))289 .action(() => calls.push('action'));290 const result = program.parseAsync([], { from: 'user' });291 assert.deepEqual(calls, []);292 await result;293 assert.deepEqual(calls, ['1', '2', 'action']);294 });295255 test('when async action then async from action', async () => {256 const calls = [];257 const program = new commander.Command();258 program259 .hook('preAction', () => calls.push('before'))260 .hook('postAction', () => calls.push('after'))261 .action(async () => {262 await 0;263 calls.push('action');264 });265 const result = program.parseAsync([], { from: 'user' });266 assert.deepEqual(calls, ['before']);267 await result;268 assert.deepEqual(calls, ['before', 'action', 'after']);269 });296 test('when async second preAction then async from second preAction', async () => {297 const calls = [];298 const program = new commander.Command();299 program300 .hook('preAction', () => calls.push('1'))301 .hook('preAction', async () => {302 await 0;303 calls.push('2');304 })305 .action(() => calls.push('action'));306 const result = program.parseAsync([], { from: 'user' });307 assert.deepEqual(calls, ['1']);308 await result;309 assert.deepEqual(calls, ['1', '2', 'action']);310 });311271 test('when async first preAction then async from first preAction', async () => {272 const calls = [];273 const program = new commander.Command();274 program275 .hook('preAction', async () => {276 await 0;277 calls.push('1');278 })279 .hook('preAction', () => calls.push('2'))280 .action(() => calls.push('action'));281 const result = program.parseAsync([], { from: 'user' });282 assert.deepEqual(calls, []);283 await result;284 assert.deepEqual(calls, ['1', '2', 'action']);285 });312 test('when async hook everything then hooks called nested', async () => {313 const calls = [];314 const program = new commander.Command();315 program316 .hook('preAction', async () => {317 await 0;318 calls.push('pb1');319 })320 .hook('postAction', async () => {321 await 0;322 calls.push('pa1');323 });324 program325 .hook('preAction', async () => {326 await 0;327 calls.push('pb2');328 })329 .hook('postAction', async () => {330 await 0;331 calls.push('pa2');332 });333 program334 .command('sub')335 .hook('preAction', async () => {336 await 0;337 calls.push('sb');338 })339 .hook('postAction', async () => {340 await 0;341 calls.push('sa');342 })343 .action(async () => {344 await 0;345 calls.push('action');346 });347 const result = program.parseAsync(['sub'], { from: 'user' });348 assert.deepEqual(calls, []);349 await result;350 assert.deepEqual(calls, [351 'pb1',352 'pb2',353 'sb',354 'action',355 'sa',356 'pa2',357 'pa1',358 ]);359 });360287 test('when async second preAction then async from second preAction', async () => {288 const calls = [];289 const program = new commander.Command();290 program291 .hook('preAction', () => calls.push('1'))292 .hook('preAction', async () => {361 test('preSubcommand hook should work', async () => {362 const calls = [];363 const program = new commander.Command();364 program.hook('preSubcommand', async () => {365 await 0;294 calls.push('2');295 })296 .action(() => calls.push('action'));297 const result = program.parseAsync([], { from: 'user' });298 assert.deepEqual(calls, ['1']);299 await result;300 assert.deepEqual(calls, ['1', '2', 'action']);301 });302303 test('when async hook everything then hooks called nested', async () => {304 const calls = [];305 const program = new commander.Command();306 program307 .hook('preAction', async () => {308 await 0;309 calls.push('pb1');310 })311 .hook('postAction', async () => {312 await 0;313 calls.push('pa1');366 calls.push(0);367 });315 program316 .hook('preAction', async () => {317 await 0;318 calls.push('pb2');368 program.command('sub').action(async () => {369 await 1;370 calls.push(1);319 })320 .hook('postAction', async () => {321 await 0;322 calls.push('pa2');371 });324 program325 .command('sub')326 .hook('preAction', async () => {327 await 0;328 calls.push('sb');329 })330 .hook('postAction', async () => {331 await 0;332 calls.push('sa');333 })334 .action(async () => {335 await 0;336 calls.push('action');372 program.action(async () => {373 await 2;374 calls.push(2);375 });338 const result = program.parseAsync(['sub'], { from: 'user' });339 assert.deepEqual(calls, []);340 await result;341 assert.deepEqual(calls, ['pb1', 'pb2', 'sb', 'action', 'sa', 'pa2', 'pa1']);342 });343344 test('preSubcommand hook should work', async () => {345 const calls = [];346 const program = new commander.Command();347 program.hook('preSubcommand', async () => {348 await 0;349 calls.push(0);376 const result = program.parseAsync(['sub'], { from: 'user' });377 assert.deepEqual(calls, []);378 await result;379 assert.deepEqual(calls, [0, 1]);380 });351 program.command('sub').action(async () => {352 await 1;353 calls.push(1);354 });355 program.action(async () => {356 await 2;357 calls.push(2);358 });359 const result = program.parseAsync(['sub'], { from: 'user' });360 assert.deepEqual(calls, []);361 await result;362 assert.deepEqual(calls, [0, 1]);363 });364 test('preSubcommand hook should effective for direct subcommands', async () => {365 const calls = [];366 const program = new commander.Command();367 program.hook('preSubcommand', async (thisCommand, subCommand) => {368 await 'preSubcommand';369 calls.push('preSubcommand');370 calls.push(subCommand.name());381 test('preSubcommand hook should effective for direct subcommands', async () => {382 const calls = [];383 const program = new commander.Command();384 program.hook('preSubcommand', async (thisCommand, subCommand) => {385 await 'preSubcommand';386 calls.push('preSubcommand');387 calls.push(subCommand.name());371 });372 program373 .command('first')374 .action(async () => {375 await 'first';376 calls.push('first');377 })378 .command('second')379 .action(async () => {380 await 'second';381 calls.push('second');382 })383 .command('third')384 .action(async () => {385 await 'third';386 calls.push('third');388 });389 program390 .command('first')391 .action(async () => {392 await 'first';393 calls.push('first');394 })395 .command('second')396 .action(async () => {397 await 'second';398 calls.push('second');399 })400 .command('third')401 .action(async () => {402 await 'third';403 calls.push('third');404 });388 program.action(async () => {389 await 2;390 calls.push(2);405 program.action(async () => {406 await 2;407 calls.push(2);408 });409 const result = program.parseAsync(['first', 'second', 'third'], {410 from: 'user',411 });412 assert.deepEqual(calls, []);413 await result;414 assert.deepEqual(calls, ['preSubcommand', 'first', 'third']);415 });392 const result = program.parseAsync(['first', 'second', 'third'], {393 from: 'user',394 });395 assert.deepEqual(calls, []);396 await result;397 assert.deepEqual(calls, ['preSubcommand', 'first', 'third']);416 });417});
modified:tests/command.name.test.js+44 added-42 removed
1const path = require('path');2const commander = require('../');3const { test } = require('node:test');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56describe('Command.name()', () => {6test('when construct with name then name is set', () => {7 const program = new commander.Command('foo');8 assert.equal(program.name(), 'foo');9});7 test('when construct with name then name is set', () => {8 const program = new commander.Command('foo');9 assert.equal(program.name(), 'foo');10 });1111test('when set program name and parse then name is as assigned', () => {12 const program = new commander.Command();13 program.name('custom');14 program.parse(['node', 'test']);15 assert.equal(program.name(), 'custom');16});12 test('when set program name and parse then name is as assigned', () => {13 const program = new commander.Command();14 program.name('custom');15 program.parse(['node', 'test']);16 assert.equal(program.name(), 'custom');17 });1818test('when program name not set and parse with script argument then plain name is found from script name', () => {19 const program = new commander.Command();20 program.parse(['node', path.resolve(process.cwd(), 'script.js')], {21 from: 'node',19 test('when program name not set and parse with script argument then plain name is found from script name', () => {20 const program = new commander.Command();21 program.parse(['node', path.resolve(process.cwd(), 'script.js')], {22 from: 'node',23 });24 assert.equal(program.name(), 'script');25 });23 assert.equal(program.name(), 'script');24});2626test('when command name not set and no script argument in parse then name is program', () => {27 const program = new commander.Command();28 program.parse([], { from: 'user' });29 assert.equal(program.name(), 'program');30});27 test('when command name not set and no script argument in parse then name is program', () => {28 const program = new commander.Command();29 program.parse([], { from: 'user' });30 assert.equal(program.name(), 'program');31 });3232test('when add command then command is named', () => {33 const program = new commander.Command();34 const subcommand = program.command('mycommand <file>');35 assert.equal(subcommand.name(), 'mycommand');36});33 test('when add command then command is named', () => {34 const program = new commander.Command();35 const subcommand = program.command('mycommand <file>');36 assert.equal(subcommand.name(), 'mycommand');37 });3838test('when set program name then name appears in help', () => {39 const program = new commander.Command();40 program.name('custom-name');41 const helpInformation = program.helpInformation();42 assert.match(helpInformation, /^Usage: custom-name/);43});39 test('when set program name then name appears in help', () => {40 const program = new commander.Command();41 program.name('custom-name');42 const helpInformation = program.helpInformation();43 assert.match(helpInformation, /^Usage: custom-name/);44 });4545test('when pass path to nameFromFilename then name is plain name', () => {46 const program = new commander.Command();47 program.nameFromFilename(path.resolve(process.cwd(), 'foo.js'));48 assert.equal(program.name(), 'foo');49});46 test('when pass path to nameFromFilename then name is plain name', () => {47 const program = new commander.Command();48 program.nameFromFilename(path.resolve(process.cwd(), 'foo.js'));49 assert.equal(program.name(), 'foo');50 });5151test('when pass __filename to nameFromFilename then name is plain name of this file', () => {52 const program = new commander.Command();53 program.nameFromFilename(__filename);54 assert.equal(program.name(), 'command.name.test');52 test('when pass __filename to nameFromFilename then name is plain name of this file', () => {53 const program = new commander.Command();54 program.nameFromFilename(__filename);55 assert.equal(program.name(), 'command.name.test');56 });57});
modified:tests/command.onCommand.test.js+1 added-1 removed
3 unmodified lines
45// The action handler used to be implemented using command events and listeners.6// Now, this is mostly just for backwards compatibility.78describe(".command('*')", () => {8describe("Command.command('*')", () => {9 test('when action handler for subcommand then emit command:subcommand', (t) => {10 const mockListener = t.mock.fn();11 const program = new commander.Command();12 program.command('sub').action(() => {});
25 unmodified lines
modified:tests/command.option-misuse.test.js+20 added-18 removed
1const { Command, Option } = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45// It is a reasonable and easy mistake to pass Option to .option(). Detect this6// and offer advice.78const expectedMessage =9 'To add an Option object use addOption() instead of option() or requiredOption()';1011describe('Command methods detect and explains misuse when incorrectly pass Option object', () => {11test('when pass Option to .option() then throw', () => {12 const program = new Command();12 test('when pass Option to .option() then throw', () => {13 const program = new Command();1414 assert.throws(15 () => {16 program.option(new Option('-d, debug'));17 },18 { message: expectedMessage },19 );20});15 assert.throws(16 () => {17 program.option(new Option('-d, debug'));18 },19 { message: expectedMessage },20 );21 });2222test('when pass Option to .requiredOption() then throw', () => {23 const program = new Command();23 test('when pass Option to .requiredOption() then throw', () => {24 const program = new Command();2525 assert.throws(26 () => {27 program.requiredOption(new Option('-d, debug'));28 },29 { message: expectedMessage },30 );26 assert.throws(27 () => {28 program.requiredOption(new Option('-d, debug'));29 },30 { message: expectedMessage },31 );32 });33});
modified:tests/command.parse.test.js+353 added-336 removed
7 unmodified lines
89// (If mutating process.argv and process.execArgv causes problems, could add utility10// functions to get them and then mock the functions for tests.)1112describe('Command.parse()', () => {12describe('.parse() args from', () => {13 test('when no args then use process.argv and app/script/args', () => {14 const program = new commander.Command();15 program.argument('[args...]');16 const hold = process.argv;17 process.argv = 'node script.js user'.split(' ');18 program.parse();19 process.argv = hold;20 assert.deepEqual(program.args, ['user']);21 });13 describe('.parse() explicit (from:) and autodetection of args format parsing', () => {14 test('when no args then use process.argv and app/script/args', () => {15 const program = new commander.Command();16 program.argument('[args...]');17 const hold = process.argv;18 process.argv = 'node script.js user'.split(' ');19 program.parse();20 process.argv = hold;21 assert.deepEqual(program.args, ['user']);22 });2323 test('when no args and electron properties and not default app then use process.argv and app/args', () => {24 const program = new commander.Command();25 program.argument('[args...]');26 const holdArgv = process.argv;27 process.versions.electron = '1.2.3';28 process.argv = 'node user'.split(' ');29 program.parse();30 delete process.versions.electron;31 process.argv = holdArgv;32 assert.deepEqual(program.args, ['user']);33 });24 test('when no args and electron properties and not default app then use process.argv and app/args', () => {25 const program = new commander.Command();26 program.argument('[args...]');27 const holdArgv = process.argv;28 process.versions.electron = '1.2.3';29 process.argv = 'node user'.split(' ');30 program.parse();31 delete process.versions.electron;32 process.argv = holdArgv;33 assert.deepEqual(program.args, ['user']);34 });3535 test('when args then app/script/args', () => {36 const program = new commander.Command();37 program.argument('[args...]');38 program.parse('node script.js user'.split(' '));39 assert.deepEqual(program.args, ['user']);40 });36 test('when args then app/script/args', () => {37 const program = new commander.Command();38 program.argument('[args...]');39 program.parse('node script.js user'.split(' '));40 assert.deepEqual(program.args, ['user']);41 });4242 test('when args from "node" then app/script/args', () => {43 const program = new commander.Command();44 program.argument('[args...]');45 program.parse('node script.js user'.split(' '), { from: 'node' });46 assert.deepEqual(program.args, ['user']);47 });43 test('when args from "node" then app/script/args', () => {44 const program = new commander.Command();45 program.argument('[args...]');46 program.parse('node script.js user'.split(' '), { from: 'node' });47 assert.deepEqual(program.args, ['user']);48 });4949 test('when args from "electron" and not default app then app/args', () => {50 const program = new commander.Command();51 program.argument('[args...]');52 const hold = process.defaultApp;53 process.defaultApp = undefined;54 program.parse('customApp user'.split(' '), { from: 'electron' });55 process.defaultApp = hold;56 assert.deepEqual(program.args, ['user']);57 });50 test('when args from "electron" and not default app then app/args', () => {51 const program = new commander.Command();52 program.argument('[args...]');53 const hold = process.defaultApp;54 process.defaultApp = undefined;55 program.parse('customApp user'.split(' '), { from: 'electron' });56 process.defaultApp = hold;57 assert.deepEqual(program.args, ['user']);58 });5959 test('when args from "electron" and default app then app/script/args', () => {60 const program = new commander.Command();61 program.argument('[args...]');62 const hold = process.defaultApp;63 process.defaultApp = true;64 program.parse('electron script user'.split(' '), { from: 'electron' });65 process.defaultApp = hold;66 assert.deepEqual(program.args, ['user']);67 });60 test('when args from "electron" and default app then app/script/args', () => {61 const program = new commander.Command();62 program.argument('[args...]');63 const hold = process.defaultApp;64 process.defaultApp = true;65 program.parse('electron script user'.split(' '), { from: 'electron' });66 process.defaultApp = hold;67 assert.deepEqual(program.args, ['user']);68 });6969 test('when args from "user" then args', () => {70 const program = new commander.Command();71 program.argument('[args...]');72 program.parse('user'.split(' '), { from: 'user' });73 assert.deepEqual(program.args, ['user']);74 });70 test('when args from "user" then args', () => {71 const program = new commander.Command();72 program.argument('[args...]');73 program.parse('user'.split(' '), { from: 'user' });74 assert.deepEqual(program.args, ['user']);75 });7676 test('when args from "silly" then throw', () => {77 const program = new commander.Command();78 program.argument('[args...]');79 assert.throws(() => {80 program.parse(['node', 'script.js'], { from: 'silly' });77 test('when args from "silly" then throw', () => {78 const program = new commander.Command();79 program.argument('[args...]');80 assert.throws(() => {81 program.parse(['node', 'script.js'], { from: 'silly' });82 });83 });82 });8484 describe('when node execArgv includes node flags', () => {85 ['-e', '--eval', '-p', '--print'].forEach((flag) => {86 test(`when node execArgv includes ${flag} then app/args`, () => {87 const program = new commander.Command();88 program.argument('[args...]');89 const holdExecArgv = process.execArgv;90 const holdArgv = process.argv;91 process.argv = ['node', 'user-arg'];92 process.execArgv = [flag, 'console.log("hello, world")'];93 program.parse();94 process.argv = holdArgv;95 process.execArgv = holdExecArgv;96 assert.deepEqual(program.args, ['user-arg']);97 process.execArgv = holdExecArgv;85 describe('when node execArgv includes node flags', () => {86 ['-e', '--eval', '-p', '--print'].forEach((flag) => {87 test(`when node execArgv includes ${flag} then app/args`, () => {88 const program = new commander.Command();89 program.argument('[args...]');90 const holdExecArgv = process.execArgv;91 const holdArgv = process.argv;92 process.argv = ['node', 'user-arg'];93 process.execArgv = [flag, 'console.log("hello, world")'];94 program.parse();95 process.argv = holdArgv;96 process.execArgv = holdExecArgv;97 assert.deepEqual(program.args, ['user-arg']);98 process.execArgv = holdExecArgv;99 });100 });101 });102 });101});103103describe('return type', () => {104 test('when call .parse then returns program', () => {105 const program = new commander.Command();106 program.argument('[args...]');107 program.action(() => {});104 describe('return type', () => {105 test('when call .parse then returns program', () => {106 const program = new commander.Command();107 program.argument('[args...]');108 program.action(() => {});109109 const result = program.parse(['node', 'test']);110 assert.equal(result, program);111 });110 const result = program.parse(['node', 'test']);111 assert.equal(result, program);112 });113113 test('when await .parseAsync then returns program', async () => {114 const program = new commander.Command();115 program.argument('[args...]');116 program.action(() => {});114 test('when await .parseAsync then returns program', async () => {115 const program = new commander.Command();116 program.argument('[args...]');117 program.action(() => {});118118 const result = await program.parseAsync(['node', 'test']);119 assert.equal(result, program);119 const result = await program.parseAsync(['node', 'test']);120 assert.equal(result, program);121 });122 });121});123123// Easy mistake to make when writing unit tests124test('when parse strings instead of array then throw', () => {125 const program = new commander.Command();126 program.argument('[args...]');127 assert.throws(() => {128 program.parse('node', 'test');129 });130});131132describe('parse parameter is treated as readonly, per TypeScript declaration', () => {133 test('when parse called then parameter does not change', () => {124 // Easy mistake to make when writing unit tests125 test('when parse strings instead of array then throw', () => {126 const program = new commander.Command();127 program.argument('[args...]');136 program.option('--debug');137 const original = ['node', '--debug', 'arg'];138 const param = original.slice();139 program.parse(param);140 assert.deepEqual(param, original);128 assert.throws(() => {129 program.parse('node', 'test');130 });131 });132143 test('when parse called and parsed args later changed then parameter does not change', () => {144 const program = new commander.Command();145 program.argument('[args...]');146 program.option('--debug');147 const original = ['node', '--debug', 'arg'];148 const param = original.slice();149 program.parse(param);150 program.args.length = 0;151 program.rawArgs.length = 0;152 assert.deepEqual(param, original);153 });133 describe('parse parameter is treated as readonly, per TypeScript declaration', () => {134 test('when parse called then parameter does not change', () => {135 const program = new commander.Command();136 program.argument('[args...]');137 program.option('--debug');138 const original = ['node', '--debug', 'arg'];139 const param = original.slice();140 program.parse(param);141 assert.deepEqual(param, original);142 });143155 test('when parse called and param later changed then parsed args do not change', () => {156 const program = new commander.Command();157 program.argument('[args...]');158 program.option('--debug');159 const param = ['node', '--debug', 'arg'];160 program.parse(param);161 const oldArgs = program.args.slice();162 const oldRawArgs = program.rawArgs.slice();163 param.length = 0;164 assert.deepEqual(program.args, oldArgs);165 assert.deepEqual(program.rawArgs, oldRawArgs);166 });167});144 test('when parse called and parsed args later changed then parameter does not change', () => {145 const program = new commander.Command();146 program.argument('[args...]');147 program.option('--debug');148 const original = ['node', '--debug', 'arg'];149 const param = original.slice();150 program.parse(param);151 program.args.length = 0;152 program.rawArgs.length = 0;153 assert.deepEqual(param, original);154 });155169describe('parseAsync parameter is treated as readonly, per TypeScript declaration', () => {170 test('when parse called then parameter does not change', async () => {171 const program = new commander.Command();172 program.argument('[args...]');173 program.option('--debug');174 const original = ['node', '--debug', 'arg'];175 const param = original.slice();176 await program.parseAsync(param);177 assert.deepEqual(param, original);156 test('when parse called and param later changed then parsed args do not change', () => {157 const program = new commander.Command();158 program.argument('[args...]');159 program.option('--debug');160 const param = ['node', '--debug', 'arg'];161 program.parse(param);162 const oldArgs = program.args.slice();163 const oldRawArgs = program.rawArgs.slice();164 param.length = 0;165 assert.deepEqual(program.args, oldArgs);166 assert.deepEqual(program.rawArgs, oldRawArgs);167 });168 });169180 test('when parseAsync called and parsed args later changed then parameter does not change', async () => {181 const program = new commander.Command();182 program.argument('[args...]');183 program.option('--debug');184 const original = ['node', '--debug', 'arg'];185 const param = original.slice();186 await program.parseAsync(param);187 program.args.length = 0;188 program.rawArgs.length = 0;189 assert.deepEqual(param, original);190 });170 describe('parseAsync parameter is treated as readonly, per TypeScript declaration', () => {171 test('when parse called then parameter does not change', async () => {172 const program = new commander.Command();173 program.argument('[args...]');174 program.option('--debug');175 const original = ['node', '--debug', 'arg'];176 const param = original.slice();177 await program.parseAsync(param);178 assert.deepEqual(param, original);179 });180192 test('when parseAsync called and param later changed then parsed args do not change', async () => {193 const program = new commander.Command();194 program.argument('[args...]');195 program.option('--debug');196 const param = ['node', '--debug', 'arg'];197 await program.parseAsync(param);198 const oldArgs = program.args.slice();199 const oldRawArgs = program.rawArgs.slice();200 param.length = 0;201 assert.deepEqual(program.args, oldArgs);202 assert.deepEqual(program.rawArgs, oldRawArgs);181 test('when parseAsync called and parsed args later changed then parameter does not change', async () => {182 const program = new commander.Command();183 program.argument('[args...]');184 program.option('--debug');185 const original = ['node', '--debug', 'arg'];186 const param = original.slice();187 await program.parseAsync(param);188 program.args.length = 0;189 program.rawArgs.length = 0;190 assert.deepEqual(param, original);191 });192193 test('when parseAsync called and param later changed then parsed args do not change', async () => {194 const program = new commander.Command();195 program.argument('[args...]');196 program.option('--debug');197 const param = ['node', '--debug', 'arg'];198 await program.parseAsync(param);199 const oldArgs = program.args.slice();200 const oldRawArgs = program.rawArgs.slice();201 param.length = 0;202 assert.deepEqual(program.args, oldArgs);203 assert.deepEqual(program.rawArgs, oldRawArgs);204 });205 });204});206206describe('.parse() called multiple times', () => {207 test('when use boolean options then option values reset', () => {208 const program = new commander.Command().option('--black').option('--white');207 describe('.parse() called multiple times', () => {208 test('when use boolean options then option values reset', () => {209 const program = new commander.Command()210 .option('--black')211 .option('--white');212210 program.parse(['--black'], { from: 'user' });211 assert.deepEqual(program.opts(), { black: true });213 program.parse(['--black'], { from: 'user' });214 assert.deepEqual(program.opts(), { black: true });215213 program.parse(['--white'], { from: 'user' });214 assert.deepEqual(program.opts(), { white: true });215 });216 program.parse(['--white'], { from: 'user' });217 assert.deepEqual(program.opts(), { white: true });218 });219217 test('when use options with option-argument then option values and sources reset', () => {218 const program = new commander.Command()219 .option('-f, --foo <value>')220 .option('-b, --bar <value>');220 test('when use options with option-argument then option values and sources reset', () => {221 const program = new commander.Command()222 .option('-f, --foo <value>')223 .option('-b, --bar <value>');224222 program.parse(['--foo', 'FOO'], { from: 'user' });223 assert.deepEqual(program.opts(), { foo: 'FOO' });224 assert.equal(program.getOptionValueSource('foo'), 'cli');225 assert.equal(program.getOptionValueSource('bar'), undefined);225 program.parse(['--foo', 'FOO'], { from: 'user' });226 assert.deepEqual(program.opts(), { foo: 'FOO' });227 assert.equal(program.getOptionValueSource('foo'), 'cli');228 assert.equal(program.getOptionValueSource('bar'), undefined);229227 program.parse(['--bar', 'BAR'], { from: 'user' });228 assert.deepEqual(program.opts(), { bar: 'BAR' });229 assert.equal(program.getOptionValueSource('foo'), undefined);230 assert.equal(program.getOptionValueSource('bar'), 'cli');231 });230 program.parse(['--bar', 'BAR'], { from: 'user' });231 assert.deepEqual(program.opts(), { bar: 'BAR' });232 assert.equal(program.getOptionValueSource('foo'), undefined);233 assert.equal(program.getOptionValueSource('bar'), 'cli');234 });235233 test('when use options with option-argument and default then option values and sources reset', () => {234 const program = new commander.Command()235 .option('-f, --foo <value>', 'description', 'default-FOO')236 .option('-b, --bar <value>', 'description', 'default-BAR');236 test('when use options with option-argument and default then option values and sources reset', () => {237 const program = new commander.Command()238 .option('-f, --foo <value>', 'description', 'default-FOO')239 .option('-b, --bar <value>', 'description', 'default-BAR');240238 program.parse(['--foo', 'FOO'], { from: 'user' });239 assert.deepEqual(program.opts(), { foo: 'FOO', bar: 'default-BAR' });240 assert.equal(program.getOptionValueSource('foo'), 'cli');241 assert.equal(program.getOptionValueSource('bar'), 'default');241 program.parse(['--foo', 'FOO'], { from: 'user' });242 assert.deepEqual(program.opts(), { foo: 'FOO', bar: 'default-BAR' });243 assert.equal(program.getOptionValueSource('foo'), 'cli');244 assert.equal(program.getOptionValueSource('bar'), 'default');245243 program.parse(['--bar', 'BAR'], { from: 'user' });244 assert.deepEqual(program.opts(), { foo: 'default-FOO', bar: 'BAR' });245 assert.equal(program.getOptionValueSource('foo'), 'default');246 assert.equal(program.getOptionValueSource('bar'), 'cli');247 });246 program.parse(['--bar', 'BAR'], { from: 'user' });247 assert.deepEqual(program.opts(), { foo: 'default-FOO', bar: 'BAR' });248 assert.equal(program.getOptionValueSource('foo'), 'default');249 assert.equal(program.getOptionValueSource('bar'), 'cli');250 });251249 test('when use negated options then option values reset', () => {250 const program = new commander.Command()251 .option('--no-foo')252 .option('--no-bar');252 test('when use negated options then option values reset', () => {253 const program = new commander.Command()254 .option('--no-foo')255 .option('--no-bar');256254 program.parse(['--no-foo'], { from: 'user' });255 assert.deepEqual(program.opts(), { foo: false, bar: true });257 program.parse(['--no-foo'], { from: 'user' });258 assert.deepEqual(program.opts(), { foo: false, bar: true });259257 program.parse(['--no-bar'], { from: 'user' });258 assert.deepEqual(program.opts(), { foo: true, bar: false });259 });260 program.parse(['--no-bar'], { from: 'user' });261 assert.deepEqual(program.opts(), { foo: true, bar: false });262 });263261 test('when use variadic option then option values reset', () => {262 const program = new commander.Command().option('--var <items...>');264 test('when use variadic option then option values reset', () => {265 const program = new commander.Command().option('--var <items...>');266264 program.parse(['--var', 'a', 'b'], { from: 'user' });265 assert.deepEqual(program.opts(), { var: ['a', 'b'] });267 program.parse(['--var', 'a', 'b'], { from: 'user' });268 assert.deepEqual(program.opts(), { var: ['a', 'b'] });269267 program.parse(['--var', 'c'], { from: 'user' });268 assert.deepEqual(program.opts(), { var: ['c'] });269 });270 program.parse(['--var', 'c'], { from: 'user' });271 assert.deepEqual(program.opts(), { var: ['c'] });272 });273271 test('when use collect example then option value resets', () => {272 function collect(value, previous) {273 return previous.concat([value]);274 }275 const program = new commander.Command();276 program.option('-c, --collect <value>', 'repeatable value', collect, []);274 test('when use collect example then option value resets', () => {275 function collect(value, previous) {276 return previous.concat([value]);277 }278 const program = new commander.Command();279 program.option('-c, --collect <value>', 'repeatable value', collect, []);280278 program.parse(['-c', 'a', '-c', 'b'], { from: 'user' });279 assert.deepEqual(program.opts(), { collect: ['a', 'b'] });281 program.parse(['-c', 'a', '-c', 'b'], { from: 'user' });282 assert.deepEqual(program.opts(), { collect: ['a', 'b'] });283281 program.parse(['-c', 'c'], { from: 'user' });282 assert.deepEqual(program.opts(), { collect: ['c'] });283 });284 program.parse(['-c', 'c'], { from: 'user' });285 assert.deepEqual(program.opts(), { collect: ['c'] });286 });287285 test('when use increaseVerbosity example then option value resets', () => {286 function increaseVerbosity(dummyValue, previous) {287 return previous + 1;288 }289 const program = new commander.Command();290 program.option(291 '-v, --verbose',292 'verbosity that can be increased',293 increaseVerbosity,294 0,295 );288 test('when use increaseVerbosity example then option value resets', () => {289 function increaseVerbosity(dummyValue, previous) {290 return previous + 1;291 }292 const program = new commander.Command();293 program.option(294 '-v, --verbose',295 'verbosity that can be increased',296 increaseVerbosity,297 0,298 );299297 program.parse(['-vvv'], { from: 'user' });298 assert.deepEqual(program.opts(), { verbose: 3 });299 program.parse(['-vv'], { from: 'user' });300 program.parse(['-vvv'], { from: 'user' });301 assert.deepEqual(program.opts(), { verbose: 3 });302 program.parse(['-vv'], { from: 'user' });303301 assert.deepEqual(program.opts(), { verbose: 2 });302 program.parse([], { from: 'user' });303 assert.deepEqual(program.opts(), { verbose: 0 });304 });304 assert.deepEqual(program.opts(), { verbose: 2 });305 program.parse([], { from: 'user' });306 assert.deepEqual(program.opts(), { verbose: 0 });307 });308306 test('when use parse and parseAsync then option values reset', async () => {307 const program = new commander.Command().option('--black').option('--white');309 test('when use parse and parseAsync then option values reset', async () => {310 const program = new commander.Command()311 .option('--black')312 .option('--white');313309 program.parse(['--black'], { from: 'user' });310 assert.deepEqual(program.opts(), { black: true });311 await program.parseAsync(['--white'], { from: 'user' });312 assert.deepEqual(program.opts(), { white: true });313 });314 program.parse(['--black'], { from: 'user' });315 assert.deepEqual(program.opts(), { black: true });316 await program.parseAsync(['--white'], { from: 'user' });317 assert.deepEqual(program.opts(), { white: true });318 });319315 test('when call subcommand then option values reset (program and subcommand)', () => {316 const program = new commander.Command().option('--black').option('--white');317 const subcommand = program.command('sub').option('--red').option('--green');320 test('when call subcommand then option values reset (program and subcommand)', () => {321 const program = new commander.Command()322 .option('--black')323 .option('--white');324 const subcommand = program325 .command('sub')326 .option('--red')327 .option('--green');328319 program.parse(['--black', 'sub', '--red'], { from: 'user' });320 assert.deepEqual(subcommand.optsWithGlobals(), { black: true, red: true });329 program.parse(['--black', 'sub', '--red'], { from: 'user' });330 assert.deepEqual(subcommand.optsWithGlobals(), {331 black: true,332 red: true,333 });334322 program.parse(['--white', 'sub', '--green'], { from: 'user' });323 assert.deepEqual(subcommand.optsWithGlobals(), {324 white: true,325 green: true,335 program.parse(['--white', 'sub', '--green'], { from: 'user' });336 assert.deepEqual(subcommand.optsWithGlobals(), {337 white: true,338 green: true,339 });340 });327 });341329 test('when call different subcommand then no reset because lazy', () => {330 // This is not a required behaviour, but is the intended behaviour.331 const program = new commander.Command();332 const sub1 = program.command('sub1').option('--red');333 const sub2 = program.command('sub2').option('--green');342 test('when call different subcommand then no reset because lazy', () => {343 // This is not a required behaviour, but is the intended behaviour.344 const program = new commander.Command();345 const sub1 = program.command('sub1').option('--red');346 const sub2 = program.command('sub2').option('--green');347335 program.parse(['sub1', '--red'], { from: 'user' });336 assert.deepEqual(sub1.opts(), { red: true });337 assert.deepEqual(sub2.opts(), {});348 program.parse(['sub1', '--red'], { from: 'user' });349 assert.deepEqual(sub1.opts(), { red: true });350 assert.deepEqual(sub2.opts(), {});351339 program.parse(['sub2', '--green'], { from: 'user' });340 assert.deepEqual(sub1.opts(), { red: true });341 assert.deepEqual(sub2.opts(), { green: true });342 });352 program.parse(['sub2', '--green'], { from: 'user' });353 assert.deepEqual(sub1.opts(), { red: true });354 assert.deepEqual(sub2.opts(), { green: true });355 });356344 test('when parse with different implied program name then name changes', () => {345 const program = new commander.Command();357 test('when parse with different implied program name then name changes', () => {358 const program = new commander.Command();359347 program.parse(['node', 'script1.js']);348 assert.equal(program.name(), 'script1');360 program.parse(['node', 'script1.js']);361 assert.equal(program.name(), 'script1');362350 program.parse(['electron', 'script2.js']);351 assert.equal(program.name(), 'script2');352 });363 program.parse(['electron', 'script2.js']);364 assert.equal(program.name(), 'script2');365 });366354 test('when parse with different arguments then args change', () => {355 // weak test, would work without store/reset!356 const program = new commander.Command()357 .argument('<first>')358 .argument('[second]');367 test('when parse with different arguments then args change', () => {368 // weak test, would work without store/reset!369 const program = new commander.Command()370 .argument('<first>')371 .argument('[second]');372360 program.parse(['one', 'two'], { from: 'user' });361 assert.deepEqual(program.args, ['one', 'two']);373 program.parse(['one', 'two'], { from: 'user' });374 assert.deepEqual(program.args, ['one', 'two']);375363 program.parse(['alpha'], { from: 'user' });364 assert.deepEqual(program.args, ['alpha']);365 });376 program.parse(['alpha'], { from: 'user' });377 assert.deepEqual(program.args, ['alpha']);378 });379367 test('when parse with different arguments then rawArgs change', () => {368 // weak test, would work without store/reset!369 const program = new commander.Command()370 .argument('<first>')371 .option('--white')372 .option('--black');380 test('when parse with different arguments then rawArgs change', () => {381 // weak test, would work without store/reset!382 const program = new commander.Command()383 .argument('<first>')384 .option('--white')385 .option('--black');386374 program.parse(['--white', 'one'], { from: 'user' });375 assert.deepEqual(program.rawArgs, ['--white', 'one']);387 program.parse(['--white', 'one'], { from: 'user' });388 assert.deepEqual(program.rawArgs, ['--white', 'one']);389377 program.parse(['--black', 'two'], { from: 'user' });378 assert.deepEqual(program.rawArgs, ['--black', 'two']);379 });390 program.parse(['--black', 'two'], { from: 'user' });391 assert.deepEqual(program.rawArgs, ['--black', 'two']);392 });393381 test('when parse with different arguments then processedArgs change', () => {382 // weak test, would work without store/reset!383 const program = new commander.Command().argument(384 '<first>',385 'first arg',386 parseFloat,387 );394 test('when parse with different arguments then processedArgs change', () => {395 // weak test, would work without store/reset!396 const program = new commander.Command().argument(397 '<first>',398 'first arg',399 parseFloat,400 );401389 program.parse([123], { from: 'user' });390 assert.deepEqual(program.processedArgs, [123]);402 program.parse([123], { from: 'user' });403 assert.deepEqual(program.processedArgs, [123]);404392 program.parse([456], { from: 'user' });393 assert.deepEqual(program.processedArgs, [456]);394 });405 program.parse([456], { from: 'user' });406 assert.deepEqual(program.processedArgs, [456]);407 });408396 test('when parse subcommand then reset state before preSubcommand hook called', () => {397 let hookCalled = false;398 const program = new commander.Command().hook(399 'preSubcommand',400 (thisCommand, subcommand) => {401 hookCalled = true;402 assert.deepEqual(subcommand.opts(), {});403 },404 );405 const subcommand = program.command('sub').option('--red').option('--green');409 test('when parse subcommand then reset state before preSubcommand hook called', () => {410 let hookCalled = false;411 const program = new commander.Command().hook(412 'preSubcommand',413 (thisCommand, subcommand) => {414 hookCalled = true;415 assert.deepEqual(subcommand.opts(), {});416 },417 );418 const subcommand = program419 .command('sub')420 .option('--red')421 .option('--green');422407 hookCalled = false;408 program.parse(['sub', '--red'], { from: 'user' });409 assert.equal(hookCalled, true);410 assert.deepEqual(subcommand.opts(), { red: true });423 hookCalled = false;424 program.parse(['sub', '--red'], { from: 'user' });425 assert.equal(hookCalled, true);426 assert.deepEqual(subcommand.opts(), { red: true });427412 hookCalled = false;413 program.parse(['sub', '--green'], { from: 'user' });414 assert.equal(hookCalled, true);415 assert.deepEqual(subcommand.opts(), { green: true });416 });428 hookCalled = false;429 program.parse(['sub', '--green'], { from: 'user' });430 assert.equal(hookCalled, true);431 assert.deepEqual(subcommand.opts(), { green: true });432 });433418 test('when using storeOptionsAsProperties then throw on second parse', () => {419 const program = new commander.Command().storeOptionsAsProperties();420 program.parse();421 assert.throws(() => {434 test('when using storeOptionsAsProperties then throw on second parse', () => {435 const program = new commander.Command().storeOptionsAsProperties();436 program.parse();437 assert.throws(() => {438 program.parse();439 });440 });441 });442});
modified:tests/command.parseOptions.test.js+4 added-4 removed
9 unmodified lines
10// Combination of parse and parseOptions tests which are more about details11// than high level behaviours which are tested elsewhere.1213// Tests created from reported bugs14describe('regression tests', () => {14describe('parsing regression tests', () => {15 // https://github.com/tj/commander.js/issues/103216 function createProgram1032() {17 const program = new commander.Command();18 program
34 unmodified lines
53 assert.equal(stdout, "[ '1', '2', '--dry-run', '3', '4', '5', '6' ]\n");54 });55});5657describe('parseOptions', () => {57describe('Command.parseOptions()', () => {58 function createProgram() {59 const program = new commander.Command();60 program61 .option('--global-flag')
109 unmodified lines
171 });172});173174// parse now sets program.args to the result of parseOptions (operands + unknown). Some limited testing.175describe('parse and program.args', () => {175describe('Command.args after parsing', () => {176 test('when program has known flag and operand then option removed and operand returned', () => {177 const program = new commander.Command();178 program.option('--global-flag').argument('[arg...]');179 program.parse('node test.js --global-flag arg'.split(' '));
63 unmodified lines
243//244// The focus in this file is testing the behaviours with known vs unknown options.245// See options.values.test.js for more general testing of known options.246247describe('Utility Conventions', () => {247describe('Posix Utility Conventions', () => {248 function createProgram() {249 const program = new commander.Command();250 program251 .option('-a,--aaa')
84 unmodified lines
modified:tests/command.positionalOptions.test.js+440 added-438 removed
3 unmodified lines
45// The changes to parsing for positional options are subtle, and took extra care to work with6// implicit help and default commands. Lots of tests.78describe('positional options using Command.passThroughOptions() and Command.enablePositionalOptions()', () => {8describe('program with passThrough', () => {9 function makeProgram() {10 const program = new commander.Command();11 program.passThroughOptions();12 program.option('-d, --debug').argument('<args...>');13 return program;14 }9 describe('program with passThrough', () => {10 function makeProgram() {11 const program = new commander.Command();12 program.passThroughOptions();13 program.option('-d, --debug').argument('<args...>');14 return program;15 }1616 test('when option before command-argument then option parsed', () => {17 const program = makeProgram();18 program.parse(['--debug', 'arg'], { from: 'user' });19 assert.deepEqual(program.args, ['arg']);20 assert.equal(program.opts().debug, true);21 });17 test('when option before command-argument then option parsed', () => {18 const program = makeProgram();19 program.parse(['--debug', 'arg'], { from: 'user' });20 assert.deepEqual(program.args, ['arg']);21 assert.equal(program.opts().debug, true);22 });2323 test('when known option after command-argument then option passed through', () => {24 const program = makeProgram();25 program.parse(['arg', '--debug'], { from: 'user' });26 assert.deepEqual(program.args, ['arg', '--debug']);27 assert.equal(program.opts().debug, undefined);28 });24 test('when known option after command-argument then option passed through', () => {25 const program = makeProgram();26 program.parse(['arg', '--debug'], { from: 'user' });27 assert.deepEqual(program.args, ['arg', '--debug']);28 assert.equal(program.opts().debug, undefined);29 });3030 test('when unknown option after command-argument then option passed through', () => {31 const program = makeProgram();32 program.parse(['arg', '--pass'], { from: 'user' });33 assert.deepEqual(program.args, ['arg', '--pass']);34 });31 test('when unknown option after command-argument then option passed through', () => {32 const program = makeProgram();33 program.parse(['arg', '--pass'], { from: 'user' });34 assert.deepEqual(program.args, ['arg', '--pass']);35 });3636 test('when action handler and unknown option after command-argument then option passed through', (t) => {37 const program = makeProgram();38 const mockAction = t.mock.fn();39 program.action(mockAction);40 program.parse(['arg', '--pass'], { from: 'user' });41 assert.equal(mockAction.mock.callCount(), 1);42 const callArgs = mockAction.mock.calls[0].arguments;43 assert.deepEqual(callArgs[0], ['arg', '--pass']);44 });37 test('when action handler and unknown option after command-argument then option passed through', (t) => {38 const program = makeProgram();39 const mockAction = t.mock.fn();40 program.action(mockAction);41 program.parse(['arg', '--pass'], { from: 'user' });42 assert.equal(mockAction.mock.callCount(), 1);43 const callArgs = mockAction.mock.calls[0].arguments;44 assert.deepEqual(callArgs[0], ['arg', '--pass']);45 });4646 test('when help option (without command-argument) then help called', (t) => {47 const program = makeProgram();48 const mockHelp = t.mock.fn(() => '');47 test('when help option (without command-argument) then help called', (t) => {48 const program = makeProgram();49 const mockHelp = t.mock.fn(() => '');5050 program.exitOverride().configureHelp({ formatHelp: mockHelp });51 try {52 program.parse(['--help'], { from: 'user' });53 } catch (err) {54 /* empty */55 }56 assert.equal(mockHelp.mock.callCount(), 1);57 });51 program.exitOverride().configureHelp({ formatHelp: mockHelp });52 try {53 program.parse(['--help'], { from: 'user' });54 } catch (err) {55 /* empty */56 }57 assert.equal(mockHelp.mock.callCount(), 1);58 });5959 test('when help option after command-argument then option passed through', () => {60 const program = makeProgram();61 program.parse(['arg', '--help'], { from: 'user' });62 assert.deepEqual(program.args, ['arg', '--help']);63 });60 test('when help option after command-argument then option passed through', () => {61 const program = makeProgram();62 program.parse(['arg', '--help'], { from: 'user' });63 assert.deepEqual(program.args, ['arg', '--help']);64 });6565 test('when version option after command-argument then option passed through', () => {66 const program = makeProgram();67 program.version('1.2.3');68 program.parse(['arg', '--version'], { from: 'user' });69 assert.deepEqual(program.args, ['arg', '--version']);66 test('when version option after command-argument then option passed through', () => {67 const program = makeProgram();68 program.version('1.2.3');69 program.parse(['arg', '--version'], { from: 'user' });70 assert.deepEqual(program.args, ['arg', '--version']);71 });72 });71});7373// -----------------------------------------------------------74 // -----------------------------------------------------------7575describe('program with positionalOptions and subcommand', () => {76 function makeProgram() {77 const program = new commander.Command();78 program79 .enablePositionalOptions()80 .option('-s, --shared <value>')81 .argument('<args...>');82 const sub = program83 .command('sub')84 .argument('[arg]')85 .option('-s, --shared <value>')86 .action(() => {}); // Not used, but normal to have action handler on subcommand.87 return { program, sub };88 }76 describe('program with positionalOptions and subcommand', () => {77 function makeProgram() {78 const program = new commander.Command();79 program80 .enablePositionalOptions()81 .option('-s, --shared <value>')82 .argument('<args...>');83 const sub = program84 .command('sub')85 .argument('[arg]')86 .option('-s, --shared <value>')87 .action(() => {}); // Not used, but normal to have action handler on subcommand.88 return { program, sub };89 }9090 test('when global option before subcommand then global option parsed', () => {91 const { program } = makeProgram();92 program.parse(['--shared', 'program', 'sub'], { from: 'user' });93 assert.equal(program.opts().shared, 'program');94 });91 test('when global option before subcommand then global option parsed', () => {92 const { program } = makeProgram();93 program.parse(['--shared', 'program', 'sub'], { from: 'user' });94 assert.equal(program.opts().shared, 'program');95 });9696 test('when shared option after subcommand then parsed by subcommand', () => {97 const { program, sub } = makeProgram();98 program.parse(['sub', '--shared', 'local'], { from: 'user' });99 assert.equal(sub.opts().shared, 'local');100 assert.equal(program.opts().shared, undefined);101 });97 test('when shared option after subcommand then parsed by subcommand', () => {98 const { program, sub } = makeProgram();99 program.parse(['sub', '--shared', 'local'], { from: 'user' });100 assert.equal(sub.opts().shared, 'local');101 assert.equal(program.opts().shared, undefined);102 });103103 test('when shared option after subcommand argument then parsed by subcommand', () => {104 const { program, sub } = makeProgram();105 program.parse(['sub', 'arg', '--shared', 'local'], { from: 'user' });106 assert.equal(sub.opts().shared, 'local');107 assert.deepEqual(sub.args, ['arg']);108 assert.equal(program.opts().shared, undefined);109 });104 test('when shared option after subcommand argument then parsed by subcommand', () => {105 const { program, sub } = makeProgram();106 program.parse(['sub', 'arg', '--shared', 'local'], { from: 'user' });107 assert.equal(sub.opts().shared, 'local');108 assert.deepEqual(sub.args, ['arg']);109 assert.equal(program.opts().shared, undefined);110 });111111 test('when shared option before and after subcommand then both parsed', () => {112 const { program, sub } = makeProgram();113 program.parse(['--shared', 'program', 'sub', '--shared', 'local'], {114 from: 'user',112 test('when shared option before and after subcommand then both parsed', () => {113 const { program, sub } = makeProgram();114 program.parse(['--shared', 'program', 'sub', '--shared', 'local'], {115 from: 'user',116 });117 assert.equal(program.opts().shared, 'program');118 assert.equal(sub.opts().shared, 'local');119 });116 assert.equal(program.opts().shared, 'program');117 assert.equal(sub.opts().shared, 'local');118 });120120 describe('help', () => {121 const cases = [122 { args: [], programHelp: 1, subHelp: 0 },123 { args: ['sub'], programHelp: 0, subHelp: 0 },124 { args: ['--help'], programHelp: 1, subHelp: 0 },125 { args: ['sub', '--help'], programHelp: 0, subHelp: 1 },126 { args: ['sub', 'foo', '--help'], programHelp: 0, subHelp: 1 },127 { args: ['help'], programHelp: 1, subHelp: 0 },128 { args: ['help', 'sub'], programHelp: 0, subHelp: 1 },129 ];121 describe('help', () => {122 const cases = [123 { args: [], programHelp: 1, subHelp: 0 },124 { args: ['sub'], programHelp: 0, subHelp: 0 },125 { args: ['--help'], programHelp: 1, subHelp: 0 },126 { args: ['sub', '--help'], programHelp: 0, subHelp: 1 },127 { args: ['sub', 'foo', '--help'], programHelp: 0, subHelp: 1 },128 { args: ['help'], programHelp: 1, subHelp: 0 },129 { args: ['help', 'sub'], programHelp: 0, subHelp: 1 },130 ];131131 for (const { args, programHelp, subHelp } of cases) {132 test(`when user args ${JSON.stringify(args)} then program/sub help called ${programHelp}/${subHelp}`, (t) => {133 const { program, sub } = makeProgram();134 const mockProgramHelp = t.mock.fn();135 program.exitOverride().configureHelp({ formatHelp: mockProgramHelp });136 const mockSubHelp = t.mock.fn();137 sub.exitOverride().configureHelp({ formatHelp: mockSubHelp });132 for (const { args, programHelp, subHelp } of cases) {133 test(`when user args ${JSON.stringify(args)} then program/sub help called ${programHelp}/${subHelp}`, (t) => {134 const { program, sub } = makeProgram();135 const mockProgramHelp = t.mock.fn();136 program.exitOverride().configureHelp({ formatHelp: mockProgramHelp });137 const mockSubHelp = t.mock.fn();138 sub.exitOverride().configureHelp({ formatHelp: mockSubHelp });139139 try {140 program.parse(args, { from: 'user' });141 } catch (err) {142 /* empty */143 }144 assert.equal(mockProgramHelp.mock.callCount(), programHelp);145 assert.equal(mockSubHelp.mock.callCount(), subHelp);146 });147 }140 try {141 program.parse(args, { from: 'user' });142 } catch (err) {143 /* empty */144 }145 assert.equal(mockProgramHelp.mock.callCount(), programHelp);146 assert.equal(mockSubHelp.mock.callCount(), subHelp);147 });148 }149 });150 });149});151151// ---------------------------------------------------------------152 // ---------------------------------------------------------------153153describe('program with positionalOptions and default subcommand (called sub)', () => {154 function makeProgram() {155 const program = new commander.Command();156 program157 .enablePositionalOptions()158 .option('-s, --shared')159 .option('-g, --global')160 .argument('<args...>');161 const sub = program162 .command('sub', { isDefault: true })163 .argument('[args...]')164 .option('-s, --shared')165 .option('-d, --default')166 .action(() => {}); // Not used, but normal to have action handler on subcommand.167 program.command('another'); // Not used, but normal to have more than one subcommand if have a default.168 return { program, sub };169 }154 describe('program with positionalOptions and default subcommand (called sub)', () => {155 function makeProgram() {156 const program = new commander.Command();157 program158 .enablePositionalOptions()159 .option('-s, --shared')160 .option('-g, --global')161 .argument('<args...>');162 const sub = program163 .command('sub', { isDefault: true })164 .argument('[args...]')165 .option('-s, --shared')166 .option('-d, --default')167 .action(() => {}); // Not used, but normal to have action handler on subcommand.168 program.command('another'); // Not used, but normal to have more than one subcommand if have a default.169 return { program, sub };170 }171171 test('when program option before sub option then program option read by program', () => {172 const { program } = makeProgram();173 program.parse(['--global', '--default'], { from: 'user' });174 assert.equal(program.opts().global, true);175 });172 test('when program option before sub option then program option read by program', () => {173 const { program } = makeProgram();174 program.parse(['--global', '--default'], { from: 'user' });175 assert.equal(program.opts().global, true);176 });177177 test('when program option before sub option then sub option read by sub', () => {178 const { program, sub } = makeProgram();179 program.parse(['--global', '--default'], { from: 'user' });180 assert.equal(sub.opts().default, true);181 });178 test('when program option before sub option then sub option read by sub', () => {179 const { program, sub } = makeProgram();180 program.parse(['--global', '--default'], { from: 'user' });181 assert.equal(sub.opts().default, true);182 });183183 test('when shared option before sub argument then option read by program', () => {184 const { program } = makeProgram();185 program.parse(['--shared', 'foo'], { from: 'user' });186 assert.equal(program.opts().shared, true);187 });184 test('when shared option before sub argument then option read by program', () => {185 const { program } = makeProgram();186 program.parse(['--shared', 'foo'], { from: 'user' });187 assert.equal(program.opts().shared, true);188 });189189 test('when shared option after sub argument then option read by sub', () => {190 const { program, sub } = makeProgram();191 program.parse(['foo', '--shared'], { from: 'user' });192 assert.equal(sub.opts().shared, true);193 });190 test('when shared option after sub argument then option read by sub', () => {191 const { program, sub } = makeProgram();192 program.parse(['foo', '--shared'], { from: 'user' });193 assert.equal(sub.opts().shared, true);194 });195195 describe('help', () => {196 const cases = [197 { args: [], programHelp: 0, subHelp: 0 },198 { args: ['--help'], programHelp: 1, subHelp: 0 },199 { args: ['help'], programHelp: 1, subHelp: 0 },200 ];196 describe('help', () => {197 const cases = [198 { args: [], programHelp: 0, subHelp: 0 },199 { args: ['--help'], programHelp: 1, subHelp: 0 },200 { args: ['help'], programHelp: 1, subHelp: 0 },201 ];202202 for (const { args, programHelp, subHelp } of cases) {203 test(`when user args ${JSON.stringify(args)} then program/sub help called ${programHelp}/${subHelp}`, (t) => {204 const { program, sub } = makeProgram();205 const mockProgramHelp = t.mock.fn();206 program.exitOverride().configureHelp({ formatHelp: mockProgramHelp });207 const mockSubHelp = t.mock.fn();208 sub.exitOverride().configureHelp({ formatHelp: mockSubHelp });203 for (const { args, programHelp, subHelp } of cases) {204 test(`when user args ${JSON.stringify(args)} then program/sub help called ${programHelp}/${subHelp}`, (t) => {205 const { program, sub } = makeProgram();206 const mockProgramHelp = t.mock.fn();207 program.exitOverride().configureHelp({ formatHelp: mockProgramHelp });208 const mockSubHelp = t.mock.fn();209 sub.exitOverride().configureHelp({ formatHelp: mockSubHelp });210210 try {211 program.parse(args, { from: 'user' });212 } catch (err) {213 /* empty */214 }215 assert.equal(mockProgramHelp.mock.callCount(), programHelp);216 assert.equal(mockSubHelp.mock.callCount(), subHelp);217 });218 }211 try {212 program.parse(args, { from: 'user' });213 } catch (err) {214 /* empty */215 }216 assert.equal(mockProgramHelp.mock.callCount(), programHelp);217 assert.equal(mockSubHelp.mock.callCount(), subHelp);218 });219 }220 });221 });220});222222// ------------------------------------------------------------------------------223 // ------------------------------------------------------------------------------224224describe('subcommand with passThrough', () => {225 function makeProgram() {226 const program = new commander.Command();227 program228 .enablePositionalOptions()229 .option('-s, --shared <value>')230 .argument('<args...>');231 const sub = program232 .command('sub')233 .passThroughOptions()234 .argument('[args...]')235 .option('-s, --shared <value>')236 .option('-d, --debug')237 .action(() => {}); // Not used, but normal to have action handler on subcommand.238 return { program, sub };239 }225 describe('subcommand with passThrough', () => {226 function makeProgram() {227 const program = new commander.Command();228 program229 .enablePositionalOptions()230 .option('-s, --shared <value>')231 .argument('<args...>');232 const sub = program233 .command('sub')234 .passThroughOptions()235 .argument('[args...]')236 .option('-s, --shared <value>')237 .option('-d, --debug')238 .action(() => {}); // Not used, but normal to have action handler on subcommand.239 return { program, sub };240 }241241 test('when option before command-argument then option parsed', () => {242 const { program, sub } = makeProgram();243 program.parse(['sub', '--debug', 'arg'], { from: 'user' });244 assert.deepEqual(sub.args, ['arg']);245 assert.equal(sub.opts().debug, true);246 });242 test('when option before command-argument then option parsed', () => {243 const { program, sub } = makeProgram();244 program.parse(['sub', '--debug', 'arg'], { from: 'user' });245 assert.deepEqual(sub.args, ['arg']);246 assert.equal(sub.opts().debug, true);247 });248248 test('when known option after command-argument then option passed through', () => {249 const { program, sub } = makeProgram();250 program.parse(['sub', 'arg', '--debug'], { from: 'user' });251 assert.deepEqual(sub.args, ['arg', '--debug']);252 assert.equal(sub.opts().debug, undefined);253 });249 test('when known option after command-argument then option passed through', () => {250 const { program, sub } = makeProgram();251 program.parse(['sub', 'arg', '--debug'], { from: 'user' });252 assert.deepEqual(sub.args, ['arg', '--debug']);253 assert.equal(sub.opts().debug, undefined);254 });255255 test('when unknown option after command-argument then option passed through', () => {256 const { program, sub } = makeProgram();257 program.parse(['sub', 'arg', '--pass'], { from: 'user' });258 assert.deepEqual(sub.args, ['arg', '--pass']);259 });256 test('when unknown option after command-argument then option passed through', () => {257 const { program, sub } = makeProgram();258 program.parse(['sub', 'arg', '--pass'], { from: 'user' });259 assert.deepEqual(sub.args, ['arg', '--pass']);260 });261261 test('when action handler and unknown option after command-argument then option passed through', (t) => {262 const { program, sub } = makeProgram();263 const mockAction = t.mock.fn();264 sub.action(mockAction);265 program.parse(['sub', 'arg', '--pass'], { from: 'user' });266 assert.equal(mockAction.mock.callCount(), 1);267 const callArgs = mockAction.mock.calls[0].arguments;268 assert.deepEqual(callArgs[0], ['arg', '--pass']);269 });262 test('when action handler and unknown option after command-argument then option passed through', (t) => {263 const { program, sub } = makeProgram();264 const mockAction = t.mock.fn();265 sub.action(mockAction);266 program.parse(['sub', 'arg', '--pass'], { from: 'user' });267 assert.equal(mockAction.mock.callCount(), 1);268 const callArgs = mockAction.mock.calls[0].arguments;269 assert.deepEqual(callArgs[0], ['arg', '--pass']);270 });271271 test('when help option after command-argument then option passed through', () => {272 const { program, sub } = makeProgram();273 program.parse(['sub', 'arg', '--help'], { from: 'user' });274 assert.deepEqual(sub.args, ['arg', '--help']);275 });272 test('when help option after command-argument then option passed through', () => {273 const { program, sub } = makeProgram();274 program.parse(['sub', 'arg', '--help'], { from: 'user' });275 assert.deepEqual(sub.args, ['arg', '--help']);276 });277277 test('when version option after command-argument then option passed through', () => {278 const { program, sub } = makeProgram();279 program.version('1.2.3');280 program.parse(['sub', 'arg', '--version'], { from: 'user' });281 assert.deepEqual(sub.args, ['arg', '--version']);282 });278 test('when version option after command-argument then option passed through', () => {279 const { program, sub } = makeProgram();280 program.version('1.2.3');281 program.parse(['sub', 'arg', '--version'], { from: 'user' });282 assert.deepEqual(sub.args, ['arg', '--version']);283 });284284 test('when shared option before sub and after sub and after sub parameter then all three parsed', () => {285 const { program, sub } = makeProgram();286 program.parse(287 ['--shared=global', 'sub', '--shared=local', 'arg', '--shared'],288 { from: 'user' },289 );290 assert.equal(program.opts().shared, 'global');291 assert.equal(sub.opts().shared, 'local');292 assert.deepEqual(sub.args, ['arg', '--shared']);285 test('when shared option before sub and after sub and after sub parameter then all three parsed', () => {286 const { program, sub } = makeProgram();287 program.parse(288 ['--shared=global', 'sub', '--shared=local', 'arg', '--shared'],289 { from: 'user' },290 );291 assert.equal(program.opts().shared, 'global');292 assert.equal(sub.opts().shared, 'local');293 assert.deepEqual(sub.args, ['arg', '--shared']);294 });295 });294});296296// ------------------------------------------------------------------------------297 // ------------------------------------------------------------------------------298298describe('default command with passThrough', () => {299 function makeProgram() {300 const program = new commander.Command();301 program.enablePositionalOptions();302 const sub = program303 .command('sub', { isDefault: true })304 .passThroughOptions()305 .argument('[args...]')306 .option('-d, --debug')307 .action(() => {}); // Not used, but normal to have action handler on subcommand.308 return { program, sub };309 }299 describe('default command with passThrough', () => {300 function makeProgram() {301 const program = new commander.Command();302 program.enablePositionalOptions();303 const sub = program304 .command('sub', { isDefault: true })305 .passThroughOptions()306 .argument('[args...]')307 .option('-d, --debug')308 .action(() => {}); // Not used, but normal to have action handler on subcommand.309 return { program, sub };310 }311311 test('when option before command-argument then option parsed', () => {312 const { program, sub } = makeProgram();313 program.parse(['--debug', 'arg'], { from: 'user' });314 assert.deepEqual(sub.args, ['arg']);315 assert.equal(sub.opts().debug, true);316 });312 test('when option before command-argument then option parsed', () => {313 const { program, sub } = makeProgram();314 program.parse(['--debug', 'arg'], { from: 'user' });315 assert.deepEqual(sub.args, ['arg']);316 assert.equal(sub.opts().debug, true);317 });318318 test('when known option after command-argument then option passed through', () => {319 const { program, sub } = makeProgram();320 program.parse(['arg', '--debug'], { from: 'user' });321 assert.deepEqual(sub.args, ['arg', '--debug']);322 assert.equal(sub.opts().debug, undefined);323 });319 test('when known option after command-argument then option passed through', () => {320 const { program, sub } = makeProgram();321 program.parse(['arg', '--debug'], { from: 'user' });322 assert.deepEqual(sub.args, ['arg', '--debug']);323 assert.equal(sub.opts().debug, undefined);324 });325325 test('when unknown option after command-argument then option passed through', () => {326 const { program, sub } = makeProgram();327 program.parse(['arg', '--pass'], { from: 'user' });328 assert.deepEqual(sub.args, ['arg', '--pass']);329 });326 test('when unknown option after command-argument then option passed through', () => {327 const { program, sub } = makeProgram();328 program.parse(['arg', '--pass'], { from: 'user' });329 assert.deepEqual(sub.args, ['arg', '--pass']);330 });331331 test('when action handler and unknown option after command-argument then option passed through', (t) => {332 const { program, sub } = makeProgram();333 const mockAction = t.mock.fn();334 sub.action(mockAction);335 program.parse(['arg', '--pass'], { from: 'user' });336 assert.equal(mockAction.mock.callCount(), 1);337 const callArgs = mockAction.mock.calls[0].arguments;338 assert.deepEqual(callArgs[0], ['arg', '--pass']);332 test('when action handler and unknown option after command-argument then option passed through', (t) => {333 const { program, sub } = makeProgram();334 const mockAction = t.mock.fn();335 sub.action(mockAction);336 program.parse(['arg', '--pass'], { from: 'user' });337 assert.equal(mockAction.mock.callCount(), 1);338 const callArgs = mockAction.mock.calls[0].arguments;339 assert.deepEqual(callArgs[0], ['arg', '--pass']);340 });341 });340});342342// ------------------------------------------------------------------------------343 // ------------------------------------------------------------------------------344344describe('program with action handler and positionalOptions and subcommand', () => {345 function makeProgram() {346 const program = new commander.Command();347 program348 .enablePositionalOptions()349 .option('-g, --global')350 .argument('<args...>')351 .action(() => {});352 const sub = program353 .command('sub')354 .argument('[arg]')355 .action(() => {});356 return { program, sub };357 }345 describe('program with action handler and positionalOptions and subcommand', () => {346 function makeProgram() {347 const program = new commander.Command();348 program349 .enablePositionalOptions()350 .option('-g, --global')351 .argument('<args...>')352 .action(() => {});353 const sub = program354 .command('sub')355 .argument('[arg]')356 .action(() => {});357 return { program, sub };358 }359359 test('when global option before parameter then global option parsed', () => {360 const { program } = makeProgram();361 program.parse(['--global', 'foo'], { from: 'user' });362 assert.equal(program.opts().global, true);363 });360 test('when global option before parameter then global option parsed', () => {361 const { program } = makeProgram();362 program.parse(['--global', 'foo'], { from: 'user' });363 assert.equal(program.opts().global, true);364 });365365 test('when global option after parameter then global option parsed', () => {366 const { program } = makeProgram();367 program.parse(['foo', '--global'], { from: 'user' });368 assert.equal(program.opts().global, true);369 });366 test('when global option after parameter then global option parsed', () => {367 const { program } = makeProgram();368 program.parse(['foo', '--global'], { from: 'user' });369 assert.equal(program.opts().global, true);370 });371371 test('when global option after parameter with same name as subcommand then global option parsed', () => {372 const { program } = makeProgram();373 program.parse(['foo', 'sub', '--global'], { from: 'user' });374 assert.equal(program.opts().global, true);372 test('when global option after parameter with same name as subcommand then global option parsed', () => {373 const { program } = makeProgram();374 program.parse(['foo', 'sub', '--global'], { from: 'user' });375 assert.equal(program.opts().global, true);376 });377 });376});378378// ------------------------------------------------------------------------------379 // ------------------------------------------------------------------------------380380describe('broken passThrough', () => {381 test('when program not positional and turn on passThroughOptions in subcommand then error', () => {382 const program = new commander.Command();383 const sub = program.command('sub');381 describe('broken passThrough', () => {382 test('when program not positional and turn on passThroughOptions in subcommand then error', () => {383 const program = new commander.Command();384 const sub = program.command('sub');385385 assert.throws(() => {386 sub.passThroughOptions();386 assert.throws(() => {387 sub.passThroughOptions();388 });389 });388 });390390 test('when program not positional and add subcommand with passThroughOptions then error', () => {391 const program = new commander.Command();392 const sub = new commander.Command('sub').passThroughOptions();391 test('when program not positional and add subcommand with passThroughOptions then error', () => {392 const program = new commander.Command();393 const sub = new commander.Command('sub').passThroughOptions();394394 assert.throws(() => {395 program.addCommand(sub);395 assert.throws(() => {396 program.addCommand(sub);397 });398 });399 });398});400400// ------------------------------------------------------------------------------401 // ------------------------------------------------------------------------------402402describe('program with action handler and passThrough and subcommand', () => {403 function makeProgram() {404 const program = new commander.Command();405 program406 .passThroughOptions()407 .option('-g, --global')408 .argument('<args...>')409 .action(() => {});410 const sub = program411 .command('sub')412 .argument('[arg]')413 .option('-g, --group')414 .option('-d, --debug')415 .action(() => {});416 return { program, sub };417 }403 describe('program with action handler and passThrough and subcommand', () => {404 function makeProgram() {405 const program = new commander.Command();406 program407 .passThroughOptions()408 .option('-g, --global')409 .argument('<args...>')410 .action(() => {});411 const sub = program412 .command('sub')413 .argument('[arg]')414 .option('-g, --group')415 .option('-d, --debug')416 .action(() => {});417 return { program, sub };418 }419419 test('when global option before parameter then global option parsed', () => {420 const { program } = makeProgram();421 program.parse(['--global', 'foo'], { from: 'user' });422 assert.equal(program.opts().global, true);423 });420 test('when global option before parameter then global option parsed', () => {421 const { program } = makeProgram();422 program.parse(['--global', 'foo'], { from: 'user' });423 assert.equal(program.opts().global, true);424 });425425 test('when global option after parameter then passed through', () => {426 const { program } = makeProgram();427 program.parse(['foo', '--global'], { from: 'user' });428 assert.deepEqual(program.args, ['foo', '--global']);429 });426 test('when global option after parameter then passed through', () => {427 const { program } = makeProgram();428 program.parse(['foo', '--global'], { from: 'user' });429 assert.deepEqual(program.args, ['foo', '--global']);430 });431431 test('when subcommand option after subcommand then option parsed', () => {432 const { program, sub } = makeProgram();433 program.parse(['sub', '--debug'], { from: 'user' });434 assert.equal(sub.opts().debug, true);435 });432 test('when subcommand option after subcommand then option parsed', () => {433 const { program, sub } = makeProgram();434 program.parse(['sub', '--debug'], { from: 'user' });435 assert.equal(sub.opts().debug, true);436 });437437 // This is somewhat of a side-effect of supporting previous test.438 test('when shared option after subcommand then parsed by subcommand', () => {439 const { program, sub } = makeProgram();440 program.parse(['sub', '-g'], { from: 'user' });441 assert.equal(sub.opts().group, true);442 assert.equal(program.opts().global, undefined);438 // This is somewhat of a side-effect of supporting previous test.439 test('when shared option after subcommand then parsed by subcommand', () => {440 const { program, sub } = makeProgram();441 program.parse(['sub', '-g'], { from: 'user' });442 assert.equal(sub.opts().group, true);443 assert.equal(program.opts().global, undefined);444 });445 });444});446446// ------------------------------------------------------------------------------447 // ------------------------------------------------------------------------------448448describe('program with allowUnknownOption', () => {449 test('when passThroughOptions and unknown option then arguments from unknown passed through', () => {450 const program = new commander.Command();451 program.passThroughOptions().allowUnknownOption().option('--debug');452 program.argument('[args...]');449 describe('program with allowUnknownOption', () => {450 test('when passThroughOptions and unknown option then arguments from unknown passed through', () => {451 const program = new commander.Command();452 program.passThroughOptions().allowUnknownOption().option('--debug');453 program.argument('[args...]');454454 program.parse(['--unknown', '--debug'], { from: 'user' });455 assert.deepEqual(program.args, ['--unknown', '--debug']);456 });455 program.parse(['--unknown', '--debug'], { from: 'user' });456 assert.deepEqual(program.args, ['--unknown', '--debug']);457 });458458 test('when positionalOptions and unknown option then known options then known option parsed', () => {459 const program = new commander.Command();460 program.enablePositionalOptions().allowUnknownOption().option('--debug');461 program.argument('[args...]');459 test('when positionalOptions and unknown option then known options then known option parsed', () => {460 const program = new commander.Command();461 program.enablePositionalOptions().allowUnknownOption().option('--debug');462 program.argument('[args...]');463463 program.parse(['--unknown', '--debug'], { from: 'user' });464 assert.equal(program.opts().debug, true);465 assert.deepEqual(program.args, ['--unknown']);464 program.parse(['--unknown', '--debug'], { from: 'user' });465 assert.equal(program.opts().debug, true);466 assert.deepEqual(program.args, ['--unknown']);467 });468 });467});469469// ------------------------------------------------------------------------------470 // ------------------------------------------------------------------------------471471describe('passThroughOptions(xxx) and option after command-argument', () => {472 function makeProgram() {473 const program = new commander.Command();474 program.option('-d, --debug').argument('<args...>');475 return program;476 }472 describe('passThroughOptions(xxx) and option after command-argument', () => {473 function makeProgram() {474 const program = new commander.Command();475 program.option('-d, --debug').argument('<args...>');476 return program;477 }478478 test('when passThroughOptions() then option passed through', () => {479 const program = makeProgram();480 program.passThroughOptions();481 program.parse(['foo', '--debug'], { from: 'user' });482 assert.deepEqual(program.args, ['foo', '--debug']);483 });479 test('when passThroughOptions() then option passed through', () => {480 const program = makeProgram();481 program.passThroughOptions();482 program.parse(['foo', '--debug'], { from: 'user' });483 assert.deepEqual(program.args, ['foo', '--debug']);484 });485485 test('when passThroughOptions(true) then option passed through', () => {486 const program = makeProgram();487 program.passThroughOptions(true);488 program.parse(['foo', '--debug'], { from: 'user' });489 assert.deepEqual(program.args, ['foo', '--debug']);490 });486 test('when passThroughOptions(true) then option passed through', () => {487 const program = makeProgram();488 program.passThroughOptions(true);489 program.parse(['foo', '--debug'], { from: 'user' });490 assert.deepEqual(program.args, ['foo', '--debug']);491 });492492 test('when passThroughOptions(false) then option parsed', () => {493 const program = makeProgram();494 program.passThroughOptions(false);495 program.parse(['foo', '--debug'], { from: 'user' });496 assert.deepEqual(program.args, ['foo']);497 assert.equal(program.opts().debug, true);493 test('when passThroughOptions(false) then option parsed', () => {494 const program = makeProgram();495 program.passThroughOptions(false);496 program.parse(['foo', '--debug'], { from: 'user' });497 assert.deepEqual(program.args, ['foo']);498 assert.equal(program.opts().debug, true);499 });500 });499});501501// ------------------------------------------------------------------------------502 // ------------------------------------------------------------------------------503503describe('enablePositionalOptions(xxx) and shared option after subcommand', () => {504 function makeProgram() {505 const program = new commander.Command();506 program.option('-d, --debug');507 const sub = program.command('sub').option('-d, --debug');508 return { program, sub };509 }504 describe('enablePositionalOptions(xxx) and shared option after subcommand', () => {505 function makeProgram() {506 const program = new commander.Command();507 program.option('-d, --debug');508 const sub = program.command('sub').option('-d, --debug');509 return { program, sub };510 }511511 test('when enablePositionalOptions() then option parsed by subcommand', () => {512 const { program, sub } = makeProgram();513 program.enablePositionalOptions();514 program.parse(['sub', '--debug'], { from: 'user' });515 assert.equal(sub.opts().debug, true);516 });512 test('when enablePositionalOptions() then option parsed by subcommand', () => {513 const { program, sub } = makeProgram();514 program.enablePositionalOptions();515 program.parse(['sub', '--debug'], { from: 'user' });516 assert.equal(sub.opts().debug, true);517 });518518 test('when enablePositionalOptions(true) then option parsed by subcommand', () => {519 const { program, sub } = makeProgram();520 program.enablePositionalOptions(true);521 program.parse(['sub', '--debug'], { from: 'user' });522 assert.equal(sub.opts().debug, true);523 });519 test('when enablePositionalOptions(true) then option parsed by subcommand', () => {520 const { program, sub } = makeProgram();521 program.enablePositionalOptions(true);522 program.parse(['sub', '--debug'], { from: 'user' });523 assert.equal(sub.opts().debug, true);524 });525525 test('when enablePositionalOptions(false) then option parsed by program', () => {526 const { program, sub } = makeProgram();527 program.enablePositionalOptions(false);528 program.parse(['sub', '--debug'], { from: 'user' });529 assert.equal(sub.opts().debug, undefined);530 assert.equal(program.opts().debug, true);526 test('when enablePositionalOptions(false) then option parsed by program', () => {527 const { program, sub } = makeProgram();528 program.enablePositionalOptions(false);529 program.parse(['sub', '--debug'], { from: 'user' });530 assert.equal(sub.opts().debug, undefined);531 assert.equal(program.opts().debug, true);532 });533 });534});
modified:tests/command.registerClash.test.js+62 added-60 removed
1const { Command } = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('registering clashing subcommands', () => {5test('when command name conflicts with existing name then throw', () => {6 assert.throws(7 () => {8 const program = new Command();9 program.command('one');10 program.command('one');11 },12 { message: /cannot add command/ },13 );14});6 test('when command name conflicts with existing name then throw', () => {7 assert.throws(8 () => {9 const program = new Command();10 program.command('one');11 program.command('one');12 },13 { message: /cannot add command/ },14 );15 });1616test('when command name conflicts with existing alias then throw', () => {17 assert.throws(18 () => {19 const program = new Command();20 program.command('one').alias('1');21 program.command('1');22 },23 { message: /cannot add command/ },24 );25});17 test('when command name conflicts with existing alias then throw', () => {18 assert.throws(19 () => {20 const program = new Command();21 program.command('one').alias('1');22 program.command('1');23 },24 { message: /cannot add command/ },25 );26 });2727test('when command alias conflicts with existing name then throw', () => {28 assert.throws(29 () => {30 const program = new Command();31 program.command('one');32 program.command('1').alias('one');33 },34 { message: /cannot add alias/ },35 );36});28 test('when command alias conflicts with existing name then throw', () => {29 assert.throws(30 () => {31 const program = new Command();32 program.command('one');33 program.command('1').alias('one');34 },35 { message: /cannot add alias/ },36 );37 });3838test('when command alias conflicts with existing alias then throw', () => {39 assert.throws(40 () => {41 const program = new Command();42 program.command('one').alias('1');43 program.command('unity').alias('1');44 },45 { message: /cannot add alias/ },46 );47});39 test('when command alias conflicts with existing alias then throw', () => {40 assert.throws(41 () => {42 const program = new Command();43 program.command('one').alias('1');44 program.command('unity').alias('1');45 },46 { message: /cannot add alias/ },47 );48 });4949test('when .addCommand name conflicts with existing name then throw', () => {50 assert.throws(51 () => {52 const program = new Command();53 program.command('one');54 program.addCommand(new Command('one'));55 },56 { message: /cannot add command/ },57 );58});50 test('when .addCommand name conflicts with existing name then throw', () => {51 assert.throws(52 () => {53 const program = new Command();54 program.command('one');55 program.addCommand(new Command('one'));56 },57 { message: /cannot add command/ },58 );59 });6060test('when .addCommand alias conflicts with existing name then throw', () => {61 assert.throws(62 () => {63 const program = new Command();64 program.command('one');65 program.addCommand(new Command('unity').alias('one'));66 },67 { message: /cannot add command/ },68 );61 test('when .addCommand alias conflicts with existing name then throw', () => {62 assert.throws(63 () => {64 const program = new Command();65 program.command('one');66 program.addCommand(new Command('unity').alias('one'));67 },68 { message: /cannot add command/ },69 );70 });71});
modified:tests/command.showHelpAfterError.test.js+2 added-2 removed
1const commander = require('../');2const { test, describe, mock } = require('node:test');3const assert = require('node:assert/strict');45describe('showHelpAfterError with message', () => {5describe('Command.showHelpAfterError(message)', () => {6 const customHelpMessage = 'See --help';78 function makeProgram(t) {9 const writeMock = t.mock.fn();
110 unmodified lines
120 assert.equal(lastCall.arguments[0], `${customHelpMessage}\n`);121 });122});123124test('when showHelpAfterError() and error and then shows full help', () => {124test('when Command.showHelpAfterError() and error and then shows full help', () => {125 const writeMock = mock.fn();126 const program = new commander.Command();127 program128 .exitOverride()
11 unmodified lines
modified:tests/command.showSuggestionAfterError.test.js+30 added-29 removed
1const { Command } = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45function getSuggestion(program, arg) {6 let message = '';
11 unmodified lines
1819 const match = message.match(/Did you mean (one of )?(.*)\?/);20 return match ? match[2] : null;21}22describe('Command.showSuggestionAfterError()', () => {23 test('when unknown command and showSuggestionAfterError() then show suggestion', () => {24 const program = new Command();25 program.showSuggestionAfterError();26 program.command('example');27 const suggestion = getSuggestion(program, 'exampel');28 assert.equal(suggestion, 'example');29 });3023test('when unknown command and showSuggestionAfterError() then show suggestion', () => {24 const program = new Command();25 program.showSuggestionAfterError();26 program.command('example');27 const suggestion = getSuggestion(program, 'exampel');28 assert.equal(suggestion, 'example');29});31 test('when unknown command and showSuggestionAfterError(false) then do not show suggestion', () => {32 const program = new Command();33 program.showSuggestionAfterError(false);34 program.command('example');35 const suggestion = getSuggestion(program, 'exampel');36 assert.equal(suggestion, null);37 });3831test('when unknown command and showSuggestionAfterError(false) then do not show suggestion', () => {32 const program = new Command();33 program.showSuggestionAfterError(false);34 program.command('example');35 const suggestion = getSuggestion(program, 'exampel');36 assert.equal(suggestion, null);37});39 test('when unknown option and showSuggestionAfterError() then show suggestion', () => {40 const program = new Command();41 program.showSuggestionAfterError();42 program.option('--example');43 const suggestion = getSuggestion(program, '--exampel');44 assert.equal(suggestion, '--example');45 });4639test('when unknown option and showSuggestionAfterError() then show suggestion', () => {40 const program = new Command();41 program.showSuggestionAfterError();42 program.option('--example');43 const suggestion = getSuggestion(program, '--exampel');44 assert.equal(suggestion, '--example');47 test('when unknown option and showSuggestionAfterError(false) then do not show suggestion', () => {48 const program = new Command();49 program.showSuggestionAfterError(false);50 program.option('--example');51 const suggestion = getSuggestion(program, '--exampel');52 assert.equal(suggestion, null);53 });54});4647test('when unknown option and showSuggestionAfterError(false) then do not show suggestion', () => {48 const program = new Command();49 program.showSuggestionAfterError(false);50 program.option('--example');51 const suggestion = getSuggestion(program, '--exampel');52 assert.equal(suggestion, null);53});
modified:tests/command.summary.test.js+1 added-1 removed
1const commander = require('../');2const { test } = require('node:test');3const assert = require('node:assert/strict');45test('when set summary then get summary', () => {5test('Command.summary(): when set summary then get summary', () => {6 const program = new commander.Command();7 const summary = 'abcdef';8 program.summary(summary);9 assert.equal(program.summary(), summary);
1 unmodified line
modified:tests/command.unknownCommand.test.js+1 added-1 removed
1const { createTestCommand } = require('./testHelpers');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('unknownCommand', () => {5describe('parsing unknown command', () => {6 test('when unknown argument in simple program then error', () => {7 const program = createTestCommand();8 assert.throws(() => {9 program.parse('node test.js unknown'.split(' '));
45 unmodified lines
modified:tests/command.unknownOption.test.js+1 added-1 removed
2 unmodified lines
3const assert = require('node:assert/strict');45// Checking for detection of unknown options, including regression tests for some past issues.67describe('unknownOption', () => {7describe('parsing unknown option', () => {8 test('when specify unknown option with subcommand and action handler then error', () => {9 const program = createTestCommand();10 program.command('info').action(() => {});11
67 unmodified lines
modified:tests/command.usage.test.js+60 added-58 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('command Usage section in help', () => {5test('when default usage and check program help then starts with default usage', () => {6 const program = new commander.Command();6 test('when default usage and check program help then starts with default usage', () => {7 const program = new commander.Command();88 program.name('test');9 const helpInformation = program.helpInformation();9 program.name('test');10 const helpInformation = program.helpInformation();1111 assert.match(helpInformation, /^Usage: test \[options\]/);12});12 assert.match(helpInformation, /^Usage: test \[options\]/);13 });1414test('when custom usage and check program help then starts with custom usage', () => {15 const myUsage = 'custom';16 const program = new commander.Command();17 program.usage(myUsage);15 test('when custom usage and check program help then starts with custom usage', () => {16 const myUsage = 'custom';17 const program = new commander.Command();18 program.usage(myUsage);1919 program.name('test');20 const helpInformation = program.helpInformation();20 program.name('test');21 const helpInformation = program.helpInformation();2222 assert.match(helpInformation, new RegExp(`^Usage: test ${myUsage}`));23});23 assert.match(helpInformation, new RegExp(`^Usage: test ${myUsage}`));24 });2525test('when default usage and check subcommand help then starts with default usage including program name', () => {26 const program = new commander.Command();27 const subCommand = program.command('info');26 test('when default usage and check subcommand help then starts with default usage including program name', () => {27 const program = new commander.Command();28 const subCommand = program.command('info');2929 program.name('test');30 const helpInformation = subCommand.helpInformation();30 program.name('test');31 const helpInformation = subCommand.helpInformation();3232 assert.match(helpInformation, /^Usage: test info \[options\]/);33});33 assert.match(helpInformation, /^Usage: test info \[options\]/);34 });3535test('when custom usage and check subcommand help then starts with custom usage including program name', () => {36 const myUsage = 'custom';37 const program = new commander.Command();38 const subCommand = program.command('info').usage(myUsage);36 test('when custom usage and check subcommand help then starts with custom usage including program name', () => {37 const myUsage = 'custom';38 const program = new commander.Command();39 const subCommand = program.command('info').usage(myUsage);4040 program.name('test');41 const helpInformation = subCommand.helpInformation();41 program.name('test');42 const helpInformation = subCommand.helpInformation();4343 assert.match(helpInformation, new RegExp(`^Usage: test info ${myUsage}`));44});44 assert.match(helpInformation, new RegExp(`^Usage: test info ${myUsage}`));45 });4646test('when has option then [options] included in usage', () => {47 const program = new commander.Command();47 test('when has option then [options] included in usage', () => {48 const program = new commander.Command();4949 program.option('--foo');50 program.option('--foo');5151 assert.match(program.usage(), /\[options\]/);52});52 assert.match(program.usage(), /\[options\]/);53 });5454test('when no options then [options] not included in usage', () => {55 const program = new commander.Command();55 test('when no options then [options] not included in usage', () => {56 const program = new commander.Command();5757 program.helpOption(false);58 program.helpOption(false);5959 assert.doesNotMatch(program.usage(), /\[options\]/);60});60 assert.doesNotMatch(program.usage(), /\[options\]/);61 });6262test('when has command then [command] included in usage', () => {63 const program = new commander.Command();63 test('when has command then [command] included in usage', () => {64 const program = new commander.Command();6565 program.command('foo');66 program.command('foo');6767 assert.match(program.usage(), /\[command\]/);68});68 assert.match(program.usage(), /\[command\]/);69 });7070test('when no commands then [command] not included in usage', () => {71 const program = new commander.Command();71 test('when no commands then [command] not included in usage', () => {72 const program = new commander.Command();7373 assert.doesNotMatch(program.usage(), /\[command\]/);74});74 assert.doesNotMatch(program.usage(), /\[command\]/);75 });7676test('when argument then argument included in usage', () => {77 const program = new commander.Command();77 test('when argument then argument included in usage', () => {78 const program = new commander.Command();7979 program.argument('<file>');80 program.argument('<file>');8181 assert.match(program.usage(), /<file>/);82});82 assert.match(program.usage(), /<file>/);83 });8484test('when options and command and argument then all three included in usage', () => {85 const program = new commander.Command();85 test('when options and command and argument then all three included in usage', () => {86 const program = new commander.Command();8787 program.argument('<file>').option('--alpha').command('beta');88 program.argument('<file>').option('--alpha').command('beta');8989 assert.equal(program.usage(), '[options] [command] <file>');90 assert.equal(program.usage(), '[options] [command] <file>');91 });92});
deleted:tests/commander.configureCommand.test.js-92 removed
1const commander = require('../');2const { test } = require('node:test');3const assert = require('node:assert/strict');45// Mostly testing direct on program, limited check that (sub)command working same.67// Default behaviours89test('when default then options not stored on command', () => {10 const program = new commander.Command();11 program.option('--foo <value>', 'description');12 program.parse(['node', 'test', '--foo', 'bar']);13 assert.equal(program.foo, undefined);14 assert.equal(program.opts().foo, 'bar');15});1617test('when default then options+command passed to action', (t) => {18 const program = new commander.Command();19 const callback = t.mock.fn();20 program.argument('<value>').action(callback);21 program.parse(['node', 'test', 'value']);22 const callArgs = callback.mock.calls[0].arguments;23 assert.equal(callArgs[0], 'value');24 assert.equal(callArgs[1], program.opts());25 assert.equal(callArgs[2], program);26});2728// storeOptionsAsProperties2930test('when storeOptionsAsProperties() then options stored on command', () => {31 const program = new commander.Command();32 program.storeOptionsAsProperties().option('--foo <value>', 'description');33 program.parse(['node', 'test', '--foo', 'bar']);34 assert.equal(program.foo, 'bar');35 assert.equal(program.opts().foo, 'bar');36});3738test('when storeOptionsAsProperties(true) then options stored on command', () => {39 const program = new commander.Command();40 program.storeOptionsAsProperties(true).option('--foo <value>', 'description');41 program.parse(['node', 'test', '--foo', 'bar']);42 assert.equal(program.foo, 'bar');43 assert.equal(program.opts().foo, 'bar');44});4546test('when storeOptionsAsProperties(false) then options not stored on command', () => {47 const program = new commander.Command();48 program49 .storeOptionsAsProperties(false)50 .option('--foo <value>', 'description');51 program.parse(['node', 'test', '--foo', 'bar']);52 assert.equal(program.foo, undefined);53 assert.equal(program.opts().foo, 'bar');54});5556test('when storeOptionsAsProperties() then command+command passed to action', (t) => {57 const program = new commander.Command();58 const callback = t.mock.fn();59 program.storeOptionsAsProperties().argument('<value>').action(callback);60 program.parse(['node', 'test', 'value']);61 const callArgs = callback.mock.calls[0].arguments;62 assert.equal(callArgs[0], 'value');63 assert.equal(callArgs[1], program);64 assert.equal(callArgs[2], program);65});6667test('when storeOptionsAsProperties(false) then opts+command passed to action', (t) => {68 const program = new commander.Command();69 const callback = t.mock.fn();70 program.storeOptionsAsProperties(false).argument('<value>').action(callback);71 program.parse(['node', 'test', 'value']);72 const callArgs = callback.mock.calls[0].arguments;73 assert.equal(callArgs[0], 'value');74 assert.equal(callArgs[1], program.opts());75 assert.equal(callArgs[2], program);76});7778test('when storeOptionsAsProperties() after adding option then throw', () => {79 const program = new commander.Command();80 program.option('--port <number>', 'port number', '80');81 assert.throws(() => {82 program.storeOptionsAsProperties();83 });84});8586test('when storeOptionsAsProperties() after setting option value then throw', () => {87 const program = new commander.Command();88 program.setOptionValue('foo', 'bar');89 assert.throws(() => {90 program.storeOptionsAsProperties();91 });92});
added:tests/commander.storeOptionsAsProperties.test.js+99 added
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45// Mostly testing direct on program, limited check that (sub)command working same.67describe('Command.storeOptionsAsProperties()', () => {8 // Default behaviours910 test('when default then options not stored on command', () => {11 const program = new commander.Command();12 program.option('--foo <value>', 'description');13 program.parse(['node', 'test', '--foo', 'bar']);14 assert.equal(program.foo, undefined);15 assert.equal(program.opts().foo, 'bar');16 });1718 test('when default then options+command passed to action', (t) => {19 const program = new commander.Command();20 const callback = t.mock.fn();21 program.argument('<value>').action(callback);22 program.parse(['node', 'test', 'value']);23 const callArgs = callback.mock.calls[0].arguments;24 assert.equal(callArgs[0], 'value');25 assert.equal(callArgs[1], program.opts());26 assert.equal(callArgs[2], program);27 });2829 // storeOptionsAsProperties3031 test('when storeOptionsAsProperties() then options stored on command', () => {32 const program = new commander.Command();33 program.storeOptionsAsProperties().option('--foo <value>', 'description');34 program.parse(['node', 'test', '--foo', 'bar']);35 assert.equal(program.foo, 'bar');36 assert.equal(program.opts().foo, 'bar');37 });3839 test('when storeOptionsAsProperties(true) then options stored on command', () => {40 const program = new commander.Command();41 program42 .storeOptionsAsProperties(true)43 .option('--foo <value>', 'description');44 program.parse(['node', 'test', '--foo', 'bar']);45 assert.equal(program.foo, 'bar');46 assert.equal(program.opts().foo, 'bar');47 });4849 test('when storeOptionsAsProperties(false) then options not stored on command', () => {50 const program = new commander.Command();51 program52 .storeOptionsAsProperties(false)53 .option('--foo <value>', 'description');54 program.parse(['node', 'test', '--foo', 'bar']);55 assert.equal(program.foo, undefined);56 assert.equal(program.opts().foo, 'bar');57 });5859 test('when storeOptionsAsProperties() then command+command passed to action', (t) => {60 const program = new commander.Command();61 const callback = t.mock.fn();62 program.storeOptionsAsProperties().argument('<value>').action(callback);63 program.parse(['node', 'test', 'value']);64 const callArgs = callback.mock.calls[0].arguments;65 assert.equal(callArgs[0], 'value');66 assert.equal(callArgs[1], program);67 assert.equal(callArgs[2], program);68 });6970 test('when storeOptionsAsProperties(false) then opts+command passed to action', (t) => {71 const program = new commander.Command();72 const callback = t.mock.fn();73 program74 .storeOptionsAsProperties(false)75 .argument('<value>')76 .action(callback);77 program.parse(['node', 'test', 'value']);78 const callArgs = callback.mock.calls[0].arguments;79 assert.equal(callArgs[0], 'value');80 assert.equal(callArgs[1], program.opts());81 assert.equal(callArgs[2], program);82 });8384 test('when storeOptionsAsProperties() after adding option then throw', () => {85 const program = new commander.Command();86 program.option('--port <number>', 'port number', '80');87 assert.throws(() => {88 program.storeOptionsAsProperties();89 });90 });9192 test('when storeOptionsAsProperties() after setting option value then throw', () => {93 const program = new commander.Command();94 program.setOptionValue('foo', 'bar');95 assert.throws(() => {96 program.storeOptionsAsProperties();97 });98 });99});
modified:tests/createCommand.test.js+32 added-30 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Command.createCommand()', () => {5test('when createCommand then unattached', () => {6 const program = new commander.Command();7 const cmd = program.createCommand();8 assert.equal(program.commands.length, 0);9 assert.equal(cmd.parent, null);10});6 test('when createCommand then unattached', () => {7 const program = new commander.Command();8 const cmd = program.createCommand();9 assert.equal(program.commands.length, 0);10 assert.equal(cmd.parent, null);11 });1212test('when subclass overrides createCommand then subcommand is subclass', () => {13 class MyClass extends commander.Command {14 constructor(name) {15 super();16 this.myProperty = 'myClass';13 test('when subclass overrides createCommand then subcommand is subclass', () => {14 class MyClass extends commander.Command {15 constructor(name) {16 super();17 this.myProperty = 'myClass';18 }1920 createCommand(name) {21 return new MyClass(name);22 }23 }24 const program = new MyClass();25 const sub = program.command('sub');26 assert.equal(sub.myProperty, 'myClass');27 });2819 createCommand(name) {20 return new MyClass(name);29 test('when override createCommand then subcommand is custom', () => {30 function createCustom(name) {31 const cmd = new commander.Command();32 cmd.myProperty = 'custom';33 return cmd;34 }22 }23 const program = new MyClass();24 const sub = program.command('sub');25 assert.equal(sub.myProperty, 'myClass');35 const program = createCustom();36 program.createCommand = createCustom;37 const sub = program.command('sub');38 assert.equal(sub.myProperty, 'custom');39 });40});2728test('when override createCommand then subcommand is custom', () => {29 function createCustom(name) {30 const cmd = new commander.Command();31 cmd.myProperty = 'custom';32 return cmd;33 }34 const program = createCustom();35 program.createCommand = createCustom;36 const sub = program.command('sub');37 assert.equal(sub.myProperty, 'custom');38});
modified:tests/deprecated.test.js+1 added-1 removed
4 unmodified lines
5// Test for backwards compatible behaviour of deprecated features that don't fit in elsewhere.6// We keep deprecated features working (when not too difficult) to avoid breaking existing code7// and reduce barriers to updating to latest version of Commander.89describe('option with regular expression instead of custom processing function', () => {9describe('deprecated support for option custom processing using regular expression', () => {10 test('when option not given then value is default', () => {11 const program = new commander.Command();12 program.option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');13 program.parse([], { from: 'user' });
17 unmodified lines
modified:tests/help.argumentDescription.test.js+1 added-1 removed
2 unmodified lines
3const assert = require('node:assert/strict');45// These are tests of the Help class, not of the Command help.67describe('argumentDescription', () => {7describe('Help.argumentDescription()', () => {8 test('when argument has no description then empty string', () => {9 const argument = new commander.Argument('[n]');10 const helper = new commander.Help();11 assert.equal(helper.argumentDescription(argument), '');
38 unmodified lines
modified:tests/help.boxWrap.test.js+103 added-98 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Help.boxWrap()', () => {5test('when empty string then return empty string', () => {6 const helper = new commander.Help();7 const text = '';8 const wrapped = helper.boxWrap(text, 50);9 assert.equal(wrapped, text);10});6 test('when empty string then return empty string', () => {7 const helper = new commander.Help();8 const text = '';9 const wrapped = helper.boxWrap(text, 50);10 assert.equal(wrapped, text);11 });1212test('when string contains unix line breaks then return (unix) empty lines', () => {13 const helper = new commander.Help();14 const text = '\n\n\n';15 const wrapped = helper.boxWrap(text, 50);16 assert.equal(wrapped, text);17});13 test('when string contains unix line breaks then return (unix) empty lines', () => {14 const helper = new commander.Help();15 const text = '\n\n\n';16 const wrapped = helper.boxWrap(text, 50);17 assert.equal(wrapped, text);18 });1919test('when string contains Windows line breaks then return (unix)) empty lines', () => {20 const helper = new commander.Help();21 const text = '\r\n\r\n\r\n';22 const wrapped = helper.boxWrap(text, 50);23 assert.equal(wrapped, '\n\n\n');24});20 test('when string contains Windows line breaks then return (unix)) empty lines', () => {21 const helper = new commander.Help();22 const text = '\r\n\r\n\r\n';23 const wrapped = helper.boxWrap(text, 50);24 assert.equal(wrapped, '\n\n\n');25 });2626test('when string contains only whitespace then returns empty string (trim right)', () => {27 const helper = new commander.Help();28 const text = ' \t ';29 const wrapped = helper.boxWrap(text, 50);30 assert.equal(wrapped, '');31});27 test('when string contains only whitespace then returns empty string (trim right)', () => {28 const helper = new commander.Help();29 const text = ' \t ';30 const wrapped = helper.boxWrap(text, 50);31 assert.equal(wrapped, '');32 });3333test('when string contains leading whitespace then returns string with leading whitespace', () => {34 const helper = new commander.Help();35 const text = ' abc';36 const wrapped = helper.boxWrap(text, 50);37 assert.equal(wrapped, ' abc');38});34 test('when string contains leading whitespace then returns string with leading whitespace', () => {35 const helper = new commander.Help();36 const text = ' abc';37 const wrapped = helper.boxWrap(text, 50);38 assert.equal(wrapped, ' abc');39 });4040test('when string contains intermediate whitespace then returns string with intermediate whitespace', () => {41 const helper = new commander.Help();42 const text = '123 456';43 const wrapped = helper.boxWrap(text, 50);44 assert.equal(wrapped, '123 456');45});41 test('when string contains intermediate whitespace then returns string with intermediate whitespace', () => {42 const helper = new commander.Help();43 const text = '123 456';44 const wrapped = helper.boxWrap(text, 50);45 assert.equal(wrapped, '123 456');46 });4747test('when string contains trailing whitespace then returns string without trailing whitespace (trim right)', () => {48 const helper = new commander.Help();49 const text = '123 456 ';50 const wrapped = helper.boxWrap(text, 50);51 assert.equal(wrapped, '123 456');52});48 test('when string contains trailing whitespace then returns string without trailing whitespace (trim right)', () => {49 const helper = new commander.Help();50 const text = '123 456 ';51 const wrapped = helper.boxWrap(text, 50);52 assert.equal(wrapped, '123 456');53 });5454test('when string contains escape sequences then returns string with escape sequences', () => {55 const helper = new commander.Help();56 const text = '123 456 ';57 const wrapped = helper.boxWrap(text, 50);58 assert.equal(wrapped, '123 456');59});55 test('when string contains escape sequences then returns string with escape sequences', () => {56 const helper = new commander.Help();57 const text = '123 456 ';58 const wrapped = helper.boxWrap(text, 50);59 assert.equal(wrapped, '123 456');60 });6161test('when string has enough words to wrap then returns two wrapped lines', () => {62 const helper = new commander.Help();63 const text = '123 567 901 345 789 123 567 901 345 789 123 567 901';64 const wrapped = helper.boxWrap(text, 45);65 assert.equal(wrapped, '123 567 901 345 789 123 567 901 345 789 123\n567 901');66});62 test('when string has enough words to wrap then returns two wrapped lines', () => {63 const helper = new commander.Help();64 const text = '123 567 901 345 789 123 567 901 345 789 123 567 901';65 const wrapped = helper.boxWrap(text, 45);66 assert.equal(67 wrapped,68 '123 567 901 345 789 123 567 901 345 789 123\n567 901',69 );70 });7168test('when string has enough words and escape sequences to wrap then returns wrapped line with break ignoring escape sequences', () => {69 const helper = new commander.Help();70 const CSI = '\u001b[';71 const underlinedText = `${CSI}4mXYZ${CSI}24m`;72 const text = `${underlinedText}${' ABC'.repeat(19)}`;73 const wrapped = helper.boxWrap(text, 44);74 assert.equal(75 wrapped,76 `${underlinedText} ${'ABC '.repeat(9)}ABC72 test('when string has enough words and escape sequences to wrap then returns wrapped line with break ignoring escape sequences', () => {73 const helper = new commander.Help();74 const CSI = '\u001b[';75 const underlinedText = `${CSI}4mXYZ${CSI}24m`;76 const text = `${underlinedText}${' ABC'.repeat(19)}`;77 const wrapped = helper.boxWrap(text, 44);78 assert.equal(79 wrapped,80 `${underlinedText} ${'ABC '.repeat(9)}ABC81${'ABC '.repeat(8)}ABC`,78 );79});82 );83 });8481test('when first word longer than width then soft wrap', () => {82 const helper = new commander.Help();83 const text = 'abc'.repeat(20);84 const wrapped = helper.boxWrap(text, 40);85 assert.equal(wrapped, text);86});85 test('when first word longer than width then soft wrap', () => {86 const helper = new commander.Help();87 const text = 'abc'.repeat(20);88 const wrapped = helper.boxWrap(text, 40);89 assert.equal(wrapped, text);90 });9188test('when second word longer than width then wrap and soft wrap', () => {89 const helper = new commander.Help();90 const text = 'xyz ' + 'abc'.repeat(20);91 const wrapped = helper.boxWrap(text, 40);92 assert.equal(wrapped, `xyz\n${'abc'.repeat(20)}`);93});92 test('when second word longer than width then wrap and soft wrap', () => {93 const helper = new commander.Help();94 const text = 'xyz ' + 'abc'.repeat(20);95 const wrapped = helper.boxWrap(text, 40);96 assert.equal(wrapped, `xyz\n${'abc'.repeat(20)}`);97 });9895test('when set width 41 then wrap at 41', () => {96 const helper = new commander.Help();97 const text = 'X'.repeat(39) + ' 1 2 3';98 let wrapped = helper.boxWrap(text, 40);99 assert.equal(wrapped, 'X'.repeat(39) + '\n1 2 3');100 wrapped = helper.boxWrap(text, 41);101 assert.equal(wrapped, 'X'.repeat(39) + ' 1\n2 3');102});99 test('when set width 41 then wrap at 41', () => {100 const helper = new commander.Help();101 const text = 'X'.repeat(39) + ' 1 2 3';102 let wrapped = helper.boxWrap(text, 40);103 assert.equal(wrapped, 'X'.repeat(39) + '\n1 2 3');104 wrapped = helper.boxWrap(text, 41);105 assert.equal(wrapped, 'X'.repeat(39) + ' 1\n2 3');106 });107104test('when set width 12 (too small) then skip wrap', () => {105 const helper = new commander.Help();106 const text = ' x'.repeat(8) + ' yy'.repeat(6);107 let wrapped = helper.boxWrap(text, 14);108 assert.equal(wrapped, text);109});108 test('when set width 12 (too small) then skip wrap', () => {109 const helper = new commander.Help();110 const text = ' x'.repeat(8) + ' yy'.repeat(6);111 let wrapped = helper.boxWrap(text, 14);112 assert.equal(wrapped, text);113 });114111test('when set width 12 (and set minWrapWidth) then skip wrap', () => {112 const helper = new commander.Help();113 helper.minWidthToWrap = 1;114 const text = ' x'.repeat(8) + ' yy'.repeat(6);115 let wrapped = helper.boxWrap(text, 14);116 assert.equal(wrapped, ' x x x x x x x\nx yy yy yy yy\nyy yy');115 test('when set width 12 (and set minWrapWidth) then skip wrap', () => {116 const helper = new commander.Help();117 helper.minWidthToWrap = 1;118 const text = ' x'.repeat(8) + ' yy'.repeat(6);119 let wrapped = helper.boxWrap(text, 14);120 assert.equal(wrapped, ' x x x x x x x\nx yy yy yy yy\nyy yy');121 });122});
modified:tests/help.commandTerm.test.js+1 added-1 removed
4 unmodified lines
5// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78// subcommandTerm does not currently respect helpOption or ignore hidden options, so not testing those.9describe('subcommandTerm', () => {9describe('Help.subcommandTerm()', () => {10 test('when plain command then returns name', () => {11 const command = new commander.Command('program');12 const helper = new commander.Help();13 assert.equal(helper.subcommandTerm(command), 'program');
32 unmodified lines
modified:tests/help.commandUsage.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('commandUsage', () => {8describe('Help.commandUsage()', () => {9 test('when single program then "program [options]"', () => {10 const program = new commander.Command();11 program.name('program');12 const helper = new commander.Help();
33 unmodified lines
modified:tests/help.longestArgumentTermLength.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('longestArgumentTermLength', () => {8describe('Help.longestArgumentTermLength()', () => {9 test('when no arguments then returns zero', () => {10 const program = new commander.Command();11 const helper = new commander.Help();12 assert.equal(helper.longestArgumentTermLength(program, helper), 0);
24 unmodified lines
modified:tests/help.longestCommandTermLength.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('longestSubcommandTermLength', () => {8describe('Help.longestSubcommandTermLength()', () => {9 test('when no commands then returns zero', () => {10 const program = new commander.Command();11 const helper = new commander.Help();12 assert.equal(helper.longestSubcommandTermLength(program, helper), 0);
49 unmodified lines
modified:tests/help.longestOptionTermLength.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('longestOptionTermLength', () => {8describe('Help.longestOptionTermLength()', () => {9 test('when no option then returns zero', () => {10 const program = new commander.Command();11 program.helpOption(false);12 const helper = new commander.Help();
26 unmodified lines
modified:tests/help.minWidthToWrap.test.js+1 added-1 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Help.minWidthToWrap', () => {5describe('Help.minWidthToWrap()', () => {6 test('when enough width then wrap', () => {7 const program = new commander.Command('program');8 program.description('x '.repeat(110));9 program.configureOutput({
40 unmodified lines
modified:tests/help.optionDescription.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('optionDescription', () => {8describe('Help.optionDescription()', () => {9 test('when option has no description then empty string', () => {10 const option = new commander.Option('-a');11 const helper = new commander.Help();12 assert.equal(helper.optionDescription(option), '');
91 unmodified lines
modified:tests/help.optionTerm.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('optionTerm', () => {8describe('Help.optionTerm()', () => {9 test('when -s flags then returns flags', () => {10 const flags = '-s';11 const option = new commander.Option(flags);12 const helper = new commander.Help();
24 unmodified lines
modified:tests/help.padWidth.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('padWidth', () => {8describe('Help.padWidth()', () => {9 test('when argument term longest return argument length', () => {10 const longestThing = 'veryLongThingBiggerThanOthers';11 const program = new commander.Command();12 program.argument(`<${longestThing}>`, 'description').option('-o');
35 unmodified lines
modified:tests/help.preformatted.test.js+1 added-1 removed
1const { Help, Command } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('preformatted', () => {5describe('Help.preformatted()', () => {6 test('when single line then false', () => {7 const helper = new Help();8 assert.equal(helper.preformatted('a b c'), false);9 });
63 unmodified lines
modified:tests/help.showGlobalOptions.test.js+44 added-42 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Help.showGlobalOptions()', () => {5test('when default configuration then global options hidden', () => {6 const program = new commander.Command();7 program.option('--global');8 const sub = program.command('sub');9 assert.doesNotMatch(sub.helpInformation(), /global/);10});6 test('when default configuration then global options hidden', () => {7 const program = new commander.Command();8 program.option('--global');9 const sub = program.command('sub');10 assert.doesNotMatch(sub.helpInformation(), /global/);11 });1212test('when showGlobalOptions:true then program options shown', () => {13 const program = new commander.Command();14 program.option('--global').configureHelp({ showGlobalOptions: true });15 const sub = program.command('sub');16 assert.match(sub.helpInformation(), /global/);17});13 test('when showGlobalOptions:true then program options shown', () => {14 const program = new commander.Command();15 program.option('--global').configureHelp({ showGlobalOptions: true });16 const sub = program.command('sub');17 assert.match(sub.helpInformation(), /global/);18 });1919test('when showGlobalOptions:true and no global options then global options header not shown', () => {20 const program = new commander.Command();21 program.configureHelp({ showGlobalOptions: true });22 const sub = program.command('sub');23 assert.doesNotMatch(sub.helpInformation(), /Global/);24});20 test('when showGlobalOptions:true and no global options then global options header not shown', () => {21 const program = new commander.Command();22 program.configureHelp({ showGlobalOptions: true });23 const sub = program.command('sub');24 assert.doesNotMatch(sub.helpInformation(), /Global/);25 });2626test('when showGlobalOptions:true and nested commands then combined nested options shown program last', () => {27 const program = new commander.Command();28 program.option('--global').configureHelp({ showGlobalOptions: true });29 const sub1 = program.command('sub1').option('--sub1');30 const sub2 = sub1.command('sub2');31 assert.match(32 sub2.helpInformation(),33 /Global Options:\n {2}--sub1\n {2}--global\n/,34 );35});27 test('when showGlobalOptions:true and nested commands then combined nested options shown program last', () => {28 const program = new commander.Command();29 program.option('--global').configureHelp({ showGlobalOptions: true });30 const sub1 = program.command('sub1').option('--sub1');31 const sub2 = sub1.command('sub2');32 assert.match(33 sub2.helpInformation(),34 /Global Options:\n {2}--sub1\n {2}--global\n/,35 );36 });3737test('when showGlobalOptions:true and sortOptions: true then global options sorted', () => {38 const program = new commander.Command();39 program40 .option('-3')41 .option('-4')42 .option('-2')43 .configureHelp({ showGlobalOptions: true, sortOptions: true });44 const sub1 = program.command('sub1').option('-6').option('-1').option('-5');45 const sub2 = sub1.command('sub2');46 assert.match(47 sub2.helpInformation(),48 /Global Options:\n {2}-1\n {2}-2\n {2}-3\n {2}-4\n {2}-5\n {2}-6\n/,49 );38 test('when showGlobalOptions:true and sortOptions: true then global options sorted', () => {39 const program = new commander.Command();40 program41 .option('-3')42 .option('-4')43 .option('-2')44 .configureHelp({ showGlobalOptions: true, sortOptions: true });45 const sub1 = program.command('sub1').option('-6').option('-1').option('-5');46 const sub2 = sub1.command('sub2');47 assert.match(48 sub2.helpInformation(),49 /Global Options:\n {2}-1\n {2}-2\n {2}-3\n {2}-4\n {2}-5\n {2}-6\n/,50 );51 });52});
modified:tests/help.sortCommands.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('sortSubcommands', () => {8describe('Help.configureHelp({ sortSubcommands: true })', () => {9 test('when unsorted then commands in order added', () => {10 const program = new commander.Command();11 program12 .command('ccc', 'desc')
23 unmodified lines
modified:tests/help.sortOptions.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('sortOptions', () => {8describe('Help.configureHelp({ sortOptions: true })', () => {9 test('when unsorted then options in order added', () => {10 const program = new commander.Command();11 program12 .option('--zzz', 'desc')
86 unmodified lines
modified:tests/help.stripAnsi.test.js+48 added-46 removed
1const { stripColor } = require('../lib/help');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters6
1 unmodified line
89const ESC = '\u001b';10const CSI = ESC + '[';1112describe('internal stripColor()', () => {12test('SGR only', () => {13 const str = `${CSI}4m`;14 assert.equal(stripColor(str), '');15});13 test('SGR only', () => {14 const str = `${CSI}4m`;15 assert.equal(stripColor(str), '');16 });1717test('SGR at start', () => {18 const str = `${CSI}4mX`;19 assert.equal(stripColor(str), 'X');20});18 test('SGR at start', () => {19 const str = `${CSI}4mX`;20 assert.equal(stripColor(str), 'X');21 });2222test('SGR in middle', () => {23 const str = `X${CSI}4mY`;24 assert.equal(stripColor(str), 'XY');25});23 test('SGR in middle', () => {24 const str = `X${CSI}4mY`;25 assert.equal(stripColor(str), 'XY');26 });2727test('SGR at end', () => {28 const str = `${CSI}4mY`;29 assert.equal(stripColor(str), 'Y');30});28 test('SGR at end', () => {29 const str = `${CSI}4mY`;30 assert.equal(stripColor(str), 'Y');31 });3232test('SGR pair', () => {33 // underline and not underlined34 const str = `${CSI}4mABC${CSI}24m`;35 assert.equal(stripColor(str), 'ABC');36});33 test('SGR pair', () => {34 // underline and not underlined35 const str = `${CSI}4mABC${CSI}24m`;36 assert.equal(stripColor(str), 'ABC');37 });3838test('explicit reset with zero', () => {39 const str = `${CSI}0m`;40 assert.equal(stripColor(str), '');41});39 test('explicit reset with zero', () => {40 const str = `${CSI}0m`;41 assert.equal(stripColor(str), '');42 });4343test('implicit reset without zero', () => {44 const str = `${CSI}m`;45 assert.equal(stripColor(str), '');46});44 test('implicit reset without zero', () => {45 const str = `${CSI}m`;46 assert.equal(stripColor(str), '');47 });4848test('multiple params: select foreground colour', () => {49 const str = `${CSI}38;5;4m`;50 assert.equal(stripColor(str), '');51});49 test('multiple params: select foreground colour', () => {50 const str = `${CSI}38;5;4m`;51 assert.equal(stripColor(str), '');52 });5353test('multiple params: general', () => {54 const str = `${CSI}2;3;4m`;55 assert.equal(stripColor(str), '');56});54 test('multiple params: general', () => {55 const str = `${CSI}2;3;4m`;56 assert.equal(stripColor(str), '');57 });5858test('multiple params: missing param', () => {59 // CSI sequences can omit number (which is then treated as 0)60 const str = `${CSI};;m`;61 assert.equal(stripColor(str), '');62});59 test('multiple params: missing param', () => {60 // CSI sequences can omit number (which is then treated as 0)61 const str = `${CSI};;m`;62 assert.equal(stripColor(str), '');63 });6464test('incomplete SGR sequence', () => {65 const str = `${CSI}14X`;66 assert.equal(stripColor(str), `${CSI}14X`);65 test('incomplete SGR sequence', () => {66 const str = `${CSI}14X`;67 assert.equal(stripColor(str), `${CSI}14X`);68 });69});
modified:tests/help.style.test.js+2 added-2 removed
12 unmodified lines
13 // Not really zero width for the "color", but pretend so spacing matches no-color output.14 return stripRed(str).length;15}1617describe('override style methods and check help information', () => {17describe('Help.configureHelp() overrides of style methods', () => {18 function makeProgram() {19 const program = new Command('program')20 .description('program description')21 .argument('<file>', 'arg description')
221 unmodified lines
243 );244 });245});246247describe('check styles with configureOutput overrides for color', () => {247describe('Help.configureHelp() overrides of color methods', () => {248 function makeProgram(hasColors) {249 const program = new Command('program');250 program.myHelpText = [];251 program
45 unmodified lines
modified:tests/help.subcommandDescription.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('subcommandDescription', () => {8describe('Help.subcommandDescription()', () => {9 test('when program has no summary or description then empty string', () => {10 const program = new commander.Command();11 const helper = new commander.Help();12 assert.equal(helper.subcommandDescription(program), '');
27 unmodified lines
modified:tests/help.suggestion.test.js+196 added-194 removed
29 unmodified lines
30 const match = message.match(/Did you mean (one of )?(.*)\?/);31 return match ? match[2] : null;32}3334describe('Command.showSuggestionAfterError()', () => {34describe('command suggestions', () => {35 const commandSuggestionTable = [36 ['yyy', ['zzz'], null, 'none similar'],37 ['a', ['b'], null, 'one edit away but not similar'],38 ['a', ['ab'], 'ab', 'one edit away'],39 ['ab', ['a'], null, 'one edit away'],40 ['at', ['cat'], 'cat', '1 insertion'],41 ['cat', ['at'], 'at', '1 deletion'],42 ['bat', ['cat'], 'cat', '1 substitution'],43 ['act', ['cat'], 'cat', '1 transposition'],44 ['cxx', ['cat'], null, '2 edits away and short string'],45 ['caxx', ['cart'], 'cart', '2 edits away and longer string'],46 [47 '1234567',48 ['1234567890'],49 '1234567890',50 '3 edits away is similar for long string',51 ],52 ['123456', ['1234567890'], null, '4 edits is too far'],53 ['xat', ['rat', 'cat', 'bat'], 'bat, cat, rat', 'sorted possibles'],54 [55 'cart',56 ['camb', 'cant', 'bard'],57 'cant',58 'only closest of different edit distances',59 ],60 ];61 commandSuggestionTable.forEach(62 ([arg, commandNames, expected, description]) => {63 test(`when cli of ${arg} and commands ${JSON.stringify(commandNames)} then suggest ${expected} because ${description}`, () => {64 const program = new Command();65 commandNames.forEach((name) => {66 program.command(name);35 describe('command suggestions', () => {36 const commandSuggestionTable = [37 ['yyy', ['zzz'], null, 'none similar'],38 ['a', ['b'], null, 'one edit away but not similar'],39 ['a', ['ab'], 'ab', 'one edit away'],40 ['ab', ['a'], null, 'one edit away'],41 ['at', ['cat'], 'cat', '1 insertion'],42 ['cat', ['at'], 'at', '1 deletion'],43 ['bat', ['cat'], 'cat', '1 substitution'],44 ['act', ['cat'], 'cat', '1 transposition'],45 ['cxx', ['cat'], null, '2 edits away and short string'],46 ['caxx', ['cart'], 'cart', '2 edits away and longer string'],47 [48 '1234567',49 ['1234567890'],50 '1234567890',51 '3 edits away is similar for long string',52 ],53 ['123456', ['1234567890'], null, '4 edits is too far'],54 ['xat', ['rat', 'cat', 'bat'], 'bat, cat, rat', 'sorted possibles'],55 [56 'cart',57 ['camb', 'cant', 'bard'],58 'cant',59 'only closest of different edit distances',60 ],61 ];62 commandSuggestionTable.forEach(63 ([arg, commandNames, expected, description]) => {64 test(`when cli of ${arg} and commands ${JSON.stringify(commandNames)} then suggest ${expected} because ${description}`, () => {65 const program = new Command();66 commandNames.forEach((name) => {67 program.command(name);68 });69 const suggestion = getSuggestion(program, arg);70 assert.equal(suggestion, expected);71 });68 const suggestion = getSuggestion(program, arg);69 assert.equal(suggestion, expected);70 });71 },72 );73});72 },73 );74 });7575test('when similar alias then suggest alias', () => {76 const program = new Command();77 program.command('xyz').alias('car');78 const suggestion = getSuggestion(program, 'bar');79 assert.equal(suggestion, 'car');80});76 test('when similar alias then suggest alias', () => {77 const program = new Command();78 program.command('xyz').alias('car');79 const suggestion = getSuggestion(program, 'bar');80 assert.equal(suggestion, 'car');81 });8282test('when similar hidden alias then not suggested', () => {83 const program = new Command();84 program.command('xyz').alias('visible').alias('silent');85 const suggestion = getSuggestion(program, 'slent');86 assert.equal(suggestion, null);87});83 test('when similar hidden alias then not suggested', () => {84 const program = new Command();85 program.command('xyz').alias('visible').alias('silent');86 const suggestion = getSuggestion(program, 'slent');87 assert.equal(suggestion, null);88 });8989test('when similar command and alias then suggest both', () => {90 const program = new Command();91 program.command('aaaaa').alias('cat');92 program.command('bat');93 program.command('ccccc');94 const suggestion = getSuggestion(program, 'mat');95 assert.equal(suggestion, 'bat, cat');96});90 test('when similar command and alias then suggest both', () => {91 const program = new Command();92 program.command('aaaaa').alias('cat');93 program.command('bat');94 program.command('ccccc');95 const suggestion = getSuggestion(program, 'mat');96 assert.equal(suggestion, 'bat, cat');97 });9898test('when implicit help command then help is candidate for suggestion', () => {99 const program = new Command();100 program.command('sub');101 const suggestion = getSuggestion(program, 'hepl');102 assert.equal(suggestion, 'help');103});99 test('when implicit help command then help is candidate for suggestion', () => {100 const program = new Command();101 program.command('sub');102 const suggestion = getSuggestion(program, 'hepl');103 assert.equal(suggestion, 'help');104 });105105test('when help command disabled then not candidate for suggestion', () => {106 const program = new Command();107 program.addHelpCommand(false);108 program.command('sub');109 const suggestion = getSuggestion(program, 'hepl');110 assert.equal(suggestion, null);111});106 test('when help command disabled then not candidate for suggestion', () => {107 const program = new Command();108 program.addHelpCommand(false);109 program.command('sub');110 const suggestion = getSuggestion(program, 'hepl');111 assert.equal(suggestion, null);112 });113113test('when default help option then --help is candidate for suggestion', () => {114 const program = new Command();115 const suggestion = getSuggestion(program, '--hepl');116 assert.equal(suggestion, '--help');117});114 test('when default help option then --help is candidate for suggestion', () => {115 const program = new Command();116 const suggestion = getSuggestion(program, '--hepl');117 assert.equal(suggestion, '--help');118 });119119test('when custom help option then --custom-help is candidate for suggestion', () => {120 const program = new Command();121 program.helpOption('-H, --custom-help');122 const suggestion = getSuggestion(program, '--custom-hepl');123 assert.equal(suggestion, '--custom-help');124});120 test('when custom help option then --custom-help is candidate for suggestion', () => {121 const program = new Command();122 program.helpOption('-H, --custom-help');123 const suggestion = getSuggestion(program, '--custom-hepl');124 assert.equal(suggestion, '--custom-help');125 });126126test('when help option disabled then not candidate for suggestion', () => {127 const program = new Command();128 program.helpOption(false);129 const suggestion = getSuggestion(program, '--hepl');130 assert.equal(suggestion, null);131});127 test('when help option disabled then not candidate for suggestion', () => {128 const program = new Command();129 program.helpOption(false);130 const suggestion = getSuggestion(program, '--hepl');131 assert.equal(suggestion, null);132 });133133test('when command:* listener and unknown command then no suggestion', () => {134 // Because one use for command:* was to handle unknown commands.135 // Listener actually stops error being thrown, but we just care about affect on suggestion in this test.136 const program = new Command();137 program.on('command:*', () => {});138 program.command('rat');139 const suggestion = getSuggestion(program, 'cat');140 assert.equal(suggestion, null);141});134 test('when command:* listener and unknown command then no suggestion', () => {135 // Because one use for command:* was to handle unknown commands.136 // Listener actually stops error being thrown, but we just care about affect on suggestion in this test.137 const program = new Command();138 program.on('command:*', () => {});139 program.command('rat');140 const suggestion = getSuggestion(program, 'cat');141 assert.equal(suggestion, null);142 });143143describe('option suggestions', () => {144 const optionSuggestionTable = [145 ['--yyy', ['--zzz'], null, 'none similar'],146 ['--a', ['--b'], null, 'one edit away but not similar'],147 ['--a', ['--ab'], '--ab', 'one edit away'],148 ['--ab', ['--a'], null, 'one edit away'],149 ['--at', ['--cat'], '--cat', '1 insertion'],150 ['--cat', ['--at'], '--at', '1 deletion'],151 ['--bat', ['--cat'], '--cat', '1 substitution'],152 ['--act', ['--cat'], '--cat', '1 transposition'],153 ['--cxx', ['--cat'], null, '2 edits away and short string'],154 ['--caxx', ['--cart'], '--cart', '2 edits away and longer string'],155 [156 '--1234567',157 ['--1234567890'],158 '--1234567890',159 '3 edits away is similar for long string',160 ],161 ['--123456', ['--1234567890'], null, '4 edits is too far'],162 [163 '--xat',164 ['--rat', '--cat', '--bat'],165 '--bat, --cat, --rat',166 'sorted possibles',167 ],168 [169 '--cart',170 ['--camb', '--cant', '--bard'],171 '--cant',172 'only closest of different edit distances',173 ],174 ];144 describe('option suggestions', () => {145 const optionSuggestionTable = [146 ['--yyy', ['--zzz'], null, 'none similar'],147 ['--a', ['--b'], null, 'one edit away but not similar'],148 ['--a', ['--ab'], '--ab', 'one edit away'],149 ['--ab', ['--a'], null, 'one edit away'],150 ['--at', ['--cat'], '--cat', '1 insertion'],151 ['--cat', ['--at'], '--at', '1 deletion'],152 ['--bat', ['--cat'], '--cat', '1 substitution'],153 ['--act', ['--cat'], '--cat', '1 transposition'],154 ['--cxx', ['--cat'], null, '2 edits away and short string'],155 ['--caxx', ['--cart'], '--cart', '2 edits away and longer string'],156 [157 '--1234567',158 ['--1234567890'],159 '--1234567890',160 '3 edits away is similar for long string',161 ],162 ['--123456', ['--1234567890'], null, '4 edits is too far'],163 [164 '--xat',165 ['--rat', '--cat', '--bat'],166 '--bat, --cat, --rat',167 'sorted possibles',168 ],169 [170 '--cart',171 ['--camb', '--cant', '--bard'],172 '--cant',173 'only closest of different edit distances',174 ],175 ];176176 optionSuggestionTable.forEach(177 ([arg, commandNames, expected, description]) => {178 test(`when cli of ${arg} and options ${JSON.stringify(commandNames)} then suggest ${expected} because ${description}`, () => {179 const program = new Command();180 commandNames.forEach((name) => {181 program.option(name);177 optionSuggestionTable.forEach(178 ([arg, commandNames, expected, description]) => {179 test(`when cli of ${arg} and options ${JSON.stringify(commandNames)} then suggest ${expected} because ${description}`, () => {180 const program = new Command();181 commandNames.forEach((name) => {182 program.option(name);183 });184 const suggestion = getSuggestion(program, arg);185 assert.equal(suggestion, expected);186 });183 const suggestion = getSuggestion(program, arg);184 assert.equal(suggestion, expected);185 });186 },187 );188});187 },188 );189 });190190test('when no options then no suggestion', () => {191 // Checking nothing blows up as much as no suggestion!192 const program = new Command();193 program.helpOption(false);194 const suggestion = getSuggestion(program, '--option');195 assert.equal(suggestion, null);196});191 test('when no options then no suggestion', () => {192 // Checking nothing blows up as much as no suggestion!193 const program = new Command();194 program.helpOption(false);195 const suggestion = getSuggestion(program, '--option');196 assert.equal(suggestion, null);197 });198198test('when subcommand option then candidate for subcommand option suggestion', () => {199 const program = new Command();200 program.command('sub').option('-l,--local');201 const suggestion = getSuggestion(program, ['sub', '--loca']);202 assert.equal(suggestion, '--local');203});199 test('when subcommand option then candidate for subcommand option suggestion', () => {200 const program = new Command();201 program.command('sub').option('-l,--local');202 const suggestion = getSuggestion(program, ['sub', '--loca']);203 assert.equal(suggestion, '--local');204 });205205test('when global option then candidate for subcommand option suggestion', () => {206 const program = new Command();207 program.option('-g, --global');208 program.command('sub');209 const suggestion = getSuggestion(program, ['sub', '--globla']);210 assert.equal(suggestion, '--global');211});206 test('when global option then candidate for subcommand option suggestion', () => {207 const program = new Command();208 program.option('-g, --global');209 program.command('sub');210 const suggestion = getSuggestion(program, ['sub', '--globla']);211 assert.equal(suggestion, '--global');212 });213213test('when global option but positionalOptions then not candidate for subcommand suggestion', () => {214 const program = new Command();215 program.enablePositionalOptions();216 program.option('-g, --global');217 program.command('sub');218 const suggestion = getSuggestion(program, ['sub', '--globla']);219 assert.equal(suggestion, null);220});214 test('when global option but positionalOptions then not candidate for subcommand suggestion', () => {215 const program = new Command();216 program.enablePositionalOptions();217 program.option('-g, --global');218 program.command('sub');219 const suggestion = getSuggestion(program, ['sub', '--globla']);220 assert.equal(suggestion, null);221 });222222test('when global and local options then both candidates', () => {223 const program = new Command();224 program.option('--cat');225 program.command('sub').option('--rat');226 const suggestion = getSuggestion(program, ['sub', '--bat']);227 assert.equal(suggestion, '--cat, --rat');228});223 test('when global and local options then both candidates', () => {224 const program = new Command();225 program.option('--cat');226 program.command('sub').option('--rat');227 const suggestion = getSuggestion(program, ['sub', '--bat']);228 assert.equal(suggestion, '--cat, --rat');229 });230230test('when command hidden then not suggested as candidate', () => {231 const program = new Command();232 program.command('secret', { hidden: true });233 const suggestion = getSuggestion(program, 'secrt');234 assert.equal(suggestion, null);235});231 test('when command hidden then not suggested as candidate', () => {232 const program = new Command();233 program.command('secret', { hidden: true });234 const suggestion = getSuggestion(program, 'secrt');235 assert.equal(suggestion, null);236 });237237test('when option hidden then not suggested as candidate', () => {238 const program = new Command();239 program.addOption(new Option('--secret').hideHelp());240 const suggestion = getSuggestion(program, '--secrt');241 assert.equal(suggestion, null);242});238 test('when option hidden then not suggested as candidate', () => {239 const program = new Command();240 program.addOption(new Option('--secret').hideHelp());241 const suggestion = getSuggestion(program, '--secrt');242 assert.equal(suggestion, null);243 });244244test('when may be duplicate identical candidates then only return one', () => {245 const program = new Command();246 program.command('sub');247 const suggestion = getSuggestion(program, ['sub', '--hepl']);248 assert.equal(suggestion, '--help');245 test('when may be duplicate identical candidates then only return one', () => {246 const program = new Command();247 program.command('sub');248 const suggestion = getSuggestion(program, ['sub', '--hepl']);249 assert.equal(suggestion, '--help');250 });251});
modified:tests/help.visibleArguments.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('visibleArguments', () => {8describe('Help.visibleArguments()', () => {9 test('when no arguments then empty array', () => {10 const program = new commander.Command();11 const helper = new commander.Help();12 assert.deepEqual(helper.visibleArguments(program), []);
67 unmodified lines
modified:tests/help.visibleCommands.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('visibleCommands', () => {8describe('Help.visibleCommands()', () => {9 test('when no subcommands then empty array', () => {10 const program = new commander.Command();11 const helper = new commander.Help();12 assert.deepEqual(helper.visibleCommands(program), []);
25 unmodified lines
modified:tests/help.visibleGlobalOptions.test.js+40 added-38 removed
1const { test } = require('node:test');1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const commander = require('../');45describe('Help.visibleGlobalOptions()', () => {5test('when default configuration then return empty array', () => {6 const program = new commander.Command();7 program.option('--global');8 const sub = program.command('sub');9 const helper = sub.createHelp();10 assert.deepEqual(helper.visibleGlobalOptions(program), []);11});6 test('when default configuration then return empty array', () => {7 const program = new commander.Command();8 program.option('--global');9 const sub = program.command('sub');10 const helper = sub.createHelp();11 assert.deepEqual(helper.visibleGlobalOptions(program), []);12 });1313test('when showGlobalOptions:true then return program options', () => {14 const program = new commander.Command();15 program.option('--global').configureHelp({ showGlobalOptions: true });16 const sub = program.command('sub');17 const helper = sub.createHelp();18 const visibleOptionNames = helper19 .visibleGlobalOptions(sub)20 .map((option) => option.name());21 assert.deepEqual(visibleOptionNames, ['global']);22});14 test('when showGlobalOptions:true then return program options', () => {15 const program = new commander.Command();16 program.option('--global').configureHelp({ showGlobalOptions: true });17 const sub = program.command('sub');18 const helper = sub.createHelp();19 const visibleOptionNames = helper20 .visibleGlobalOptions(sub)21 .map((option) => option.name());22 assert.deepEqual(visibleOptionNames, ['global']);23 });2424test('when showGlobalOptions:true and program has version then return version', () => {25 const program = new commander.Command();26 program.configureHelp({ showGlobalOptions: true }).version('1.2.3');27 const sub = program.command('sub');28 const helper = sub.createHelp();29 const visibleOptionNames = helper30 .visibleGlobalOptions(sub)31 .map((option) => option.name());32 assert.deepEqual(visibleOptionNames, ['version']);33});25 test('when showGlobalOptions:true and program has version then return version', () => {26 const program = new commander.Command();27 program.configureHelp({ showGlobalOptions: true }).version('1.2.3');28 const sub = program.command('sub');29 const helper = sub.createHelp();30 const visibleOptionNames = helper31 .visibleGlobalOptions(sub)32 .map((option) => option.name());33 assert.deepEqual(visibleOptionNames, ['version']);34 });3535test('when showGlobalOptions:true and nested commands then return combined global options', () => {36 const program = new commander.Command();37 program.configureHelp({ showGlobalOptions: true }).option('--global');38 const sub1 = program.command('sub1').option('--sub1');39 const sub2 = sub1.command('sub2');40 const helper = sub2.createHelp();41 const visibleOptionNames = helper42 .visibleGlobalOptions(sub2)43 .map((option) => option.name());44 assert.deepEqual(visibleOptionNames, ['sub1', 'global']);36 test('when showGlobalOptions:true and nested commands then return combined global options', () => {37 const program = new commander.Command();38 program.configureHelp({ showGlobalOptions: true }).option('--global');39 const sub1 = program.command('sub1').option('--sub1');40 const sub2 = sub1.command('sub2');41 const helper = sub2.createHelp();42 const visibleOptionNames = helper43 .visibleGlobalOptions(sub2)44 .map((option) => option.name());45 assert.deepEqual(visibleOptionNames, ['sub1', 'global']);46 });47});
modified:tests/help.visibleOptions.test.js+1 added-1 removed
3 unmodified lines
45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).78describe('visibleOptions', () => {8describe('Help.visibleOptions()', () => {9 test('when no options then just help visible', () => {10 const program = new commander.Command();11 const helper = new commander.Help();12 const visibleOptionNames = helper
66 unmodified lines
modified:tests/helpGroup.test.js+2 added-2 removed
37 unmodified lines
38 assert.match(helpInfo, /Greek:\n *alpha\n *beta/);39 });40});4142describe('.optionsGroup', () => {42describe('Command.optionsGroup', () => {43 test('when add one option then help contains group', () => {44 const program = new Command();45 program.optionsGroup('Greek:');46 program.option('--alpha');
103 unmodified lines
150 );151 });152});153154describe('.commandsGroup', () => {154describe('Command.commandsGroup', () => {155 test('when add one command then help contains group', () => {156 const program = new Command();157 program.commandsGroup('Greek:');158 program.command('alpha');
97 unmodified lines
modified:tests/incrementNodeInspectorPort.test.js+1 added-1 removed
2 unmodified lines
3const childProcess = require('child_process');4const path = require('path');5const commander = require('../');67describe('incrementNodeInspectorPort', () => {7describe('increment node inspector port in executable subcommands', () => {8 function makeSpies(t) {9 const spawnSpy = t.mock.method(childProcess, 'spawn', () => {10 return {11 on: () => {},
133 unmodified lines
modified:tests/negatives.test.js+176 added-174 removed
1 unmodified line
2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56describe('negative numbers in args', () => {7 // boolean is whether is a consumable argument when negative numbers allowed8 const negativeNumbers = [9 ['-.1', true],10 ['-123', true],11 ['-123.45', true],12 ['-1e3', true],13 ['-1e+3', true],14 ['-1e-3', true],15 ['-1.2e3', true],16 ['-1.2e+3', true],17 ['-1.2e-3', true],18 ['-1e-3.0', false], // invalid number format19 ['--1 ', false], // invalid number format20 ['-0', true],21 ['1', true],22 ['-1x', false], // whole string is not a number23 ['-x-1 ', false], // whole string is not a number24 ['', true],25 ['-0x1234', false], // not a plain number26 ];6describe('negative numbers', () => {7 describe('negative numbers in args', () => {8 // boolean is whether is a consumable argument when negative numbers allowed9 const negativeNumbers = [10 ['-.1', true],11 ['-123', true],12 ['-123.45', true],13 ['-1e3', true],14 ['-1e+3', true],15 ['-1e-3', true],16 ['-1.2e3', true],17 ['-1.2e+3', true],18 ['-1.2e-3', true],19 ['-1e-3.0', false], // invalid number format20 ['--1 ', false], // invalid number format21 ['-0', true],22 ['1', true],23 ['-1x', false], // whole string is not a number24 ['-x-1 ', false], // whole string is not a number25 ['', true],26 ['-0x1234', false], // not a plain number27 ];2828 negativeNumbers.forEach(([value, consume]) => {29 function callProgram(program, args, consume) {30 if (consume) {31 assert.doesNotThrow(() => {32 program.parse(args, { from: 'user' });33 });34 } else {35 assert.throws(36 () => {29 negativeNumbers.forEach(([value, consume]) => {30 function callProgram(program, args, consume) {31 if (consume) {32 assert.doesNotThrow(() => {33 program.parse(args, { from: 'user' });34 });35 } else {36 assert.throws(37 () => {38 program.parse(args, { from: 'user' });38 },39 { code: 'commander.unknownOption' },40 );39 },40 { code: 'commander.unknownOption' },41 );42 }43 }42 }43 test(`when option-argument for short optional is ${value} then consumed=${consume}`, () => {44 const program = createTestCommand();45 program.option('-o, --optional [value]', 'optional option');46 const args = ['-o', value];47 callProgram(program, args, consume);48 // throws after setting optional to true49 assert.equal(program.opts()['optional'], consume ? value : true);50 });44 test(`when option-argument for short optional is ${value} then consumed=${consume}`, () => {45 const program = createTestCommand();46 program.option('-o, --optional [value]', 'optional option');47 const args = ['-o', value];48 callProgram(program, args, consume);49 // throws after setting optional to true50 assert.equal(program.opts()['optional'], consume ? value : true);51 });5252 test(`when option-argument for long optional is ${value} then consumed=${consume}`, () => {53 const program = createTestCommand();54 program.option('-o, --optional [value]', 'optional option');55 const args = ['--optional', value];56 callProgram(program, args, consume);57 // throws after setting optional to true58 assert.equal(program.opts()['optional'], consume ? value : true);59 });53 test(`when option-argument for long optional is ${value} then consumed=${consume}`, () => {54 const program = createTestCommand();55 program.option('-o, --optional [value]', 'optional option');56 const args = ['--optional', value];57 callProgram(program, args, consume);58 // throws after setting optional to true59 assert.equal(program.opts()['optional'], consume ? value : true);60 });6161 test(`when option-argument for short optional... is ${value} then consumed=${consume}`, () => {62 const program = createTestCommand();63 program.option('-o, --optional [value...]', 'optional option');64 const args = ['-o', 'first', value];65 callProgram(program, args, consume);66 // throws after consuming 'first'67 assert.deepEqual(68 program.opts()['optional'],69 consume ? ['first', value] : ['first'],70 );71 });62 test(`when option-argument for short optional... is ${value} then consumed=${consume}`, () => {63 const program = createTestCommand();64 program.option('-o, --optional [value...]', 'optional option');65 const args = ['-o', 'first', value];66 callProgram(program, args, consume);67 // throws after consuming 'first'68 assert.deepEqual(69 program.opts()['optional'],70 consume ? ['first', value] : ['first'],71 );72 });7373 test(`when option-argument for long optional... is ${value} then consumed=${consume}`, () => {74 const program = createTestCommand();75 program.option('-o, --optional [value...]', 'optional option');76 const args = ['--optional', 'first', value];77 callProgram(program, args, consume);78 // throws after consuming 'first'79 assert.deepEqual(80 program.opts()['optional'],81 consume ? ['first', value] : ['first'],82 );83 });74 test(`when option-argument for long optional... is ${value} then consumed=${consume}`, () => {75 const program = createTestCommand();76 program.option('-o, --optional [value...]', 'optional option');77 const args = ['--optional', 'first', value];78 callProgram(program, args, consume);79 // throws after consuming 'first'80 assert.deepEqual(81 program.opts()['optional'],82 consume ? ['first', value] : ['first'],83 );84 });8585 test(`when command-argument is ${value} then consumed=${consume}`, () => {86 const program = createTestCommand();87 program.argument('<value>', 'argument');88 const args = [value];89 callProgram(program, args, consume);90 assert.deepEqual(91 consume ? program.args : undefined,92 consume ? [value] : undefined,93 );94 });86 test(`when command-argument is ${value} then consumed=${consume}`, () => {87 const program = createTestCommand();88 program.argument('<value>', 'argument');89 const args = [value];90 callProgram(program, args, consume);91 assert.deepEqual(92 consume ? program.args : undefined,93 consume ? [value] : undefined,94 );95 });9696 test(`when digit option defined and option-argument is %s then negative not consumed`, () => {97 const program = createTestCommand();98 program99 .option('-o, --optional [value]', 'optional option')100 .option('-9', 'register option using digit');101 const args = ['-o', value];102 let customConsume = value[0] !== '-';103 callProgram(program, args, customConsume);104 assert.equal(program.opts()['optional'], customConsume ? value : true);97 test(`when digit option defined and option-argument is %s then negative not consumed`, () => {98 const program = createTestCommand();99 program100 .option('-o, --optional [value]', 'optional option')101 .option('-9', 'register option using digit');102 const args = ['-o', value];103 let customConsume = value[0] !== '-';104 callProgram(program, args, customConsume);105 assert.equal(program.opts()['optional'], customConsume ? value : true);106 });107108 test(`when digit option defined and command-argument is %s then negative not consumed`, () => {109 const program = createTestCommand();110 program.argument('[value]').option('-9', 'register option using digit');111 const args = [value];112 let customConsume = value[0] !== '-';113 callProgram(program, args, customConsume);114 assert.deepEqual(115 customConsume ? program.args : undefined,116 customConsume ? [value] : undefined,117 );118 });119 });120 });121107 test(`when digit option defined and command-argument is %s then negative not consumed`, () => {108 const program = createTestCommand();109 program.argument('[value]').option('-9', 'register option using digit');110 const args = [value];111 let customConsume = value[0] !== '-';112 callProgram(program, args, customConsume);113 assert.deepEqual(114 customConsume ? program.args : undefined,115 customConsume ? [value] : undefined,116 );122 test('when complex example with negative numbers then all consumed', () => {123 const program = new Command();124 program125 .option('-o [value]', 'optional')126 .option('-m <value>', 'required option-argument')127 .option('-O [value...]', 'optional')128 .option('-M <value...>', 'required option-argument')129 .argument('[value...]', 'argument');130 const args = [131 '-10',132 '-O',133 '-40',134 '-41',135 '-M',136 '-50',137 '-51',138 '-o',139 '-20',140 '-m',141 '-30',142 '-11',143 ];144 program.parse(args, { from: 'user' });145 assert.deepEqual(program.opts(), {146 o: '-20',147 m: '-30',148 O: ['-40', '-41'],149 M: ['-50', '-51'],150 });151 assert.deepEqual(program.args, ['-10', '-11']);152 });119});153121test('when complex example with negative numbers then all consumed', () => {122 const program = new Command();123 program124 .option('-o [value]', 'optional')125 .option('-m <value>', 'required option-argument')126 .option('-O [value...]', 'optional')127 .option('-M <value...>', 'required option-argument')128 .argument('[value...]', 'argument');129 const args = [130 '-10',131 '-O',132 '-40',133 '-41',134 '-M',135 '-50',136 '-51',137 '-o',138 '-20',139 '-m',140 '-30',141 '-11',142 ];143 program.parse(args, { from: 'user' });144 assert.deepEqual(program.opts(), {145 o: '-20',146 m: '-30',147 O: ['-40', '-41'],148 M: ['-50', '-51'],154 test('when program has digit option then negatives not allowed in leaf command', () => {155 const program = createTestCommand();156 program.option('-2', 'double option');157 let leafArgs;158 program159 .command('leaf')160 .argument('[value...]')161 .action((args) => {162 leafArgs = args;163 });164 const args = ['leaf', '-1'];165 assert.throws(() => program.parse(args, { from: 'user' }));166 });150 assert.deepEqual(program.args, ['-10', '-11']);151});167153test('when program has digit option then negatives not allowed in leaf command', () => {154 const program = createTestCommand();155 program.option('-2', 'double option');156 let leafArgs;157 program158 .command('leaf')159 .argument('[value...]')160 .action((args) => {161 leafArgs = args;162 });163 const args = ['leaf', '-1'];164 assert.throws(() => program.parse(args, { from: 'user' }));165});168 test('when default command without digit option then negatives accepted', () => {169 const program = new Command();170 let leafArgs;171 program172 .command('leaf', { isDefault: true })173 .argument('[value...]')174 .action((args) => {175 leafArgs = args;176 });177 program.parse(['-1'], { from: 'user' });178 assert.deepEqual(leafArgs, ['-1']);179 });180167test('when default command without digit option then negatives accepted', () => {168 const program = new Command();169 let leafArgs;170 program171 .command('leaf', { isDefault: true })172 .argument('[value...]')173 .action((args) => {174 leafArgs = args;175 });176 program.parse(['-1'], { from: 'user' });177 assert.deepEqual(leafArgs, ['-1']);178});181 test('when default command with digit option then negative throws', () => {182 const program = createTestCommand();183 program184 .command('leaf', { isDefault: true })185 .option('-2')186 .argument('[value...]')187 .action(() => {});188 assert.throws(() => program.parse(['-1'], { from: 'user' }));189 });190180test('when default command with digit option then negative throws', () => {181 const program = createTestCommand();182 program183 .command('leaf', { isDefault: true })184 .option('-2')185 .argument('[value...]')186 .action(() => {});187 assert.throws(() => program.parse(['-1'], { from: 'user' }));191 test('when program has subcommand and action handler then negative command-argument unsupported', () => {192 // Known limitation in parsing. Only allowed negative command-arguments in leaf commands193 // to minimise changes to parsing when added support for negative numbers.194 const program = createTestCommand();195 program.argument('[value...]').action(() => {});196 program.command('leaf').action(() => {});197 assert.throws(() => program.parse(['-1'], { from: 'user' }));198 });199});189190test('when program has subcommand and action handler then negative command-argument unsupported', () => {191 // Known limitation in parsing. Only allowed negative command-arguments in leaf commands192 // to minimise changes to parsing when added support for negative numbers.193 const program = createTestCommand();194 program.argument('[value...]').action(() => {});195 program.command('leaf').action(() => {});196 assert.throws(() => program.parse(['-1'], { from: 'user' }));197});
modified:tests/options.bool.combo.test.js+157 added-155 removed
3 unmodified lines
45// Test combination of flag and --no-flag6// (single flags tested in options.bool.test.js)78describe('boolean option combos (--foo and --no-foo)', () => {8// boolean option combo with no default9describe('boolean option combo with no default', () => {10 function createPepperProgram() {11 const program = new commander.Command();12 program13 .option('-p, --pepper', 'add pepper')14 .option('-P, --no-pepper', 'remove pepper');15 return program;16 }9 // boolean option combo with no default10 describe('positive option with no default', () => {11 function createPepperProgram() {12 const program = new commander.Command();13 program14 .option('-p, --pepper', 'add pepper')15 .option('-P, --no-pepper', 'remove pepper');16 return program;17 }1818 test('when boolean combo not specified then value is undefined', () => {19 const program = createPepperProgram();20 program.parse(['node', 'test']);21 assert.equal(program.opts().pepper, undefined);22 });19 test('when option not specified then value is undefined', () => {20 const program = createPepperProgram();21 program.parse(['node', 'test']);22 assert.equal(program.opts().pepper, undefined);23 });2424 test('when boolean combo positive then value is true', () => {25 const program = createPepperProgram();26 program.parse(['node', 'test', '--pepper']);27 assert.equal(program.opts().pepper, true);28 });25 test('when positive option then value is true', () => {26 const program = createPepperProgram();27 program.parse(['node', 'test', '--pepper']);28 assert.equal(program.opts().pepper, true);29 });3030 test('when boolean combo negative then value is false', () => {31 const program = createPepperProgram();32 program.parse(['node', 'test', '--no-pepper']);33 assert.equal(program.opts().pepper, false);34 });31 test('when negative option then value is false', () => {32 const program = createPepperProgram();33 program.parse(['node', 'test', '--no-pepper']);34 assert.equal(program.opts().pepper, false);35 });3636 test('when boolean combo last is positive then value is true', () => {37 const program = createPepperProgram();38 program.parse(['node', 'test', '--no-pepper', '--pepper']);39 assert.equal(program.opts().pepper, true);40 });37 test('when last option is positive then value is true', () => {38 const program = createPepperProgram();39 program.parse(['node', 'test', '--no-pepper', '--pepper']);40 assert.equal(program.opts().pepper, true);41 });4242 test('when boolean combo last is negative then value is false', () => {43 const program = createPepperProgram();44 program.parse(['node', 'test', '--pepper', '--no-pepper']);45 assert.equal(program.opts().pepper, false);43 test('when last option is negative then value is false', () => {44 const program = createPepperProgram();45 program.parse(['node', 'test', '--pepper', '--no-pepper']);46 assert.equal(program.opts().pepper, false);47 });48 });47});4949// Flag with default, say from an environment variable.50 // Flag with default, say from an environment variable.5151function createPepperProgramWithDefault(defaultValue) {52 const program = new commander.Command();53 program54 .option('-p, --pepper', 'add pepper', defaultValue)55 .option('-P, --no-pepper', 'remove pepper');56 return program;57}52 function createPepperProgramWithDefault(defaultValue) {53 const program = new commander.Command();54 program55 .option('-p, --pepper', 'add pepper', defaultValue)56 .option('-P, --no-pepper', 'remove pepper');57 return program;58 }5959// boolean option combo, default true, long flags60describe('boolean option combo, default true, long flags', () => {61 test('when boolean combo not specified then value is true', () => {62 const program = createPepperProgramWithDefault(true);63 program.parse(['node', 'test']);64 assert.equal(program.opts().pepper, true);65 });60 // boolean option combo, default true, long flags61 describe('option with default of true, long flags', () => {62 test('when option not specified then value is true', () => {63 const program = createPepperProgramWithDefault(true);64 program.parse(['node', 'test']);65 assert.equal(program.opts().pepper, true);66 });6767 test('when boolean combo positive then value is true', () => {68 const program = createPepperProgramWithDefault(true);69 program.parse(['node', 'test', '--pepper']);70 assert.equal(program.opts().pepper, true);71 });68 test('when positive option then value is true', () => {69 const program = createPepperProgramWithDefault(true);70 program.parse(['node', 'test', '--pepper']);71 assert.equal(program.opts().pepper, true);72 });7373 test('when boolean combo negative then value is false', () => {74 const program = createPepperProgramWithDefault(true);75 program.parse(['node', 'test', '--no-pepper']);76 assert.equal(program.opts().pepper, false);74 test('when negative option then value is false', () => {75 const program = createPepperProgramWithDefault(true);76 program.parse(['node', 'test', '--no-pepper']);77 assert.equal(program.opts().pepper, false);78 });79 });78});8080// boolean option combo, default false, short flags81describe('boolean option combo, default false, short flags', () => {82 test('when boolean combo not specified then value is false', () => {83 const program = createPepperProgramWithDefault(false);84 program.parse(['node', 'test']);85 assert.equal(program.opts().pepper, false);86 });81 // boolean option combo, default false, short flags82 describe('option with default of false, short flags', () => {83 test('when option not specified then value is false', () => {84 const program = createPepperProgramWithDefault(false);85 program.parse(['node', 'test']);86 assert.equal(program.opts().pepper, false);87 });8888 test('when boolean combo positive then value is true', () => {89 const program = createPepperProgramWithDefault(false);90 program.parse(['node', 'test', '-p']);91 assert.equal(program.opts().pepper, true);92 });89 test('when positive option then value is true', () => {90 const program = createPepperProgramWithDefault(false);91 program.parse(['node', 'test', '-p']);92 assert.equal(program.opts().pepper, true);93 });9494 test('when boolean combo negative then value is false', () => {95 const program = createPepperProgramWithDefault(false);96 program.parse(['node', 'test', '-P']);97 assert.equal(program.opts().pepper, false);95 test('when negative option then value is false', () => {96 const program = createPepperProgramWithDefault(false);97 program.parse(['node', 'test', '-P']);98 assert.equal(program.opts().pepper, false);99 });100 });99});101101// boolean option combo with non-boolean default.102// Changed behaviour to normal default in Commander 9.103describe('boolean option combo with non-boolean default', () => {104 test('when boolean combo not specified then value is default', () => {105 const program = createPepperProgramWithDefault('default');106 program.parse(['node', 'test']);107 assert.equal(program.opts().pepper, 'default');108 });102 // boolean option combo with non-boolean default.103 // Changed behaviour to normal default in Commander 9.104 describe('option with non-boolean default', () => {105 test('when option not specified then value is default', () => {106 const program = createPepperProgramWithDefault('default');107 program.parse(['node', 'test']);108 assert.equal(program.opts().pepper, 'default');109 });110110 test('when boolean combo positive then value is true', () => {111 const program = createPepperProgramWithDefault('default');112 program.parse(['node', 'test', '--pepper']);113 assert.equal(program.opts().pepper, true);114 });111 test('when positive option then value is true', () => {112 const program = createPepperProgramWithDefault('default');113 program.parse(['node', 'test', '--pepper']);114 assert.equal(program.opts().pepper, true);115 });116116 test('when boolean combo negative then value is false', () => {117 const program = createPepperProgramWithDefault('default');118 program.parse(['node', 'test', '--no-pepper']);119 assert.equal(program.opts().pepper, false);117 test('when negative option then value is false', () => {118 const program = createPepperProgramWithDefault('default');119 program.parse(['node', 'test', '--no-pepper']);120 assert.equal(program.opts().pepper, false);121 });122 });121});123123describe('boolean option combo with non-boolean default and preset', () => {124 function createPepperProgramWithDefaultAndPreset() {125 const program = new commander.Command();126 program127 .addOption(128 new commander.Option('-p, --pepper')129 .default('default')130 .preset('preset'),131 )132 .option('-P, --no-pepper', 'remove pepper');133 return program;134 }124 describe('option with non-boolean default and preset', () => {125 function createPepperProgramWithDefaultAndPreset() {126 const program = new commander.Command();127 program128 .addOption(129 new commander.Option('-p, --pepper')130 .default('default')131 .preset('preset'),132 )133 .option('-P, --no-pepper', 'remove pepper');134 return program;135 }136136 test('when boolean combo not specified then value is default', () => {137 const program = createPepperProgramWithDefaultAndPreset();138 program.parse(['node', 'test']);139 assert.equal(program.opts().pepper, 'default');140 });137 test('when option not specified then value is default', () => {138 const program = createPepperProgramWithDefaultAndPreset();139 program.parse(['node', 'test']);140 assert.equal(program.opts().pepper, 'default');141 });142142 test('when boolean combo positive then value is preset', () => {143 const program = createPepperProgramWithDefaultAndPreset();144 program.parse(['node', 'test', '--pepper']);145 assert.equal(program.opts().pepper, 'preset');146 });143 test('when positive option then value is preset', () => {144 const program = createPepperProgramWithDefaultAndPreset();145 program.parse(['node', 'test', '--pepper']);146 assert.equal(program.opts().pepper, 'preset');147 });148148 test('when boolean combo negative then value is false', () => {149 const program = createPepperProgramWithDefaultAndPreset();150 program.parse(['node', 'test', '--no-pepper']);151 assert.equal(program.opts().pepper, false);149 test('when negative option then value is false', () => {150 const program = createPepperProgramWithDefaultAndPreset();151 program.parse(['node', 'test', '--no-pepper']);152 assert.equal(program.opts().pepper, false);153 });154 });153});155155describe('only lone negative causes implicit default of true', () => {156 test('when lone negative then default value is true', () => {157 const program = new commander.Command();158 program.option('--no-pepper', 'remove pepper');159 program.parse([], { from: 'user' });160 assert.equal(program.opts().pepper, true);161 });156 describe('only lone negative causes implicit default of true', () => {157 test('when lone negative then default value is true', () => {158 const program = new commander.Command();159 program.option('--no-pepper', 'remove pepper');160 program.parse([], { from: 'user' });161 assert.equal(program.opts().pepper, true);162 });163163 test('when boolean combo and negative first then no implicit default', () => {164 // New behaviour in Commander 15, now only lone negative gets implicit default of true.165 const program = new commander.Command();166 program167 .option('--no-pepper', 'remove pepper')168 .option('--pepper', 'pepper only');169 program.parse([], { from: 'user' });170 assert.equal(program.opts().pepper, undefined);171 });164 test('when boolean combo and negative first then no implicit default', () => {165 // New behaviour in Commander 15, now only lone negative gets implicit default of true.166 const program = new commander.Command();167 program168 .option('--no-pepper', 'remove pepper')169 .option('--pepper', 'pepper only');170 program.parse([], { from: 'user' });171 assert.equal(program.opts().pepper, undefined);172 });173173 test('when boolean combo and negative second then no implicit default', () => {174 const program = new commander.Command();175 program176 .option('--pepper', 'pepper only')177 .option('--no-pepper', 'remove pepper');178 program.parse([], { from: 'user' });179 assert.equal(program.opts().pepper, undefined);180 });174 test('when boolean combo and negative second then no implicit default', () => {175 const program = new commander.Command();176 program177 .option('--pepper', 'pepper only')178 .option('--no-pepper', 'remove pepper');179 program.parse([], { from: 'user' });180 assert.equal(program.opts().pepper, undefined);181 });182182 test('when boolean combo and negative second with explicit default then get explicit default', () => {183 // Prior to Commander 15, negative second would ignore implicit and explicit default value.184 // Simpler rule now and the special default behaviour is for lone negative only. Add test since185 // intentional change of behaviour for unlikely edge case.186 const program = new commander.Command();187 program188 .option('--pepper', 'pepper only')189 .option('--no-pepper', 'remove pepper', 'plain');190 program.parse([], { from: 'user' });191 assert.equal(program.opts().pepper, 'plain');183 test('when boolean combo and negative second with explicit default then get explicit default', () => {184 // Prior to Commander 15, negative second would ignore implicit and explicit default value.185 // Simpler rule now and the special default behaviour is for lone negative only. Add test since186 // intentional change of behaviour for unlikely edge case.187 const program = new commander.Command();188 program189 .option('--pepper', 'pepper only')190 .option('--no-pepper', 'remove pepper', 'plain');191 program.parse([], { from: 'user' });192 assert.equal(program.opts().pepper, 'plain');193 });194 });195});
modified:tests/options.bool.small.combined.test.js+1 added-1 removed
1const commander = require('../');2const { test } = require('node:test');3const assert = require('node:assert/strict');45test('when when multiple short flags specified then all values are true', () => {5test('when when multiple short flags specified then parsed as short option group', () => {6 const program = new commander.Command();7 program8 .option('-p, --pepper', 'add pepper')9 .option('-c, --cheese', 'add cheese');
6 unmodified lines
modified:tests/options.bool.test.js+17 added-18 removed
2 unmodified lines
3const assert = require('node:assert/strict');45// Test simple flag and negatable flag67// boolean flag on program8describe('boolean flag on program', () => {9 test('when boolean flag not specified then value is undefined', () => {7// boolean option on program8describe('boolean option on program', () => {9 test('when boolean option not specified then value is undefined', () => {10 const program = new commander.Command();11 program.option('--pepper', 'add pepper');12 program.parse(['node', 'test']);13 assert.equal(program.opts().pepper, undefined);14 });1516 test('when boolean flag specified then value is true', () => {16 test('when boolean option specified then value is true', () => {17 const program = new commander.Command();18 program.option('--pepper', 'add pepper');19 program.parse(['node', 'test', '--pepper']);20 assert.equal(program.opts().pepper, true);21 });2223 test('when negatable boolean flag not specified then value is true', () => {23 test('when negatable boolean option not specified then value is true', () => {24 const program = new commander.Command();25 program.option('--no-cheese', 'remove cheese');26 program.parse(['node', 'test']);27 assert.equal(program.opts().cheese, true);28 });2930 test('when negatable boolean flag specified then value is false', () => {30 test('when negatable boolean option specified then value is false', () => {31 const program = new commander.Command();32 program.option('--no-cheese', 'remove cheese');33 program.parse(['node', 'test', '--no-cheese']);34 assert.equal(program.opts().cheese, false);35 });36});3738// boolean flag on command39describe('boolean flag on command', () => {40 test('when boolean flag not specified then value is undefined', () => {38describe('boolean option on subcommand', () => {39 test('when boolean option not specified then value is undefined', () => {40 let subCommandOptions;41 const program = new commander.Command();42 program43 .command('sub')
4 unmodified lines
48 program.parse(['node', 'test', 'sub']);49 assert.equal(subCommandOptions.pepper, undefined);50 });5153 test('when boolean flag specified then value is true', () => {52 test('when boolean option specified then value is true', () => {53 let subCommandOptions;54 const program = new commander.Command();55 program56 .command('sub')
4 unmodified lines
61 program.parse(['node', 'test', 'sub', '--pepper']);62 assert.equal(subCommandOptions.pepper, true);63 });6466 test('when negatable boolean flag not specified then value is true', () => {65 test('when negatable boolean option not specified then value is true', () => {66 let subCommandOptions;67 const program = new commander.Command();68 program69 .command('sub')
4 unmodified lines
74 program.parse(['node', 'test', 'sub']);75 assert.equal(subCommandOptions.cheese, true);76 });7779 test('when negatable boolean flag specified then value is false', () => {78 test('when negatable boolean option specified then value is false', () => {79 let subCommandOptions;80 const program = new commander.Command();81 program82 .command('sub')
8 unmodified lines
9192// boolean flag with non-boolean default93// NB: behaviour changed in Commander v9 to have default be default.94// These tests no longer match likely uses, but retained and updated to match current behaviour.96describe('boolean flag with non-boolean default', () => {97 test('when flag not specified then value is "default"', () => {95describe('boolean option with non-boolean default', () => {96 test('when option not specified then value is "default"', () => {97 const flagValue = 'black';98 const program = new commander.Command();99 program.option('--olives', 'Add green olives?', flagValue);100 program.parse(['node', 'test']);101 assert.equal(program.opts().olives, flagValue);102 });103105 test('when flag specified then value is true', () => {104 test('when option specified then value is true', () => {105 const flagValue = 'black';106 const program = new commander.Command();107 program.option('-v, --olives', 'Add green olives?', flagValue);108 program.parse(['node', 'test', '--olives']);109 assert.equal(program.opts().olives, true);110 });111113 test('when combo flag and negated then value is false', () => {112 test('when combo option and negated then value is false', () => {113 const flagValue = 'black';114 const program = new commander.Command();115 program116 .option('-v, --olives', 'Add green olives?', flagValue)
3 unmodified lines
120 });121});122123// Regression test for #1301 with `-no-` in middle of option125describe('regression test for -no- in middle of option flag', () => {126 test('when flag not specified then value is undefined', () => {124describe('regression test for -no- in middle of option name', () => {125 test('when option not specified then value is undefined', () => {126 const program = new commander.Command();127 program.option('--module-no-parse');128 program.parse(['node', 'test']);129 assert.equal(program.opts().moduleNoParse, undefined);
9 unmodified lines
modified:tests/options.camelcase.test.js+38 added-36 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45// Capitalise the letters of words after dashes, but otherwise preserve case67describe('option property is camelCase of option name', () => {7test('when option defined with --word-word then option property is wordWord', () => {8 const program = new commander.Command();9 program.option('--my-option', 'description');10 program.parse(['node', 'test', '--my-option']);11 assert.equal(program.opts().myOption, true);12});8 test('when option defined with --word-word then option property is wordWord', () => {9 const program = new commander.Command();10 program.option('--my-option', 'description');11 program.parse(['node', 'test', '--my-option']);12 assert.equal(program.opts().myOption, true);13 });1414test('when option defined with --word-wORD then option property is wordWORD', () => {15 const program = new commander.Command();16 program.option('--my-oPTION', 'description');17 program.parse(['node', 'test', '--my-oPTION']);18 assert.equal(program.opts().myOPTION, true);19});15 test('when option defined with --word-wORD then option property is wordWORD', () => {16 const program = new commander.Command();17 program.option('--my-oPTION', 'description');18 program.parse(['node', 'test', '--my-oPTION']);19 assert.equal(program.opts().myOPTION, true);20 });2121test('when option defined with --word-WORD then option property is wordWORD', () => {22 const program = new commander.Command();23 program.option('--my-OPTION', 'description');24 program.parse(['node', 'test', '--my-OPTION']);25 assert.equal(program.opts().myOPTION, true);26});22 test('when option defined with --word-WORD then option property is wordWORD', () => {23 const program = new commander.Command();24 program.option('--my-OPTION', 'description');25 program.parse(['node', 'test', '--my-OPTION']);26 assert.equal(program.opts().myOPTION, true);27 });2828test('when option defined with --word-word-word then option property is wordWordWord', () => {29 const program = new commander.Command();30 program.option('--my-special-option', 'description');31 program.parse(['node', 'test', '--my-special-option']);32 assert.equal(program.opts().mySpecialOption, true);33});29 test('when option defined with --word-word-word then option property is wordWordWord', () => {30 const program = new commander.Command();31 program.option('--my-special-option', 'description');32 program.parse(['node', 'test', '--my-special-option']);33 assert.equal(program.opts().mySpecialOption, true);34 });3535test('when option defined with --word-WORD-word then option property is wordWORDWord', () => {36 const program = new commander.Command();37 program.option('--my-SPECIAL-option', 'description');38 program.parse(['node', 'test', '--my-SPECIAL-option']);39 assert.equal(program.opts().mySPECIALOption, true);40});36 test('when option defined with --word-WORD-word then option property is wordWORDWord', () => {37 const program = new commander.Command();38 program.option('--my-SPECIAL-option', 'description');39 program.parse(['node', 'test', '--my-SPECIAL-option']);40 assert.equal(program.opts().mySPECIALOption, true);41 });4242test('when option defined with --Word then option property is Word', () => {43 const program = new commander.Command();44 program.option('--Myoption', 'description');45 program.parse(['node', 'test', '--Myoption']);46 assert.equal(program.opts().Myoption, true);43 test('when option defined with --Word then option property is Word', () => {44 const program = new commander.Command();45 program.option('--Myoption', 'description');46 program.parse(['node', 'test', '--Myoption']);47 assert.equal(program.opts().Myoption, true);48 });49});
modified:tests/options.choices.test.js+43 added-39 removed
1 unmodified line
2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56test('when option argument in choices then option set', () => {7 const program = new commander.Command();8 program.addOption(9 new commander.Option('--colour <shade>').choices(['red', 'blue']),10 );11 program.parse(['--colour', 'red'], { from: 'user' });12 assert.equal(program.opts().colour, 'red');13});1415test('when option argument is not in choices then error', () => {16 // Lightweight check, more detailed testing of behaviour in command.exitOverride.test.js17 const program = createTestCommand();18 program.addOption(19 new commander.Option('--colour <shade>').choices(['red', 'blue']),20 );21 assert.throws(() => {22 program.parse(['--colour', 'orange'], { from: 'user' });6describe('Option.choices()', () => {7 test('when option argument in choices then option set', () => {8 const program = new commander.Command();9 program.addOption(10 new commander.Option('--colour <shade>').choices(['red', 'blue']),11 );12 program.parse(['--colour', 'red'], { from: 'user' });13 assert.equal(program.opts().colour, 'red');14 });24});1526describe('choices parameter is treated as readonly, per TypeScript declaration', () => {27 test('when choices called then parameter does not change', () => {28 // Unlikely this could break, but check the API we are declaring in TypeScript.29 const original = ['red', 'blue', 'green'];30 const param = original.slice();31 new commander.Option('--colour <shade>').choices(param);32 assert.deepEqual(param, original);33 });3435 test('when choices called and argChoices later changed then parameter does not change', () => {36 const original = ['red', 'blue', 'green'];37 const param = original.slice();38 const option = new commander.Option('--colour <shade>').choices(param);39 option.argChoices.push('purple');40 assert.deepEqual(param, original);41 });4243 test('when choices called and parameter changed the choices does not change', () => {16 test('when option argument is not in choices then error', () => {17 // Lightweight check, more detailed testing of behaviour in command.exitOverride.test.js18 const program = createTestCommand();45 const param = ['red', 'blue'];46 program.addOption(new commander.Option('--colour <shade>').choices(param));47 param.push('orange');19 program.addOption(20 new commander.Option('--colour <shade>').choices(['red', 'blue']),21 );22 assert.throws(() => {23 program.parse(['--colour', 'orange'], { from: 'user' });24 });25 });2627 describe('choices parameter is treated as readonly, per TypeScript declaration', () => {28 test('when choices called then parameter does not change', () => {29 // Unlikely this could break, but check the API we are declaring in TypeScript.30 const original = ['red', 'blue', 'green'];31 const param = original.slice();32 new commander.Option('--colour <shade>').choices(param);33 assert.deepEqual(param, original);34 });3536 test('when choices called and argChoices later changed then parameter does not change', () => {37 const original = ['red', 'blue', 'green'];38 const param = original.slice();39 const option = new commander.Option('--colour <shade>').choices(param);40 option.argChoices.push('purple');41 assert.deepEqual(param, original);42 });4344 test('when choices called and parameter changed the choices does not change', () => {45 const program = createTestCommand();46 const param = ['red', 'blue'];47 program.addOption(48 new commander.Option('--colour <shade>').choices(param),49 );50 param.push('orange');51 assert.throws(() => {52 program.parse(['--colour', 'orange'], { from: 'user' });53 });54 });55 });56});
modified:tests/options.conflicts.test.js+1 added-1 removed
2 unmodified lines
3const { createTestCommand } = require('./testHelpers');4const { test, describe } = require('node:test');5const assert = require('node:assert/strict');67describe('command with conflicting options', () => {7describe('Option.conflicts()', () => {8 function makeProgram(t) {9 const actionMock = t.mock.fn();10 const program = createTestCommand();11 program
384 unmodified lines
modified:tests/options.custom-processing.test.js+107 added-105 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45function myParseInt(value, dummyPrevious) {6 // parseInt takes a string and a radix
11 unmodified lines
18function commaSeparatedList(value, dummyPrevious) {19 return value.split(',');20}2122describe('custom processing function for option', () => {22test('when option not specified then callback not called', (t) => {23 const mockCoercion = t.mock.fn();24 const program = new commander.Command();25 program.option('-i, --integer <n>', 'number', mockCoercion);26 program.parse(['node', 'test']);27 assert.equal(mockCoercion.mock.callCount(), 0);28});23 test('when option not specified then callback not called', (t) => {24 const mockCoercion = t.mock.fn();25 const program = new commander.Command();26 program.option('-i, --integer <n>', 'number', mockCoercion);27 program.parse(['node', 'test']);28 assert.equal(mockCoercion.mock.callCount(), 0);29 });3030test('when option not specified then value is undefined', () => {31 const program = new commander.Command();32 program.option('-i, --integer <n>', 'number', myParseInt);33 program.parse(['node', 'test']);34 assert.equal(program.opts().integer, undefined);35});31 test('when option not specified then value is undefined', () => {32 const program = new commander.Command();33 program.option('-i, --integer <n>', 'number', myParseInt);34 program.parse(['node', 'test']);35 assert.equal(program.opts().integer, undefined);36 });3737test('when starting value is defined and option not specified then callback not called', (t) => {38 const mockCoercion = t.mock.fn();39 const program = new commander.Command();40 program.option('-i, --integer <n>', 'number', mockCoercion, 1);41 program.parse(['node', 'test']);42 assert.equal(mockCoercion.mock.callCount(), 0);43});38 test('when starting value is defined and option not specified then callback not called', (t) => {39 const mockCoercion = t.mock.fn();40 const program = new commander.Command();41 program.option('-i, --integer <n>', 'number', mockCoercion, 1);42 program.parse(['node', 'test']);43 assert.equal(mockCoercion.mock.callCount(), 0);44 });4545test('when starting value is defined and option not specified then value is starting value', () => {46 // NB: Can not specify a starting value for a boolean flag! Discovered when writing this test...47 const startingValue = 1;48 const program = new commander.Command();49 program.option('-i, --integer <n>', 'number', myParseInt, startingValue);50 program.parse(['node', 'test']);51 assert.equal(program.opts().integer, startingValue);52});46 test('when starting value is defined and option not specified then value is starting value', () => {47 // NB: Can not specify a starting value for a boolean flag! Discovered when writing this test...48 const startingValue = 1;49 const program = new commander.Command();50 program.option('-i, --integer <n>', 'number', myParseInt, startingValue);51 program.parse(['node', 'test']);52 assert.equal(program.opts().integer, startingValue);53 });5454test('when option specified then callback called with value and previous', (t) => {55 const mockCoercion = t.mock.fn();56 const value = '1';57 const program = new commander.Command();58 program.option('-i, --integer <n>', 'number', mockCoercion);59 program.parse(['node', 'test', '-i', value]);60 assert.deepEqual(mockCoercion.mock.calls[0].arguments, [value, undefined]);61});55 test('when option specified then callback called with value and previous', (t) => {56 const mockCoercion = t.mock.fn();57 const value = '1';58 const program = new commander.Command();59 program.option('-i, --integer <n>', 'number', mockCoercion);60 program.parse(['node', 'test', '-i', value]);61 assert.deepEqual(mockCoercion.mock.calls[0].arguments, [value, undefined]);62 });6363test('when option specified then value is as returned from callback', () => {64 const callbackResult = 2;65 const program = new commander.Command();66 program.option('-i, --integer <n>', 'number', () => {67 return callbackResult;64 test('when option specified then value is as returned from callback', () => {65 const callbackResult = 2;66 const program = new commander.Command();67 program.option('-i, --integer <n>', 'number', () => {68 return callbackResult;69 });70 program.parse(['node', 'test', '-i', '0']);71 assert.equal(program.opts().integer, callbackResult);72 });69 program.parse(['node', 'test', '-i', '0']);70 assert.equal(program.opts().integer, callbackResult);71});7373test('when starting value is defined and option specified then callback called with value and starting value', (t) => {74 const mockCoercion = t.mock.fn();75 const startingValue = 1;76 const value = '2';77 const program = new commander.Command();78 program.option('-i, --integer <n>', 'number', mockCoercion, startingValue);79 program.parse(['node', 'test', '-i', value]);80 assert.deepEqual(mockCoercion.mock.calls[0].arguments, [81 value,82 startingValue,83 ]);84});74 test('when starting value is defined and option specified then callback called with value and starting value', (t) => {75 const mockCoercion = t.mock.fn();76 const startingValue = 1;77 const value = '2';78 const program = new commander.Command();79 program.option('-i, --integer <n>', 'number', mockCoercion, startingValue);80 program.parse(['node', 'test', '-i', value]);81 assert.deepEqual(mockCoercion.mock.calls[0].arguments, [82 value,83 startingValue,84 ]);85 });8686test('when option specified multiple times then callback called with value and previousValue', (t) => {87 const mockCoercion = t.mock.fn(() => 'callback');88 const program = new commander.Command();89 program.option('-i, --integer <n>', 'number', mockCoercion);90 program.parse(['node', 'test', '-i', '1', '-i', '2']);91 assert.equal(mockCoercion.mock.callCount(), 2);92 assert.deepEqual(mockCoercion.mock.calls[0].arguments, ['1', undefined]);93 assert.deepEqual(mockCoercion.mock.calls[1].arguments, ['2', 'callback']);94});87 test('when option specified multiple times then callback called with value and previousValue', (t) => {88 const mockCoercion = t.mock.fn(() => 'callback');89 const program = new commander.Command();90 program.option('-i, --integer <n>', 'number', mockCoercion);91 program.parse(['node', 'test', '-i', '1', '-i', '2']);92 assert.equal(mockCoercion.mock.callCount(), 2);93 assert.deepEqual(mockCoercion.mock.calls[0].arguments, ['1', undefined]);94 assert.deepEqual(mockCoercion.mock.calls[1].arguments, ['2', 'callback']);95 });9696// Now some functional tests like the examples in the README!97 // Now some functional tests like the examples in the README!9898test('when parseFloat "1e2" then value is 100', () => {99 const program = new commander.Command();100 program.option('-f, --float <number>', 'float argument', parseFloat);101 program.parse(['node', 'test', '-f', '1e2']);102 assert.equal(program.opts().float, 100);103});99 test('when parseFloat "1e2" then value is 100', () => {100 const program = new commander.Command();101 program.option('-f, --float <number>', 'float argument', parseFloat);102 program.parse(['node', 'test', '-f', '1e2']);103 assert.equal(program.opts().float, 100);104 });105105test('when myParseInt "1" then value is 1', () => {106 const program = new commander.Command();107 program.option('-i, --integer <number>', 'integer argument', myParseInt);108 program.parse(['node', 'test', '-i', '1']);109 assert.equal(program.opts().integer, 1);110});106 test('when myParseInt "1" then value is 1', () => {107 const program = new commander.Command();108 program.option('-i, --integer <number>', 'integer argument', myParseInt);109 program.parse(['node', 'test', '-i', '1']);110 assert.equal(program.opts().integer, 1);111 });112112test('when increaseVerbosity -v -v -v then value is 3', () => {113 const program = new commander.Command();114 program.option(115 '-v, --verbose',116 'verbosity that can be increased',117 increaseVerbosity,118 0,119 );120 program.parse(['node', 'test', '-v', '-v', '-v']);121 assert.equal(program.opts().verbose, 3);122});113 test('when increaseVerbosity -v -v -v then value is 3', () => {114 const program = new commander.Command();115 program.option(116 '-v, --verbose',117 'verbosity that can be increased',118 increaseVerbosity,119 0,120 );121 program.parse(['node', 'test', '-v', '-v', '-v']);122 assert.equal(program.opts().verbose, 3);123 });124124test('when collect -c a -c b -c c then value is [a, b, c]', () => {125 const program = new commander.Command();126 program.option('-c, --collect <value>', 'repeatable value', collect, []);127 program.parse(['node', 'test', '-c', 'a', '-c', 'b', '-c', 'c']);128 assert.deepEqual(program.opts().collect, ['a', 'b', 'c']);129});125 test('when collect -c a -c b -c c then value is [a, b, c]', () => {126 const program = new commander.Command();127 program.option('-c, --collect <value>', 'repeatable value', collect, []);128 program.parse(['node', 'test', '-c', 'a', '-c', 'b', '-c', 'c']);129 assert.deepEqual(program.opts().collect, ['a', 'b', 'c']);130 });131131test('when commaSeparatedList x,y,z then value is [x, y, z]', () => {132 const program = new commander.Command();133 program.option(134 '-l, --list <items>',135 'comma separated list',136 commaSeparatedList,137 );138 program.parse(['node', 'test', '--list', 'x,y,z']);139 assert.deepEqual(program.opts().list, ['x', 'y', 'z']);132 test('when commaSeparatedList x,y,z then value is [x, y, z]', () => {133 const program = new commander.Command();134 program.option(135 '-l, --list <items>',136 'comma separated list',137 commaSeparatedList,138 );139 program.parse(['node', 'test', '--list', 'x,y,z']);140 assert.deepEqual(program.opts().list, ['x', 'y', 'z']);141 });142});
modified:tests/options.default.test.js+3 added-3 removed
1const { Command, Option } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('.option() with default and option not specified in parse', () => {5describe('Command.option() with default value and option not specified in parse', () => {6 test('when boolean option with boolean default then value is default', () => {7 const program = new Command();8 program.option('-d, --debug', 'description', false);9 program.parse([], { from: 'user' });
50 unmodified lines
60 assert.equal(program.opts().colour, 'RGB');61 });62});6364describe('Option with default and option not specified in parse', () => {64describe('Option with default value and option not specified in parse', () => {65 test('when boolean option with boolean default then value is default', () => {66 const program = new Command();67 program.addOption(new Option('-d, --debug').default(false));68 program.parse([], { from: 'user' });
51 unmodified lines
120 });121});122123// Fairly obvious this needs to happen, but was broken for optional in past!124describe('default overwritten by specified option', () => {124describe('option default value overwritten by option specified in parse', () => {125 test('when boolean option with boolean default then value is true', () => {126 const program = new Command();127 program.option('-d, --debug', 'description', false);128 program.parse(['-d'], { from: 'user' });
67 unmodified lines
modified:tests/options.dual-options.test.js+75 added-73 removed
3 unmodified lines
4const assert = require('node:assert/strict');56// This tests an internal helper class which is not currently exposed on the package.78describe('DualOptions internal helper class', () => {8test('when positive option then stored in positiveOptions', () => {9 const program = new Command();10 program.option('--one');11 const helper = new DualOptions(program.options);12 assert.equal(helper.positiveOptions.size, 1);13 assert.equal(helper.negativeOptions.size, 0);14 assert.equal(helper.dualOptions.size, 0);15});9 test('when positive option then stored in positiveOptions', () => {10 const program = new Command();11 program.option('--one');12 const helper = new DualOptions(program.options);13 assert.equal(helper.positiveOptions.size, 1);14 assert.equal(helper.negativeOptions.size, 0);15 assert.equal(helper.dualOptions.size, 0);16 });1717test('when negative option then stored in negativeOptions', () => {18 const program = new Command();19 program.option('--no-one');20 const helper = new DualOptions(program.options);21 assert.equal(helper.positiveOptions.size, 0);22 assert.equal(helper.negativeOptions.size, 1);23 assert.equal(helper.dualOptions.size, 0);24});18 test('when negative option then stored in negativeOptions', () => {19 const program = new Command();20 program.option('--no-one');21 const helper = new DualOptions(program.options);22 assert.equal(helper.positiveOptions.size, 0);23 assert.equal(helper.negativeOptions.size, 1);24 assert.equal(helper.dualOptions.size, 0);25 });2626test('when unrelated positive and negative options then no dual options', () => {27 const program = new Command();28 program.option('--one').option('--no-two');29 const helper = new DualOptions(program.options);30 assert.equal(helper.dualOptions.size, 0);31});27 test('when unrelated positive and negative options then no dual options', () => {28 const program = new Command();29 program.option('--one').option('--no-two');30 const helper = new DualOptions(program.options);31 assert.equal(helper.dualOptions.size, 0);32 });3333test('when related positive and negative options then stored as dual option', () => {34 const program = new Command();35 program.option('--one').option('--no-one');36 const helper = new DualOptions(program.options);37 assert.equal(helper.dualOptions.size, 1);38});34 test('when related positive and negative options then stored as dual option', () => {35 const program = new Command();36 program.option('--one').option('--no-one');37 const helper = new DualOptions(program.options);38 assert.equal(helper.dualOptions.size, 1);39 });4040test('when related negative and positive options then stored as dual option', () => {41 const program = new Command();42 program.option('--no-one').option('--one');43 const helper = new DualOptions(program.options);44 assert.equal(helper.dualOptions.size, 1);45});41 test('when related negative and positive options then stored as dual option', () => {42 const program = new Command();43 program.option('--no-one').option('--one');44 const helper = new DualOptions(program.options);45 assert.equal(helper.dualOptions.size, 1);46 });4747describe('valueFromOption with boolean option', () => {48 const positiveOption = new Option('--one');49 const negativeOption = new Option('--no-one');50 const options = [positiveOption, negativeOption];48 describe('valueFromOption with boolean option', () => {49 const positiveOption = new Option('--one');50 const negativeOption = new Option('--no-one');51 const options = [positiveOption, negativeOption];5252 test('when negativeOption with false then return true', () => {53 const helper = new DualOptions(options);54 assert.equal(helper.valueFromOption(false, negativeOption), true);55 });53 test('when negativeOption with false then return true', () => {54 const helper = new DualOptions(options);55 assert.equal(helper.valueFromOption(false, negativeOption), true);56 });5757 test('when negativeOption with true then return false', () => {58 const helper = new DualOptions(options);59 assert.equal(helper.valueFromOption(true, negativeOption), false);60 });58 test('when negativeOption with true then return false', () => {59 const helper = new DualOptions(options);60 assert.equal(helper.valueFromOption(true, negativeOption), false);61 });6262 test('when positiveOption with false then return false', () => {63 const helper = new DualOptions(options);64 assert.equal(helper.valueFromOption(false, positiveOption), false);65 });63 test('when positiveOption with false then return false', () => {64 const helper = new DualOptions(options);65 assert.equal(helper.valueFromOption(false, positiveOption), false);66 });6767 test('when positiveOption with true then return true', () => {68 const helper = new DualOptions(options);69 assert.equal(helper.valueFromOption(true, positiveOption), true);68 test('when positiveOption with true then return true', () => {69 const helper = new DualOptions(options);70 assert.equal(helper.valueFromOption(true, positiveOption), true);71 });72 });71});7373describe('valueFromOption with option expecting value and negative with preset', () => {74 const positiveOption = new Option('--one <value>');75 const negativeOption = new Option('--no-one').preset('FALSE');76 const options = [positiveOption, negativeOption];74 describe('valueFromOption with option expecting value and negative with preset', () => {75 const positiveOption = new Option('--one <value>');76 const negativeOption = new Option('--no-one').preset('FALSE');77 const options = [positiveOption, negativeOption];7878 test('when negativeOption with FALSE then return true', () => {79 const helper = new DualOptions(options);80 assert.equal(helper.valueFromOption('FALSE', negativeOption), true);81 });79 test('when negativeOption with FALSE then return true', () => {80 const helper = new DualOptions(options);81 assert.equal(helper.valueFromOption('FALSE', negativeOption), true);82 });8383 test('when negativeOption with string then return false', () => {84 const helper = new DualOptions(options);85 assert.equal(helper.valueFromOption('foo', negativeOption), false);86 });84 test('when negativeOption with string then return false', () => {85 const helper = new DualOptions(options);86 assert.equal(helper.valueFromOption('foo', negativeOption), false);87 });8888 test('when positiveOption with FALSE then return false', () => {89 const helper = new DualOptions(options);90 assert.equal(helper.valueFromOption('FALSE', positiveOption), false);91 });89 test('when positiveOption with FALSE then return false', () => {90 const helper = new DualOptions(options);91 assert.equal(helper.valueFromOption('FALSE', positiveOption), false);92 });9393 test('when positiveOption with true then return true', () => {94 const helper = new DualOptions(options);95 assert.equal(helper.valueFromOption('foo', positiveOption), true);94 test('when positiveOption with true then return true', () => {95 const helper = new DualOptions(options);96 assert.equal(helper.valueFromOption('foo', positiveOption), true);97 });98 });99});
modified:tests/options.env.test.js+327 added-319 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Option.env()', () => {5// treating optional same as required, treat as option taking value rather than as boolean6describe('option declared with value', () => {7 const flagsList = ['-f, --foo <required-arg>', '-f, --foo [optional-arg]'];8 for (const fooFlags of flagsList) {9 describe(`option declared as: ${fooFlags}`, () => {10 test('when env undefined and no cli then option undefined', () => {11 const program = new commander.Command();12 program.addOption(new commander.Option(fooFlags).env('BAR'));13 program.parse([], { from: 'user' });14 assert.equal(program.opts().foo, undefined);15 });6 // treating optional same as required, treat as option taking value rather than as boolean7 describe('option declared with value', () => {8 const flagsList = ['-f, --foo <required-arg>', '-f, --foo [optional-arg]'];9 for (const fooFlags of flagsList) {10 describe(`option declared as: ${fooFlags}`, () => {11 test('when env undefined and no cli then option undefined', () => {12 const program = new commander.Command();13 program.addOption(new commander.Option(fooFlags).env('BAR'));14 program.parse([], { from: 'user' });15 assert.equal(program.opts().foo, undefined);16 });1717 test('when env defined and no cli then option from env', () => {18 const program = new commander.Command();19 process.env.BAR = 'env';20 program.addOption(new commander.Option(fooFlags).env('BAR'));21 program.parse([], { from: 'user' });22 assert.equal(program.opts().foo, 'env');23 delete process.env.BAR;24 });18 test('when env defined and no cli then option from env', () => {19 const program = new commander.Command();20 process.env.BAR = 'env';21 program.addOption(new commander.Option(fooFlags).env('BAR'));22 program.parse([], { from: 'user' });23 assert.equal(program.opts().foo, 'env');24 delete process.env.BAR;25 });2626 test('when env defined and cli then option from cli', () => {27 const program = new commander.Command();28 process.env.BAR = 'env';29 program.addOption(new commander.Option(fooFlags).env('BAR'));30 program.parse(['--foo', 'cli'], { from: 'user' });31 assert.equal(program.opts().foo, 'cli');32 delete process.env.BAR;33 });27 test('when env defined and cli then option from cli', () => {28 const program = new commander.Command();29 process.env.BAR = 'env';30 program.addOption(new commander.Option(fooFlags).env('BAR'));31 program.parse(['--foo', 'cli'], { from: 'user' });32 assert.equal(program.opts().foo, 'cli');33 delete process.env.BAR;34 });3535 test('when env defined and value source is config then option from env', () => {36 const program = new commander.Command();37 process.env.BAR = 'env';38 program.addOption(new commander.Option(fooFlags).env('BAR'));39 program.setOptionValueWithSource('foo', 'config', 'config');40 program.parse([], { from: 'user' });41 assert.equal(program.opts().foo, 'env');42 delete process.env.BAR;43 });36 test('when env defined and value source is config then option from env', () => {37 const program = new commander.Command();38 process.env.BAR = 'env';39 program.addOption(new commander.Option(fooFlags).env('BAR'));40 program.setOptionValueWithSource('foo', 'config', 'config');41 program.parse([], { from: 'user' });42 assert.equal(program.opts().foo, 'env');43 delete process.env.BAR;44 });4545 test('when env defined and value source is unspecified then option unchanged', () => {46 const program = new commander.Command();47 process.env.BAR = 'env';48 program.addOption(new commander.Option(fooFlags).env('BAR'));49 program.setOptionValue('foo', 'client');50 program.parse([], { from: 'user' });51 assert.equal(program.opts().foo, 'client');52 delete process.env.BAR;53 });46 test('when env defined and value source is unspecified then option unchanged', () => {47 const program = new commander.Command();48 process.env.BAR = 'env';49 program.addOption(new commander.Option(fooFlags).env('BAR'));50 program.setOptionValue('foo', 'client');51 program.parse([], { from: 'user' });52 assert.equal(program.opts().foo, 'client');53 delete process.env.BAR;54 });5555 test('when default and env undefined and no cli then option from default', () => {56 const program = new commander.Command();57 program.addOption(58 new commander.Option(fooFlags).env('BAR').default('default'),59 );60 program.parse([], { from: 'user' });61 assert.equal(program.opts().foo, 'default');62 });56 test('when default and env undefined and no cli then option from default', () => {57 const program = new commander.Command();58 program.addOption(59 new commander.Option(fooFlags).env('BAR').default('default'),60 );61 program.parse([], { from: 'user' });62 assert.equal(program.opts().foo, 'default');63 });6464 test('when default and env defined and no cli then option from env', () => {65 const program = new commander.Command();66 process.env.BAR = 'env';67 program.addOption(68 new commander.Option(fooFlags).env('BAR').default('default'),69 );70 program.parse([], { from: 'user' });71 assert.equal(program.opts().foo, 'env');72 delete process.env.BAR;73 });65 test('when default and env defined and no cli then option from env', () => {66 const program = new commander.Command();67 process.env.BAR = 'env';68 program.addOption(69 new commander.Option(fooFlags).env('BAR').default('default'),70 );71 program.parse([], { from: 'user' });72 assert.equal(program.opts().foo, 'env');73 delete process.env.BAR;74 });7575 test('when default and env defined and cli then option from cli', () => {76 const program = new commander.Command();77 process.env.BAR = 'env';78 program.addOption(79 new commander.Option(fooFlags).env('BAR').default('default'),80 );81 program.parse(['--foo', 'cli'], { from: 'user' });82 assert.equal(program.opts().foo, 'cli');83 delete process.env.BAR;76 test('when default and env defined and cli then option from cli', () => {77 const program = new commander.Command();78 process.env.BAR = 'env';79 program.addOption(80 new commander.Option(fooFlags).env('BAR').default('default'),81 );82 program.parse(['--foo', 'cli'], { from: 'user' });83 assert.equal(program.opts().foo, 'cli');84 delete process.env.BAR;85 });86 });87 }88 });8990 describe('boolean flag', () => {91 test('when env undefined and no cli then option undefined', () => {92 const program = new commander.Command();93 program.addOption(new commander.Option('-f, --foo').env('BAR'));94 program.parse([], { from: 'user' });95 assert.equal(program.opts().foo, undefined);96 });86 }87});9789describe('boolean flag', () => {90 test('when env undefined and no cli then option undefined', () => {91 const program = new commander.Command();92 program.addOption(new commander.Option('-f, --foo').env('BAR'));93 program.parse([], { from: 'user' });94 assert.equal(program.opts().foo, undefined);95 });98 test('when env defined with value and no cli then option true', () => {99 const program = new commander.Command();100 process.env.BAR = 'env';101 program.addOption(new commander.Option('-f, --foo').env('BAR'));102 program.parse([], { from: 'user' });103 assert.equal(program.opts().foo, true);104 delete process.env.BAR;105 });106107 test('when env is "" and no cli then option true', () => {97 test('when env defined with value and no cli then option true', () => {98 const program = new commander.Command();99 process.env.BAR = 'env';100 program.addOption(new commander.Option('-f, --foo').env('BAR'));101 program.parse([], { from: 'user' });102 assert.equal(program.opts().foo, true);103 delete process.env.BAR;104 });108 // any string, including ""109 const program = new commander.Command();110 process.env.BAR = '';111 program.addOption(new commander.Option('-f, --foo').env('BAR'));112 program.parse([], { from: 'user' });113 assert.equal(program.opts().foo, true);114 delete process.env.BAR;115 });116106 test('when env is "" and no cli then option true', () => {107 // any string, including ""108 const program = new commander.Command();109 process.env.BAR = '';110 program.addOption(new commander.Option('-f, --foo').env('BAR'));111 program.parse([], { from: 'user' });112 assert.equal(program.opts().foo, true);113 delete process.env.BAR;114 });117 test('when env is "0" and no cli then option true', () => {118 // any string, including "0"119 const program = new commander.Command();120 process.env.BAR = '0';121 program.addOption(new commander.Option('-f, --foo').env('BAR'));122 program.parse([], { from: 'user' });123 assert.equal(program.opts().foo, true);124 delete process.env.BAR;125 });126116 test('when env is "0" and no cli then option true', () => {117 // any string, including "0"118 const program = new commander.Command();119 process.env.BAR = '0';120 program.addOption(new commander.Option('-f, --foo').env('BAR'));121 program.parse([], { from: 'user' });122 assert.equal(program.opts().foo, true);123 delete process.env.BAR;127 test('when env is "false" and no cli then option true', () => {128 // any string, including "false"129 const program = new commander.Command();130 process.env.BAR = 'false';131 program.addOption(new commander.Option('-f, --foo').env('BAR'));132 program.parse([], { from: 'user' });133 assert.equal(program.opts().foo, true);134 delete process.env.BAR;135 });136 });137126 test('when env is "false" and no cli then option true', () => {127 // any string, including "false"128 const program = new commander.Command();129 process.env.BAR = 'false';130 program.addOption(new commander.Option('-f, --foo').env('BAR'));131 program.parse([], { from: 'user' });132 assert.equal(program.opts().foo, true);133 delete process.env.BAR;134 });135});138 describe('boolean no-flag', () => {139 test('when env undefined and no cli then option true', () => {140 const program = new commander.Command();141 program.addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));142 program.parse([], { from: 'user' });143 assert.equal(program.opts().foo, true);144 });145137describe('boolean no-flag', () => {138 test('when env undefined and no cli then option true', () => {139 const program = new commander.Command();140 program.addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));141 program.parse([], { from: 'user' });142 assert.equal(program.opts().foo, true);146 test('when env defined and no cli then option false', () => {147 const program = new commander.Command();148 process.env.NO_BAR = 'env';149 program.addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));150 program.parse([], { from: 'user' });151 assert.equal(program.opts().foo, false);152 delete process.env.NO_BAR;153 });154 });155145 test('when env defined and no cli then option false', () => {146 const program = new commander.Command();147 process.env.NO_BAR = 'env';148 program.addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));149 program.parse([], { from: 'user' });150 assert.equal(program.opts().foo, false);151 delete process.env.NO_BAR;152 });153});156 describe('boolean flag and negatable', () => {157 test('when env undefined and no cli then option undefined', () => {158 const program = new commander.Command();159 program160 .addOption(new commander.Option('-f, --foo').env('BAR'))161 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));162 program.parse([], { from: 'user' });163 assert.equal(program.opts().foo, undefined);164 });165155describe('boolean flag and negatable', () => {156 test('when env undefined and no cli then option undefined', () => {157 const program = new commander.Command();158 program159 .addOption(new commander.Option('-f, --foo').env('BAR'))160 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));161 program.parse([], { from: 'user' });162 assert.equal(program.opts().foo, undefined);163 });166 test('when env defined and no cli then option true', () => {167 const program = new commander.Command();168 process.env.BAR = 'env';169 program170 .addOption(new commander.Option('-f, --foo').env('BAR'))171 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));172 program.parse([], { from: 'user' });173 assert.equal(program.opts().foo, true);174 delete process.env.BAR;175 });176165 test('when env defined and no cli then option true', () => {166 const program = new commander.Command();167 process.env.BAR = 'env';168 program169 .addOption(new commander.Option('-f, --foo').env('BAR'))170 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));171 program.parse([], { from: 'user' });172 assert.equal(program.opts().foo, true);173 delete process.env.BAR;174 });177 test('when env defined and cli --no-foo then option false', () => {178 const program = new commander.Command();179 process.env.BAR = 'env';180 program181 .addOption(new commander.Option('-f, --foo').env('BAR'))182 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));183 program.parse(['--no-foo'], { from: 'user' });184 assert.equal(program.opts().foo, false);185 delete process.env.BAR;186 });187176 test('when env defined and cli --no-foo then option false', () => {177 const program = new commander.Command();178 process.env.BAR = 'env';179 program180 .addOption(new commander.Option('-f, --foo').env('BAR'))181 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));182 program.parse(['--no-foo'], { from: 'user' });183 assert.equal(program.opts().foo, false);184 delete process.env.BAR;185 });188 test('when no_env defined and no cli then option false', () => {189 const program = new commander.Command();190 process.env.NO_BAR = 'env';191 program192 .addOption(new commander.Option('-f, --foo').env('BAR'))193 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));194 program.parse([], { from: 'user' });195 assert.equal(program.opts().foo, false);196 delete process.env.NO_BAR;197 });198187 test('when no_env defined and no cli then option false', () => {188 const program = new commander.Command();189 process.env.NO_BAR = 'env';190 program191 .addOption(new commander.Option('-f, --foo').env('BAR'))192 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));193 program.parse([], { from: 'user' });194 assert.equal(program.opts().foo, false);195 delete process.env.NO_BAR;199 test('when no_env defined and cli --foo then option true', () => {200 const program = new commander.Command();201 process.env.NO_BAR = 'env';202 program203 .addOption(new commander.Option('-f, --foo').env('BAR'))204 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));205 program.parse(['--foo'], { from: 'user' });206 assert.equal(program.opts().foo, true);207 delete process.env.NO_BAR;208 });209 });210198 test('when no_env defined and cli --foo then option true', () => {199 const program = new commander.Command();200 process.env.NO_BAR = 'env';201 program202 .addOption(new commander.Option('-f, --foo').env('BAR'))203 .addOption(new commander.Option('-F, --no-foo').env('NO_BAR'));204 program.parse(['--foo'], { from: 'user' });205 assert.equal(program.opts().foo, true);206 delete process.env.NO_BAR;211 describe('custom argParser', () => {212 test('when env defined and no cli then custom parse from env', () => {213 const program = new commander.Command();214 process.env.BAR = 'env';215 program.addOption(216 new commander.Option('-f, --foo <required>')217 .env('BAR')218 .argParser((str) => str.toUpperCase()),219 );220 program.parse([], { from: 'user' });221 assert.equal(program.opts().foo, 'ENV');222 delete process.env.BAR;223 });224 });208});225210describe('custom argParser', () => {211 test('when env defined and no cli then custom parse from env', () => {212 const program = new commander.Command();213 process.env.BAR = 'env';214 program.addOption(215 new commander.Option('-f, --foo <required>')216 .env('BAR')217 .argParser((str) => str.toUpperCase()),218 );219 program.parse([], { from: 'user' });220 assert.equal(program.opts().foo, 'ENV');221 delete process.env.BAR;222 });223});226 describe('variadic', () => {227 test('when env defined and no cli then array from env', () => {228 const program = new commander.Command();229 process.env.BAR = 'env';230 program.addOption(231 new commander.Option('-f, --foo <required...>').env('BAR'),232 );233 program.parse([], { from: 'user' });234 assert.deepEqual(program.opts().foo, ['env']);235 delete process.env.BAR;236 });237225describe('variadic', () => {226 test('when env defined and no cli then array from env', () => {227 const program = new commander.Command();228 process.env.BAR = 'env';229 program.addOption(230 new commander.Option('-f, --foo <required...>').env('BAR'),231 );232 program.parse([], { from: 'user' });233 assert.deepEqual(program.opts().foo, ['env']);234 delete process.env.BAR;238 test('when env defined and cli then array from cli', () => {239 const program = new commander.Command();240 process.env.BAR = 'env';241 program.addOption(242 new commander.Option('-f, --foo <required...>').env('BAR'),243 );244 program.parse(['--foo', 'cli'], { from: 'user' });245 assert.deepEqual(program.opts().foo, ['cli']);246 delete process.env.BAR;247 });248 });249237 test('when env defined and cli then array from cli', () => {238 const program = new commander.Command();239 process.env.BAR = 'env';240 program.addOption(241 new commander.Option('-f, --foo <required...>').env('BAR'),242 );243 program.parse(['--foo', 'cli'], { from: 'user' });244 assert.deepEqual(program.opts().foo, ['cli']);245 delete process.env.BAR;246 });247});250 describe('env only processed when applies', () => {251 test('when env defined on another subcommand then env not applied', () => {252 // Doing selective processing. Not processing env at addOption time.253 const program = new commander.Command();254 process.env.BAR = 'env';255 program.command('one').action(() => {});256 const two = program257 .command('two')258 .addOption(259 new commander.Option('-f, --foo <required...>')260 .env('BAR')261 .default('default'),262 )263 .action(() => {});264 program.parse(['one'], { from: 'user' });265 assert.equal(two.opts().foo, 'default');266 delete process.env.BAR;267 });268249describe('env only processed when applies', () => {250 test('when env defined on another subcommand then env not applied', () => {251 // Doing selective processing. Not processing env at addOption time.252 const program = new commander.Command();253 process.env.BAR = 'env';254 program.command('one').action(() => {});255 const two = program256 .command('two')257 .addOption(269 test('when env and cli defined then only emit option event for cli', (t) => {270 const program = new commander.Command();271 const optionEventMock = t.mock.fn();272 const optionEnvEventMock = t.mock.fn();273 program.on('option:foo', optionEventMock);274 program.on('optionEnv:foo', optionEnvEventMock);275 process.env.BAR = 'env';276 program.addOption(277 new commander.Option('-f, --foo <required...>').env('BAR'),278 );279 program.parse(['--foo', 'cli'], { from: 'user' });280 assert.equal(optionEventMock.mock.calls[0].arguments[0], 'cli');281 assert.equal(optionEventMock.mock.callCount(), 1);282 assert.equal(optionEnvEventMock.mock.callCount(), 0);283 delete process.env.BAR;284 });285286 test('when env and cli defined then only parse value for cli', (t) => {287 const program = new commander.Command();288 const parseMock = t.mock.fn();289 process.env.BAR = 'env';290 program.addOption(291 new commander.Option('-f, --foo <required...>')292 .env('BAR')260 .default('default'),261 )262 .action(() => {});263 program.parse(['one'], { from: 'user' });264 assert.equal(two.opts().foo, 'default');265 delete process.env.BAR;293 .argParser(parseMock),294 );295 program.parse(['--foo', 'cli'], { from: 'user' });296 assert.equal(parseMock.mock.calls[0].arguments[0], 'cli');297 assert.equal(parseMock.mock.calls[0].arguments[1], undefined);298 assert.equal(parseMock.mock.callCount(), 1);299 delete process.env.BAR;300 });301 });302268 test('when env and cli defined then only emit option event for cli', (t) => {269 const program = new commander.Command();270 const optionEventMock = t.mock.fn();271 const optionEnvEventMock = t.mock.fn();272 program.on('option:foo', optionEventMock);273 program.on('optionEnv:foo', optionEnvEventMock);274 process.env.BAR = 'env';275 program.addOption(276 new commander.Option('-f, --foo <required...>').env('BAR'),277 );278 program.parse(['--foo', 'cli'], { from: 'user' });279 assert.equal(optionEventMock.mock.calls[0].arguments[0], 'cli');280 assert.equal(optionEventMock.mock.callCount(), 1);281 assert.equal(optionEnvEventMock.mock.callCount(), 0);282 delete process.env.BAR;283 });303 describe('events dispatched for env', () => {304 test('when env defined then emit "optionEnv" and not "option"', (t) => {305 // Decided to do separate events, so test stays that way.306 const program = new commander.Command();307 const optionEventMock = t.mock.fn();308 const optionEnvEventMock = t.mock.fn();309 program.on('option:foo', optionEventMock);310 program.on('optionEnv:foo', optionEnvEventMock);311 process.env.BAR = 'env';312 program.addOption(313 new commander.Option('-f, --foo <required>').env('BAR'),314 );315 program.parse([], { from: 'user' });316 assert.equal(optionEventMock.mock.callCount(), 0);317 assert.equal(optionEnvEventMock.mock.callCount(), 1);318 delete process.env.BAR;319 });320285 test('when env and cli defined then only parse value for cli', (t) => {286 const program = new commander.Command();287 const parseMock = t.mock.fn();288 process.env.BAR = 'env';289 program.addOption(290 new commander.Option('-f, --foo <required...>')291 .env('BAR')292 .argParser(parseMock),293 );294 program.parse(['--foo', 'cli'], { from: 'user' });295 assert.equal(parseMock.mock.calls[0].arguments[0], 'cli');296 assert.equal(parseMock.mock.calls[0].arguments[1], undefined);297 assert.equal(parseMock.mock.callCount(), 1);298 delete process.env.BAR;299 });300});321 test('when env defined for required then emit "optionEnv" with value', (t) => {322 const program = new commander.Command();323 const optionEnvEventMock = t.mock.fn();324 program.on('optionEnv:foo', optionEnvEventMock);325 process.env.BAR = 'env';326 program.addOption(327 new commander.Option('-f, --foo <required>').env('BAR'),328 );329 program.parse([], { from: 'user' });330 assert.equal(optionEnvEventMock.mock.calls[0].arguments[0], 'env');331 delete process.env.BAR;332 });333302describe('events dispatched for env', () => {303 test('when env defined then emit "optionEnv" and not "option"', (t) => {304 // Decided to do separate events, so test stays that way.305 const program = new commander.Command();306 const optionEventMock = t.mock.fn();307 const optionEnvEventMock = t.mock.fn();308 program.on('option:foo', optionEventMock);309 program.on('optionEnv:foo', optionEnvEventMock);310 process.env.BAR = 'env';311 program.addOption(new commander.Option('-f, --foo <required>').env('BAR'));312 program.parse([], { from: 'user' });313 assert.equal(optionEventMock.mock.callCount(), 0);314 assert.equal(optionEnvEventMock.mock.callCount(), 1);315 delete process.env.BAR;316 });334 test('when env defined for optional then emit "optionEnv" with value', (t) => {335 const program = new commander.Command();336 const optionEnvEventMock = t.mock.fn();337 program.on('optionEnv:foo', optionEnvEventMock);338 process.env.BAR = 'env';339 program.addOption(340 new commander.Option('-f, --foo [optional]').env('BAR'),341 );342 program.parse([], { from: 'user' });343 assert.equal(optionEnvEventMock.mock.calls[0].arguments[0], 'env');344 delete process.env.BAR;345 });346347 test('when env defined for boolean then emit "optionEnv" with no param', (t) => {318 test('when env defined for required then emit "optionEnv" with value', (t) => {319 const program = new commander.Command();320 const optionEnvEventMock = t.mock.fn();321 program.on('optionEnv:foo', optionEnvEventMock);322 process.env.BAR = 'env';323 program.addOption(new commander.Option('-f, --foo <required>').env('BAR'));324 program.parse([], { from: 'user' });325 assert.equal(optionEnvEventMock.mock.calls[0].arguments[0], 'env');326 delete process.env.BAR;327 });348 // check matches historical boolean action event349 const program = new commander.Command();350 const optionEnvEventMock = t.mock.fn();351 program.on('optionEnv:foo', optionEnvEventMock);352 process.env.BAR = 'anything';353 program.addOption(new commander.Option('-f, --foo').env('BAR'));354 program.parse([], { from: 'user' });355 assert.equal(optionEnvEventMock.mock.calls[0].arguments.length, 0);356 delete process.env.BAR;357 });358359 test('when env defined for negated boolean then emit "optionEnv" with no param', (t) => {329 test('when env defined for optional then emit "optionEnv" with value', (t) => {330 const program = new commander.Command();331 const optionEnvEventMock = t.mock.fn();332 program.on('optionEnv:foo', optionEnvEventMock);333 process.env.BAR = 'env';334 program.addOption(new commander.Option('-f, --foo [optional]').env('BAR'));335 program.parse([], { from: 'user' });336 assert.equal(optionEnvEventMock.mock.calls[0].arguments[0], 'env');337 delete process.env.BAR;360 // check matches historical boolean action event361 const program = new commander.Command();362 const optionEnvEventMock = t.mock.fn();363 program.on('optionEnv:no-foo', optionEnvEventMock);364 process.env.BAR = 'anything';365 program.addOption(new commander.Option('-F, --no-foo').env('BAR'));366 program.parse([], { from: 'user' });367 assert.equal(optionEnvEventMock.mock.calls[0].arguments.length, 0);368 delete process.env.BAR;369 });370 });339340 test('when env defined for boolean then emit "optionEnv" with no param', (t) => {341 // check matches historical boolean action event342 const program = new commander.Command();343 const optionEnvEventMock = t.mock.fn();344 program.on('optionEnv:foo', optionEnvEventMock);345 process.env.BAR = 'anything';346 program.addOption(new commander.Option('-f, --foo').env('BAR'));347 program.parse([], { from: 'user' });348 assert.equal(optionEnvEventMock.mock.calls[0].arguments.length, 0);349 delete process.env.BAR;350 });351352 test('when env defined for negated boolean then emit "optionEnv" with no param', (t) => {353 // check matches historical boolean action event354 const program = new commander.Command();355 const optionEnvEventMock = t.mock.fn();356 program.on('optionEnv:no-foo', optionEnvEventMock);357 process.env.BAR = 'anything';358 program.addOption(new commander.Option('-F, --no-foo').env('BAR'));359 program.parse([], { from: 'user' });360 assert.equal(optionEnvEventMock.mock.calls[0].arguments.length, 0);361 delete process.env.BAR;362 });371});
modified:tests/options.flags.test.js+62 added-60 removed
1const commander = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45// Test the various ways flags can be specified in the first parameter to `.option`67describe('option parsing', () => {7test('when only short flag defined and not specified then value is undefined', () => {8 const program = new commander.Command();9 program.option('-p', 'add pepper');10 program.parse(['node', 'test']);11 assert.equal(program.opts().p, undefined);12});8 test('when only short flag defined and not specified then value is undefined', () => {9 const program = new commander.Command();10 program.option('-p', 'add pepper');11 program.parse(['node', 'test']);12 assert.equal(program.opts().p, undefined);13 });1414test('when only short flag defined and specified then value is true', () => {15 const program = new commander.Command();16 program.option('-p', 'add pepper');17 program.parse(['node', 'test', '-p']);18 assert.equal(program.opts().p, true);19});15 test('when only short flag defined and specified then value is true', () => {16 const program = new commander.Command();17 program.option('-p', 'add pepper');18 program.parse(['node', 'test', '-p']);19 assert.equal(program.opts().p, true);20 });2121test('when only long flag defined and not specified then value is undefined', () => {22 const program = new commander.Command();23 program.option('--pepper', 'add pepper');24 program.parse(['node', 'test']);25 assert.equal(program.opts().pepper, undefined);26});22 test('when only long flag defined and not specified then value is undefined', () => {23 const program = new commander.Command();24 program.option('--pepper', 'add pepper');25 program.parse(['node', 'test']);26 assert.equal(program.opts().pepper, undefined);27 });2828test('when only long flag defined and specified then value is true', () => {29 const program = new commander.Command();30 program.option('--pepper', 'add pepper');31 program.parse(['node', 'test', '--pepper']);32 assert.equal(program.opts().pepper, true);33});29 test('when only long flag defined and specified then value is true', () => {30 const program = new commander.Command();31 program.option('--pepper', 'add pepper');32 program.parse(['node', 'test', '--pepper']);33 assert.equal(program.opts().pepper, true);34 });3535test('when "short,long" flags defined and short specified then value is true', () => {36 const program = new commander.Command();37 program.option('-p,--pepper', 'add pepper');38 program.parse(['node', 'test', '-p']);39 assert.equal(program.opts().pepper, true);40});36 test('when "short,long" flags defined and short specified then value is true', () => {37 const program = new commander.Command();38 program.option('-p,--pepper', 'add pepper');39 program.parse(['node', 'test', '-p']);40 assert.equal(program.opts().pepper, true);41 });4242test('when "short,long" flags defined and long specified then value is true', () => {43 const program = new commander.Command();44 program.option('-p,--pepper', 'add pepper');45 program.parse(['node', 'test', '--pepper']);46 assert.equal(program.opts().pepper, true);47});43 test('when "short,long" flags defined and long specified then value is true', () => {44 const program = new commander.Command();45 program.option('-p,--pepper', 'add pepper');46 program.parse(['node', 'test', '--pepper']);47 assert.equal(program.opts().pepper, true);48 });4949test('when "short|long" flags defined and short specified then value is true', () => {50 const program = new commander.Command();51 program.option('-p|--pepper', 'add pepper');52 program.parse(['node', 'test', '-p']);53 assert.equal(program.opts().pepper, true);54});50 test('when "short|long" flags defined and short specified then value is true', () => {51 const program = new commander.Command();52 program.option('-p|--pepper', 'add pepper');53 program.parse(['node', 'test', '-p']);54 assert.equal(program.opts().pepper, true);55 });5656test('when "short|long" flags defined and long specified then value is true', () => {57 const program = new commander.Command();58 program.option('-p|--pepper', 'add pepper');59 program.parse(['node', 'test', '--pepper']);60 assert.equal(program.opts().pepper, true);61});57 test('when "short|long" flags defined and long specified then value is true', () => {58 const program = new commander.Command();59 program.option('-p|--pepper', 'add pepper');60 program.parse(['node', 'test', '--pepper']);61 assert.equal(program.opts().pepper, true);62 });6363test('when "short long" flags defined and short specified then value is true', () => {64 const program = new commander.Command();65 program.option('-p --pepper', 'add pepper');66 program.parse(['node', 'test', '-p']);67 assert.equal(program.opts().pepper, true);68});64 test('when "short long" flags defined and short specified then value is true', () => {65 const program = new commander.Command();66 program.option('-p --pepper', 'add pepper');67 program.parse(['node', 'test', '-p']);68 assert.equal(program.opts().pepper, true);69 });7070test('when "short long" flags defined and long specified then value is true', () => {71 const program = new commander.Command();72 program.option('-p --pepper', 'add pepper');73 program.parse(['node', 'test', '--pepper']);74 assert.equal(program.opts().pepper, true);71 test('when "short long" flags defined and long specified then value is true', () => {72 const program = new commander.Command();73 program.option('-p --pepper', 'add pepper');74 program.parse(['node', 'test', '--pepper']);75 assert.equal(program.opts().pepper, true);76 });77});
modified:tests/options.getset.test.js+61 added-59 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Command.getOptionValue() and .setOptionValue()', () => {5describe('storeOptionsAsProperties', () => {6 const storeOptionsAsPropertiesList = [true, false];7 for (const storeOptionsAsProperties of storeOptionsAsPropertiesList) {8 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and option specified on CLI then value returned by getOptionValue`, () => {9 const program = new commander.Command();10 program11 .storeOptionsAsProperties(storeOptionsAsProperties)12 .option('--cheese [type]', 'cheese type');13 const cheeseType = 'blue';14 program.parse(['node', 'test', '--cheese', cheeseType]);15 assert.equal(program.getOptionValue('cheese'), cheeseType);16 });6 describe('storeOptionsAsProperties', () => {7 const storeOptionsAsPropertiesList = [true, false];8 for (const storeOptionsAsProperties of storeOptionsAsPropertiesList) {9 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and option specified on CLI then value returned by getOptionValue`, () => {10 const program = new commander.Command();11 program12 .storeOptionsAsProperties(storeOptionsAsProperties)13 .option('--cheese [type]', 'cheese type');14 const cheeseType = 'blue';15 program.parse(['node', 'test', '--cheese', cheeseType]);16 assert.equal(program.getOptionValue('cheese'), cheeseType);17 });1818 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and setOptionValue then value returned by opts`, () => {19 const program = new commander.Command();20 const cheeseType = 'blue';21 // Note: opts() only returns declared options when options stored as properties22 program23 .storeOptionsAsProperties(storeOptionsAsProperties)24 .option('--cheese [type]', 'cheese type')25 .setOptionValue('cheese', cheeseType);26 assert.equal(program.opts().cheese, cheeseType);27 });28 }29});19 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and setOptionValue then value returned by opts`, () => {20 const program = new commander.Command();21 const cheeseType = 'blue';22 // Note: opts() only returns declared options when options stored as properties23 program24 .storeOptionsAsProperties(storeOptionsAsProperties)25 .option('--cheese [type]', 'cheese type')26 .setOptionValue('cheese', cheeseType);27 assert.equal(program.opts().cheese, cheeseType);28 });29 }30 });3131test('when setOptionValueWithSource then value returned by opts', () => {32 const program = new commander.Command();33 const cheeseValue = 'blue';34 program35 .option('--cheese [type]', 'cheese type')36 .setOptionValueWithSource('cheese', cheeseValue, 'cli');37 assert.equal(program.opts().cheese, cheeseValue);38});32 test('when setOptionValueWithSource then value returned by opts', () => {33 const program = new commander.Command();34 const cheeseValue = 'blue';35 program36 .option('--cheese [type]', 'cheese type')37 .setOptionValueWithSource('cheese', cheeseValue, 'cli');38 assert.equal(program.opts().cheese, cheeseValue);39 });4040test('when setOptionValueWithSource then source returned by getOptionValueSource', () => {41 const program = new commander.Command();42 program43 .option('--cheese [type]', 'cheese type')44 .setOptionValueWithSource('cheese', 'blue', 'config');45 assert.equal(program.getOptionValueSource('cheese'), 'config');46});41 test('when setOptionValueWithSource then source returned by getOptionValueSource', () => {42 const program = new commander.Command();43 program44 .option('--cheese [type]', 'cheese type')45 .setOptionValueWithSource('cheese', 'blue', 'config');46 assert.equal(program.getOptionValueSource('cheese'), 'config');47 });4848test('when option value parsed from env then option source is env', () => {49 const program = new commander.Command();50 process.env.BAR = 'env';51 program.addOption(new commander.Option('-f, --foo').env('BAR'));52 program.parse([], { from: 'user' });53 assert.equal(program.getOptionValueSource('foo'), 'env');54 delete process.env.BAR;55});49 test('when option value parsed from env then option source is env', () => {50 const program = new commander.Command();51 process.env.BAR = 'env';52 program.addOption(new commander.Option('-f, --foo').env('BAR'));53 program.parse([], { from: 'user' });54 assert.equal(program.getOptionValueSource('foo'), 'env');55 delete process.env.BAR;56 });5757test('when option value parsed from cli then option source is cli', () => {58 const program = new commander.Command();59 program.addOption(new commander.Option('-f, --foo').env('BAR'));60 program.parse(['--foo'], { from: 'user' });61 assert.equal(program.getOptionValueSource('foo'), 'cli');62});58 test('when option value parsed from cli then option source is cli', () => {59 const program = new commander.Command();60 program.addOption(new commander.Option('-f, --foo').env('BAR'));61 program.parse(['--foo'], { from: 'user' });62 assert.equal(program.getOptionValueSource('foo'), 'cli');63 });6464test('when setOptionValue then clears previous source', () => {65 const program = new commander.Command();66 program.option('--foo', 'description', 'default value');67 assert.equal(program.getOptionValueSource('foo'), 'default');68 program.setOptionValue('foo', 'bar');69 assert.equal(program.getOptionValueSource('foo'), undefined);65 test('when setOptionValue then clears previous source', () => {66 const program = new commander.Command();67 program.option('--foo', 'description', 'default value');68 assert.equal(program.getOptionValueSource('foo'), 'default');69 program.setOptionValue('foo', 'bar');70 assert.equal(program.getOptionValueSource('foo'), undefined);71 });72});
modified:tests/options.implies.test.js+178 added-176 removed
1 unmodified line
2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56describe('Option.implies()', () => {6describe('check priorities', () => {7 test('when source undefined and implied undefined then implied is undefined', () => {7 describe('check priorities', () => {8 test('when source undefined and implied undefined then implied is undefined', () => {9 const program = new Command();10 program11 .addOption(new Option('--foo').implies({ bar: 'implied' }))12 .option('--bar');13 program.parse([], { from: 'user' });14 assert.deepEqual(program.opts(), {});15 });1617 test('when source default and implied undefined then implied is undefined', () => {18 const program = new Command();19 program20 .addOption(21 new Option('--foo').implies({ bar: 'implied' }).default('default'),22 )23 .option('--bar');24 program.parse([], { from: 'user' });25 assert.deepEqual(program.opts(), { foo: 'default' });26 });2728 test('when source from env and implied undefined then implied is implied', () => {29 const program = new Command();30 const envName = 'COMMANDER_TEST_DELETE_ME';31 process.env[envName] = 'env';32 program33 .addOption(new Option('--foo').implies({ bar: 'implied' }).env(envName))34 .option('--bar');35 program.parse([], { from: 'user' });36 assert.deepEqual(program.opts(), { foo: true, bar: 'implied' });37 delete process.env[envName];38 });3940 test('when source from cli and implied undefined then implied is implied', () => {41 const program = new Command();42 program43 .addOption(new Option('--foo').implies({ bar: 'implied' }))44 .option('--bar');45 program.parse(['--foo'], { from: 'user' });46 assert.deepEqual(program.opts(), { foo: true, bar: 'implied' });47 });4849 test('when source cli and implied default then implied is implied', () => {50 const program = new Command();51 program52 .addOption(new Option('--foo').implies({ bar: 'implied' }))53 .option('--bar', '', 'default');54 program.parse(['--foo'], { from: 'user' });55 assert.deepEqual(program.opts(), { foo: true, bar: 'implied' });56 });5758 test('when source cli and env default then implied is env', () => {59 const program = new Command();60 const envName = 'COMMANDER_TEST_DELETE_ME';61 process.env[envName] = 'env';62 program63 .addOption(new Option('--foo').implies({ bar: 'implied' }))64 .addOption(new Option('--bar <value>').env(envName));65 program.parse(['--foo'], { from: 'user' });66 assert.deepEqual(program.opts(), { foo: true, bar: 'env' });67 delete process.env[envName];68 });69 });7071 test('when imply non-option then ok and stored', () => {72 const program = new Command();73 program.addOption(new Option('--foo').implies({ bar: 'implied' }));74 program.parse(['--foo'], { from: 'user' });75 assert.deepEqual(program.opts(), { foo: true, bar: 'implied' });76 });7778 test('when imply multiple values then store multiple values', () => {79 const program = new Command();80 program10 .addOption(new Option('--foo').implies({ bar: 'implied' }))11 .option('--bar');12 program.parse([], { from: 'user' });13 assert.deepEqual(program.opts(), {});81 .addOption(new Option('--foo').implies({ one: 'ONE', two: 'TWO' }))82 .option('--one')83 .option('--two');84 program.parse(['--foo'], { from: 'user' });85 assert.deepEqual(program.opts(), { foo: true, one: 'ONE', two: 'TWO' });86 });8716 test('when source default and implied undefined then implied is undefined', () => {88 test('when imply multiple times then store multiple values', () => {89 const program = new Command();90 program91 .addOption(20 new Option('--foo').implies({ bar: 'implied' }).default('default'),92 new Option('--foo').implies({ one: 'ONE' }).implies({ two: 'TWO' }),93 )22 .option('--bar');23 program.parse([], { from: 'user' });24 assert.deepEqual(program.opts(), { foo: 'default' });94 .option('--one')95 .option('--two');96 program.parse(['--foo'], { from: 'user' });97 assert.deepEqual(program.opts(), { foo: true, one: 'ONE', two: 'TWO' });98 });9927 test('when source from env and implied undefined then implied is implied', () => {100 test('when imply from positive option then positive implied', () => {101 const program = new Command();29 const envName = 'COMMANDER_TEST_DELETE_ME';30 process.env[envName] = 'env';102 program32 .addOption(new Option('--foo').implies({ bar: 'implied' }).env(envName))33 .option('--bar');34 program.parse([], { from: 'user' });35 assert.deepEqual(program.opts(), { foo: true, bar: 'implied' });36 delete process.env[envName];103 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))104 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));105 program.parse(['--foo'], { from: 'user' });106 assert.deepEqual(program.opts(), { foo: true, implied: 'POSITIVE' });107 });10839 test('when source from cli and implied undefined then implied is implied', () => {109 test('when imply from negative option then negative implied', () => {110 const program = new Command();111 program42 .addOption(new Option('--foo').implies({ bar: 'implied' }))43 .option('--bar');44 program.parse(['--foo'], { from: 'user' });45 assert.deepEqual(program.opts(), { foo: true, bar: 'implied' });112 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))113 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));114 program.parse(['--no-foo'], { from: 'user' });115 assert.deepEqual(program.opts(), { foo: false, implied: 'NEGATIVE' });116 });11748 test('when source cli and implied default then implied is implied', () => {118 test('when imply from lone negative option then negative implied', () => {119 const program = new Command();120 program.addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));121 program.parse(['--no-foo'], { from: 'user' });122 assert.deepEqual(program.opts(), { foo: false, implied: 'NEGATIVE' });123 });124125 test('when imply from negative option with preset then negative implied', () => {126 const program = new Command();127 program51 .addOption(new Option('--foo').implies({ bar: 'implied' }))52 .option('--bar', '', 'default');53 program.parse(['--foo'], { from: 'user' });54 assert.deepEqual(program.opts(), { foo: true, bar: 'implied' });128 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))129 .addOption(130 new Option('--no-foo').implies({ implied: 'NEGATIVE' }).preset('FALSE'),131 );132 program.parse(['--no-foo'], { from: 'user' });133 assert.deepEqual(program.opts(), { foo: 'FALSE', implied: 'NEGATIVE' });134 });13557 test('when source cli and env default then implied is env', () => {136 test('when chained implies then only explicitly trigger', () => {137 const program = new Command();59 const envName = 'COMMANDER_TEST_DELETE_ME';60 process.env[envName] = 'env';138 program62 .addOption(new Option('--foo').implies({ bar: 'implied' }))63 .addOption(new Option('--bar <value>').env(envName));64 program.parse(['--foo'], { from: 'user' });65 assert.deepEqual(program.opts(), { foo: true, bar: 'env' });66 delete process.env[envName];139 .addOption(new Option('--one').implies({ two: true }))140 .addOption(new Option('--two').implies({ three: true }))141 .addOption(new Option('--three'));142 program.parse(['--one'], { from: 'user' });143 assert.deepEqual(program.opts(), { one: true, two: true });144 });68});14570test('when imply non-option then ok and stored', () => {71 const program = new Command();72 program.addOption(new Option('--foo').implies({ bar: 'implied' }));73 program.parse(['--foo'], { from: 'user' });74 assert.deepEqual(program.opts(), { foo: true, bar: 'implied' });75});146 test('when looped implies then no infinite loop', () => {147 const program = new Command();148 program149 .addOption(new Option('--ying').implies({ yang: true }))150 .addOption(new Option('--yang').implies({ ying: true }));151 program.parse(['--ying'], { from: 'user' });152 assert.deepEqual(program.opts(), { ying: true, yang: true });153 });15477test('when imply multiple values then store multiple values', () => {78 const program = new Command();79 program80 .addOption(new Option('--foo').implies({ one: 'ONE', two: 'TWO' }))81 .option('--one')82 .option('--two');83 program.parse(['--foo'], { from: 'user' });84 assert.deepEqual(program.opts(), { foo: true, one: 'ONE', two: 'TWO' });85});155 test('when conflict with implied value then throw', () => {156 const program = createTestCommand();157 program158 .addOption(new Option('--unary'))159 .addOption(new Option('--binary').conflicts('unary'))160 .addOption(new Option('--one').implies({ unary: true }));16187test('when imply multiple times then store multiple values', () => {88 const program = new Command();89 program90 .addOption(91 new Option('--foo').implies({ one: 'ONE' }).implies({ two: 'TWO' }),92 )93 .option('--one')94 .option('--two');95 program.parse(['--foo'], { from: 'user' });96 assert.deepEqual(program.opts(), { foo: true, one: 'ONE', two: 'TWO' });97});162 assert.throws(() => {163 program.parse(['--binary', '--one'], { from: 'user' });164 });165 });16699test('when imply from positive option then positive implied', () => {100 const program = new Command();101 program102 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))103 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));104 program.parse(['--foo'], { from: 'user' });105 assert.deepEqual(program.opts(), { foo: true, implied: 'POSITIVE' });106});167 test('when requiredOption with implied value then not throw', () => {168 const program = new Command();169 program170 .requiredOption('--target <target-file>')171 .addOption(172 new Option('--default-target').implies({ target: 'default-file' }),173 );174108test('when imply from negative option then negative implied', () => {109 const program = new Command();110 program111 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))112 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));113 program.parse(['--no-foo'], { from: 'user' });114 assert.deepEqual(program.opts(), { foo: false, implied: 'NEGATIVE' });115});175 assert.doesNotThrow(() => {176 program.parse(['--default-target'], { from: 'user' });177 });178 });179117test('when imply from lone negative option then negative implied', () => {118 const program = new Command();119 program.addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));120 program.parse(['--no-foo'], { from: 'user' });121 assert.deepEqual(program.opts(), { foo: false, implied: 'NEGATIVE' });122});180 test('when implies on program and use subcommand then program updated', () => {181 const program = new Command();182 program.addOption(new Option('--foo').implies({ bar: 'implied' }));183 program.command('sub').action(() => {});184 program.parse(['--foo', 'sub'], { from: 'user' });185 assert.equal(program.opts().bar, 'implied');186 });187124test('when imply from negative option with preset then negative implied', () => {125 const program = new Command();126 program127 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))128 .addOption(129 new Option('--no-foo').implies({ implied: 'NEGATIVE' }).preset('FALSE'),130 );131 program.parse(['--no-foo'], { from: 'user' });132 assert.deepEqual(program.opts(), { foo: 'FALSE', implied: 'NEGATIVE' });133});188 test('when option with implies used multiple times then implied gets single value', () => {189 const program = new Command();190 program191 .addOption(new Option('--foo').implies({ bar: 'implied' }))192 .option('-b, --bar <value...>');193 program.parse(['--foo', '--foo'], { from: 'user' });194 assert.deepEqual(program.opts().bar, 'implied');195 });196135test('when chained implies then only explicitly trigger', () => {136 const program = new Command();137 program138 .addOption(new Option('--one').implies({ two: true }))139 .addOption(new Option('--two').implies({ three: true }))140 .addOption(new Option('--three'));141 program.parse(['--one'], { from: 'user' });142 assert.deepEqual(program.opts(), { one: true, two: true });143});144145test('when looped implies then no infinite loop', () => {146 const program = new Command();147 program148 .addOption(new Option('--ying').implies({ yang: true }))149 .addOption(new Option('--yang').implies({ ying: true }));150 program.parse(['--ying'], { from: 'user' });151 assert.deepEqual(program.opts(), { ying: true, yang: true });152});153154test('when conflict with implied value then throw', () => {155 const program = createTestCommand();156 program157 .addOption(new Option('--unary'))158 .addOption(new Option('--binary').conflicts('unary'))159 .addOption(new Option('--one').implies({ unary: true }));160161 assert.throws(() => {162 program.parse(['--binary', '--one'], { from: 'user' });197 test('when implied option has custom processing then custom processing not called', () => {198 let called = false;199 const program = new Command();200 program201 .addOption(new Option('--foo').implies({ bar: true }))202 .option('-b, --bar', 'description', () => {203 called = true;204 });205 program.parse(['--foo'], { from: 'user' });206 assert.equal(program.opts().bar, true);207 assert.equal(called, false);208 });164});209166test('when requiredOption with implied value then not throw', () => {167 const program = new Command();168 program169 .requiredOption('--target <target-file>')170 .addOption(171 new Option('--default-target').implies({ target: 'default-file' }),172 );173174 assert.doesNotThrow(() => {175 program.parse(['--default-target'], { from: 'user' });210 test('when passed string then treat as boolean', () => {211 // Do something sensible instead of something silly if user passes just name of option.212 // https://github.com/tj/commander.js/issues/1852213 const program = new Command();214 program215 .addOption(new Option('--foo').implies('bar'))216 .option('-b, --bar', 'description');217 program.parse(['--foo'], { from: 'user' });218 assert.equal(program.opts().bar, true);219 });220});178179test('when implies on program and use subcommand then program updated', () => {180 const program = new Command();181 program.addOption(new Option('--foo').implies({ bar: 'implied' }));182 program.command('sub').action(() => {});183 program.parse(['--foo', 'sub'], { from: 'user' });184 assert.equal(program.opts().bar, 'implied');185});186187test('when option with implies used multiple times then implied gets single value', () => {188 const program = new Command();189 program190 .addOption(new Option('--foo').implies({ bar: 'implied' }))191 .option('-b, --bar <value...>');192 program.parse(['--foo', '--foo'], { from: 'user' });193 assert.deepEqual(program.opts().bar, 'implied');194});195196test('when implied option has custom processing then custom processing not called', () => {197 let called = false;198 const program = new Command();199 program200 .addOption(new Option('--foo').implies({ bar: true }))201 .option('-b, --bar', 'description', () => {202 called = true;203 });204 program.parse(['--foo'], { from: 'user' });205 assert.equal(program.opts().bar, true);206 assert.equal(called, false);207});208209test('when passed string then treat as boolean', () => {210 // Do something sensible instead of something silly if user passes just name of option.211 // https://github.com/tj/commander.js/issues/1852212 const program = new Command();213 program214 .addOption(new Option('--foo').implies('bar'))215 .option('-b, --bar', 'description');216 program.parse(['--foo'], { from: 'user' });217 assert.equal(program.opts().bar, true);218});
modified:tests/options.mandatory.test.js+172 added-170 removed
4 unmodified lines
56// Assuming mandatory options behave as normal options apart from the mandatory aspect, not retesting all behaviour.7// Likewise, not redoing all tests on subcommand after testing on program.89describe('Command.requiredOption()', () => {9describe('required program option with mandatory value specified', () => {10 test('when program has required value specified then value as specified', () => {11 const program = new commander.Command();12 program.requiredOption('--cheese <type>', 'cheese type');13 program.parse(['node', 'test', '--cheese', 'blue']);14 assert.equal(program.opts().cheese, 'blue');15 });10 describe('required program option with mandatory value specified', () => {11 test('when program has required value specified then value as specified', () => {12 const program = new commander.Command();13 program.requiredOption('--cheese <type>', 'cheese type');14 program.parse(['node', 'test', '--cheese', 'blue']);15 assert.equal(program.opts().cheese, 'blue');16 });1717 test('when program has option with name different than property then still recognised', () => {18 const program = new commander.Command();19 program.requiredOption('--cheese-type <type>', 'cheese type');20 program.parse(['node', 'test', '--cheese-type', 'blue']);21 assert.equal(program.opts().cheeseType, 'blue');22 });18 test('when program has option with name different than property then still recognised', () => {19 const program = new commander.Command();20 program.requiredOption('--cheese-type <type>', 'cheese type');21 program.parse(['node', 'test', '--cheese-type', 'blue']);22 assert.equal(program.opts().cheeseType, 'blue');23 });2424 test('when program has required value default then default value', () => {25 const program = new commander.Command();26 program.requiredOption('--cheese <type>', 'cheese type', 'default');27 program.parse(['node', 'test']);28 assert.equal(program.opts().cheese, 'default');29 });25 test('when program has required value default then default value', () => {26 const program = new commander.Command();27 program.requiredOption('--cheese <type>', 'cheese type', 'default');28 program.parse(['node', 'test']);29 assert.equal(program.opts().cheese, 'default');30 });3131 test('when program has optional value flag specified then true', () => {32 const program = new commander.Command();33 program.requiredOption('--cheese [type]', 'cheese type');34 program.parse(['node', 'test', '--cheese']);35 assert.equal(program.opts().cheese, true);36 });32 test('when program has optional value flag specified then true', () => {33 const program = new commander.Command();34 program.requiredOption('--cheese [type]', 'cheese type');35 program.parse(['node', 'test', '--cheese']);36 assert.equal(program.opts().cheese, true);37 });3838 test('when program has optional value default then default value', () => {39 const program = new commander.Command();40 program.requiredOption('--cheese [type]', 'cheese type', 'default');41 program.parse(['node', 'test']);42 assert.equal(program.opts().cheese, 'default');43 });39 test('when program has optional value default then default value', () => {40 const program = new commander.Command();41 program.requiredOption('--cheese [type]', 'cheese type', 'default');42 program.parse(['node', 'test']);43 assert.equal(program.opts().cheese, 'default');44 });4545 test('when program has value/no flag specified with value then specified value', () => {46 const program = new commander.Command();47 program48 .requiredOption('--cheese <type>', 'cheese type')49 .requiredOption('--no-cheese', 'no cheese thanks');50 program.parse(['node', 'test', '--cheese', 'blue']);51 assert.equal(program.opts().cheese, 'blue');52 });46 test('when program has value/no flag specified with value then specified value', () => {47 const program = new commander.Command();48 program49 .requiredOption('--cheese <type>', 'cheese type')50 .requiredOption('--no-cheese', 'no cheese thanks');51 program.parse(['node', 'test', '--cheese', 'blue']);52 assert.equal(program.opts().cheese, 'blue');53 });5454 test('when program has mandatory-yes/no flag specified with flag then true', () => {55 const program = new commander.Command();56 program57 .requiredOption('--cheese', 'cheese type')58 .option('--no-cheese', 'no cheese thanks');59 program.parse(['node', 'test', '--cheese']);60 assert.equal(program.opts().cheese, true);61 });55 test('when program has mandatory-yes/no flag specified with flag then true', () => {56 const program = new commander.Command();57 program58 .requiredOption('--cheese', 'cheese type')59 .option('--no-cheese', 'no cheese thanks');60 program.parse(['node', 'test', '--cheese']);61 assert.equal(program.opts().cheese, true);62 });6363 test('when program has mandatory-yes/mandatory-no flag specified with flag then true', () => {64 const program = new commander.Command();65 program66 .requiredOption('--cheese', 'cheese type')67 .requiredOption('--no-cheese', 'no cheese thanks');68 program.parse(['node', 'test', '--cheese']);69 assert.equal(program.opts().cheese, true);70 });64 test('when program has mandatory-yes/mandatory-no flag specified with flag then true', () => {65 const program = new commander.Command();66 program67 .requiredOption('--cheese', 'cheese type')68 .requiredOption('--no-cheese', 'no cheese thanks');69 program.parse(['node', 'test', '--cheese']);70 assert.equal(program.opts().cheese, true);71 });7272 test('when program has yes/no flag specified negated then false', () => {73 const program = new commander.Command();74 program75 .requiredOption('--cheese <type>', 'cheese type')76 .option('--no-cheese', 'no cheese thanks');77 program.parse(['node', 'test', '--no-cheese']);78 assert.equal(program.opts().cheese, false);79 });73 test('when program has yes/no flag specified negated then false', () => {74 const program = new commander.Command();75 program76 .requiredOption('--cheese <type>', 'cheese type')77 .option('--no-cheese', 'no cheese thanks');78 program.parse(['node', 'test', '--no-cheese']);79 assert.equal(program.opts().cheese, false);80 });8181 test('when program has required value specified and subcommand then specified value', () => {82 const program = new commander.Command();83 program84 .requiredOption('--cheese <type>', 'cheese type')85 .command('sub')86 .action(() => {});87 program.parse(['node', 'test', '--cheese', 'blue', 'sub']);88 assert.equal(program.opts().cheese, 'blue');82 test('when program has required value specified and subcommand then specified value', () => {83 const program = new commander.Command();84 program85 .requiredOption('--cheese <type>', 'cheese type')86 .command('sub')87 .action(() => {});88 program.parse(['node', 'test', '--cheese', 'blue', 'sub']);89 assert.equal(program.opts().cheese, 'blue');90 });91 });90});9292describe('required program option with mandatory value not specified', () => {93 test('when program has required option not specified then error', () => {94 const program = createTestCommand();95 program.requiredOption('--cheese <type>', 'cheese type');93 describe('required program option with mandatory value not specified', () => {94 test('when program has required option not specified then error', () => {95 const program = createTestCommand();96 program.requiredOption('--cheese <type>', 'cheese type');9797 assert.throws(() => {98 program.parse(['node', 'test']);98 assert.throws(() => {99 program.parse(['node', 'test']);100 });101 });100 });102102 test('when program has optional option not specified then error', () => {103 const program = createTestCommand();104 program.requiredOption('--cheese [type]', 'cheese type');103 test('when program has optional option not specified then error', () => {104 const program = createTestCommand();105 program.requiredOption('--cheese [type]', 'cheese type');106106 assert.throws(() => {107 program.parse(['node', 'test']);107 assert.throws(() => {108 program.parse(['node', 'test']);109 });110 });109 });111111 test('when program has yes/no not specified then error', () => {112 const program = createTestCommand();113 program114 .requiredOption('--cheese', 'cheese type')115 .option('--no-cheese', 'no cheese thanks');112 test('when program has yes/no not specified then error', () => {113 const program = createTestCommand();114 program115 .requiredOption('--cheese', 'cheese type')116 .option('--no-cheese', 'no cheese thanks');117117 assert.throws(() => {118 program.parse(['node', 'test']);118 assert.throws(() => {119 program.parse(['node', 'test']);120 });121 });120 });122122 test('when program has required value not specified and subcommand then error', () => {123 const program = createTestCommand();124 program125 .requiredOption('--cheese <type>', 'cheese type')126 .command('sub')127 .action(() => {});123 test('when program has required value not specified and subcommand then error', () => {124 const program = createTestCommand();125 program126 .requiredOption('--cheese <type>', 'cheese type')127 .command('sub')128 .action(() => {});129129 assert.throws(() => {130 program.parse(['node', 'test', 'sub']);130 assert.throws(() => {131 program.parse(['node', 'test', 'sub']);132 });133 });134 });133});135135describe('required command option with mandatory value specified', () => {136 test('when command has required value specified then no error and option has specified value', () => {137 const program = createTestCommand();138 let cmdOptions;139 program140 .command('sub')141 .requiredOption('--subby <type>', 'description')142 .action((options) => {143 cmdOptions = options;144 });136 describe('required command option with mandatory value specified', () => {137 test('when command has required value specified then no error and option has specified value', () => {138 const program = createTestCommand();139 let cmdOptions;140 program141 .command('sub')142 .requiredOption('--subby <type>', 'description')143 .action((options) => {144 cmdOptions = options;145 });146146 program.parse(['node', 'test', 'sub', '--subby', 'blue']);147 program.parse(['node', 'test', 'sub', '--subby', 'blue']);148148 assert.equal(cmdOptions.subby, 'blue');149 });149 assert.equal(cmdOptions.subby, 'blue');150 });151151 test('when command has required value specified using env then no error and option has specified value', () => {152 const program = createTestCommand();153 program.addOption(154 new commander.Option('-p, --port <number>', 'port number')155 .makeOptionMandatory()156 .env('FOO'),157 );152 test('when command has required value specified using env then no error and option has specified value', () => {153 const program = createTestCommand();154 program.addOption(155 new commander.Option('-p, --port <number>', 'port number')156 .makeOptionMandatory()157 .env('FOO'),158 );159159 process.env.FOO = 'bar';160 program.parse([], { from: 'user' });161 delete process.env.FOO;160 process.env.FOO = 'bar';161 program.parse([], { from: 'user' });162 delete process.env.FOO;163163 assert.equal(program.opts().port, 'bar');164 assert.equal(program.opts().port, 'bar');165 });166 });165});167167describe('required command option with mandatory value not specified', () => {168 test('when command has required value not specified then error', () => {169 const program = createTestCommand();170 program171 .command('sub')172 .requiredOption('--subby <type>', 'description')173 .action(() => {});168 describe('required command option with mandatory value not specified', () => {169 test('when command has required value not specified then error', () => {170 const program = createTestCommand();171 program172 .command('sub')173 .requiredOption('--subby <type>', 'description')174 .action(() => {});175175 assert.throws(() => {176 program.parse(['node', 'test', 'sub']);176 assert.throws(() => {177 program.parse(['node', 'test', 'sub']);178 });179 });178 });180180 test('when command has required value but not called then no error', () => {181 const program = createTestCommand();182 program183 .command('sub')184 .requiredOption('--subby <type>', 'description')185 .action(() => {});186 program.command('sub2');181 test('when command has required value but not called then no error', () => {182 const program = createTestCommand();183 program184 .command('sub')185 .requiredOption('--subby <type>', 'description')186 .action(() => {});187 program.command('sub2');188188 assert.doesNotThrow(() => {189 program.parse(['node', 'test', 'sub2']);189 assert.doesNotThrow(() => {190 program.parse(['node', 'test', 'sub2']);191 });192 });193 });192});194194describe('missing mandatory option but help requested', () => {195 test('when program has required option not specified and --help then help', () => {196 const program = createTestCommand();197 program.requiredOption('--cheese <type>', 'cheese type');195 describe('missing mandatory option but help requested', () => {196 test('when program has required option not specified and --help then help', () => {197 const program = createTestCommand();198 program.requiredOption('--cheese <type>', 'cheese type');199199 assert.throws(200 () => {201 program.parse(['node', 'test', '--help']);202 },203 { code: 'commander.helpDisplayed' },204 );205 });200 assert.throws(201 () => {202 program.parse(['node', 'test', '--help']);203 },204 { code: 'commander.helpDisplayed' },205 );206 });207207 test('when program has required option not specified and subcommand --help then help', () => {208 const program = createTestCommand();209 program210 .requiredOption('--cheese <type>', 'cheese type')211 .command('sub')212 .action(() => {});208 test('when program has required option not specified and subcommand --help then help', () => {209 const program = createTestCommand();210 program211 .requiredOption('--cheese <type>', 'cheese type')212 .command('sub')213 .action(() => {});214214 assert.throws(215 () => {216 program.parse(['node', 'test', 'sub', '--help']);217 },218 { code: 'commander.helpDisplayed' },219 );215 assert.throws(216 () => {217 program.parse(['node', 'test', 'sub', '--help']);218 },219 { code: 'commander.helpDisplayed' },220 );221 });222 });223});
modified:tests/options.opts.test.js+60 added-58 removed
3 unmodified lines
45// Test the `.opts()` way of accessing option values.6// Basic coverage of the main option types (leaving out negatable flags and options with optional values).78describe('Command.opts()', () => {8test('when .version used with storeOptionsAsProperties() then version in opts', () => {9 const program = new commander.Command();10 const version = '0.0.1';11 program.storeOptionsAsProperties().version(version);12 program.parse(['node', 'test']);13 assert.deepEqual(program.opts(), { version });14});9 test('when .version used with storeOptionsAsProperties() then version in opts', () => {10 const program = new commander.Command();11 const version = '0.0.1';12 program.storeOptionsAsProperties().version(version);13 program.parse(['node', 'test']);14 assert.deepEqual(program.opts(), { version });15 });1616test('when .version used with storeOptionsAsProperties(false) then version not in opts', () => {17 // New behaviour, stop storing version as an option value.18 const program = new commander.Command();19 const version = '0.0.1';20 program.storeOptionsAsProperties(false).version(version);21 program.parse(['node', 'test']);22 assert.deepEqual(program.opts(), {});23});17 test('when .version used with storeOptionsAsProperties(false) then version not in opts', () => {18 // New behaviour, stop storing version as an option value.19 const program = new commander.Command();20 const version = '0.0.1';21 program.storeOptionsAsProperties(false).version(version);22 program.parse(['node', 'test']);23 assert.deepEqual(program.opts(), {});24 });2525describe('storeOptionsAsProperties', () => {26 const storeOptionsAsPropertiesList = [true, false];27 for (const storeOptionsAsProperties of storeOptionsAsPropertiesList) {28 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and boolean flag not specified then not in opts`, () => {29 const program = new commander.Command();30 program.storeOptionsAsProperties(storeOptionsAsProperties);31 program.option('--pepper', 'add pepper');32 program.parse(['node', 'test']);33 const expected = storeOptionsAsProperties ? { pepper: undefined } : {};34 assert.deepEqual(program.opts(), expected);35 });26 describe('storeOptionsAsProperties', () => {27 const storeOptionsAsPropertiesList = [true, false];28 for (const storeOptionsAsProperties of storeOptionsAsPropertiesList) {29 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and boolean flag not specified then not in opts`, () => {30 const program = new commander.Command();31 program.storeOptionsAsProperties(storeOptionsAsProperties);32 program.option('--pepper', 'add pepper');33 program.parse(['node', 'test']);34 const expected = storeOptionsAsProperties ? { pepper: undefined } : {};35 assert.deepEqual(program.opts(), expected);36 });3737 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and boolean flag specified then value true`, () => {38 const program = new commander.Command();39 program.storeOptionsAsProperties(storeOptionsAsProperties);40 program.option('--pepper', 'add pepper');41 program.parse(['node', 'test', '--pepper']);42 assert.deepEqual(program.opts(), { pepper: true });43 });38 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and boolean flag specified then value true`, () => {39 const program = new commander.Command();40 program.storeOptionsAsProperties(storeOptionsAsProperties);41 program.option('--pepper', 'add pepper');42 program.parse(['node', 'test', '--pepper']);43 assert.deepEqual(program.opts(), { pepper: true });44 });4545 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and option with required value not specified then not in opts`, () => {46 const program = new commander.Command();47 program.storeOptionsAsProperties(storeOptionsAsProperties);48 program.option('--pepper <flavour>', 'add pepper');49 program.parse(['node', 'test']);50 const expected = storeOptionsAsProperties ? { pepper: undefined } : {};51 assert.deepEqual(program.opts(), expected);52 });46 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and option with required value not specified then not in opts`, () => {47 const program = new commander.Command();48 program.storeOptionsAsProperties(storeOptionsAsProperties);49 program.option('--pepper <flavour>', 'add pepper');50 program.parse(['node', 'test']);51 const expected = storeOptionsAsProperties ? { pepper: undefined } : {};52 assert.deepEqual(program.opts(), expected);53 });5454 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and option with required value specified then value as specified`, () => {55 const pepperValue = 'red';56 const program = new commander.Command();57 program.storeOptionsAsProperties(storeOptionsAsProperties);58 program.option('--pepper <flavour>', 'add pepper');59 program.parse(['node', 'test', '--pepper', pepperValue]);60 assert.deepEqual(program.opts(), { pepper: pepperValue });61 });55 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and option with required value specified then value as specified`, () => {56 const pepperValue = 'red';57 const program = new commander.Command();58 program.storeOptionsAsProperties(storeOptionsAsProperties);59 program.option('--pepper <flavour>', 'add pepper');60 program.parse(['node', 'test', '--pepper', pepperValue]);61 assert.deepEqual(program.opts(), { pepper: pepperValue });62 });6363 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and option with default value not specified then default value in opts`, () => {64 const pepperDefault = 'red';65 const program = new commander.Command();66 program.storeOptionsAsProperties(storeOptionsAsProperties);67 program.option('--pepper <flavour>', 'add pepper', pepperDefault);68 program.parse(['node', 'test']);69 assert.deepEqual(program.opts(), { pepper: pepperDefault });70 });71 }64 test(`when storeOptionsAsProperties is ${storeOptionsAsProperties} and option with default value not specified then default value in opts`, () => {65 const pepperDefault = 'red';66 const program = new commander.Command();67 program.storeOptionsAsProperties(storeOptionsAsProperties);68 program.option('--pepper <flavour>', 'add pepper', pepperDefault);69 program.parse(['node', 'test']);70 assert.deepEqual(program.opts(), { pepper: pepperDefault });71 });72 }73 });74});
modified:tests/options.optsWithGlobals.test.js+1 added-1 removed
2 unmodified lines
3const assert = require('node:assert/strict');45// Testing optsWithGlobals and getOptionValueSourceWithGlobals with focus on globals.67describe('optsWithGlobals', () => {7describe('Command.optsWithGlobals()', () => {8 test('when variety of options used with program then opts is same as optsWithGlobals', () => {9 const program = new commander.Command();10 program11 .option('-b, --boolean')
105 unmodified lines
modified:tests/options.preset.test.js+52 added-50 removed
1const { Command, Option } = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('Option.preset()', () => {5test('when boolean option with string preset used then value is preset', () => {6 const program = new Command();7 program.addOption(new Option('-d, --debug').preset('foo'));8 program.parse(['-d'], { from: 'user' });9 assert.equal(program.opts().debug, 'foo');10});6 test('when boolean option with string preset used then value is preset', () => {7 const program = new Command();8 program.addOption(new Option('-d, --debug').preset('foo'));9 program.parse(['-d'], { from: 'user' });10 assert.equal(program.opts().debug, 'foo');11 });1212test('when boolean option with number preset used then value is preset', () => {13 const program = new Command();14 program.addOption(new Option('-d, --debug').preset(80));15 program.parse(['-d'], { from: 'user' });16 assert.equal(program.opts().debug, 80);17});13 test('when boolean option with number preset used then value is preset', () => {14 const program = new Command();15 program.addOption(new Option('-d, --debug').preset(80));16 program.parse(['-d'], { from: 'user' });17 assert.equal(program.opts().debug, 80);18 });1919test('when optional with string preset used then value is preset', () => {20 const program = new Command();21 program.addOption(new Option('-p, --port [port]').preset('foo'));22 program.parse(['-p'], { from: 'user' });23 assert.equal(program.opts().port, 'foo');24});20 test('when optional with string preset used then value is preset', () => {21 const program = new Command();22 program.addOption(new Option('-p, --port [port]').preset('foo'));23 program.parse(['-p'], { from: 'user' });24 assert.equal(program.opts().port, 'foo');25 });2626test('when optional with number preset used then value is preset', () => {27 const program = new Command();28 program.addOption(new Option('-p, --port [port]').preset(80));29 program.parse(['-p'], { from: 'user' });30 assert.equal(program.opts().port, 80);31});27 test('when optional with number preset used then value is preset', () => {28 const program = new Command();29 program.addOption(new Option('-p, --port [port]').preset(80));30 program.parse(['-p'], { from: 'user' });31 assert.equal(program.opts().port, 80);32 });3333test('when optional with string preset used with option-argument then value is as specified', () => {34 const program = new Command();35 program.addOption(new Option('-p, --port [port]').preset('foo'));36 program.parse(['-p', '1234'], { from: 'user' });37 assert.equal(program.opts().port, '1234');38});34 test('when optional with string preset used with option-argument then value is as specified', () => {35 const program = new Command();36 program.addOption(new Option('-p, --port [port]').preset('foo'));37 program.parse(['-p', '1234'], { from: 'user' });38 assert.equal(program.opts().port, '1234');39 });4040test('when optional with preset and coerce used then preset is coerced', () => {41 const program = new Command();42 program.addOption(43 new Option('-p, --port [port]').preset('4').argParser(parseFloat),44 );45 program.parse(['-p'], { from: 'user' });46 assert.equal(program.opts().port, 4);47});41 test('when optional with preset and coerce used then preset is coerced', () => {42 const program = new Command();43 program.addOption(44 new Option('-p, --port [port]').preset('4').argParser(parseFloat),45 );46 program.parse(['-p'], { from: 'user' });47 assert.equal(program.opts().port, 4);48 });4949test('when optional with preset and variadic used then preset is concatenated', () => {50 const program = new Command();51 program.addOption(new Option('-n, --name [name...]').preset('two'));52 program.parse(['-n', 'one', '-n', '-n', 'three'], { from: 'user' });53 assert.deepEqual(program.opts().name, ['one', 'two', 'three']);54});50 test('when optional with preset and variadic used then preset is concatenated', () => {51 const program = new Command();52 program.addOption(new Option('-n, --name [name...]').preset('two'));53 program.parse(['-n', 'one', '-n', '-n', 'three'], { from: 'user' });54 assert.deepEqual(program.opts().name, ['one', 'two', 'three']);55 });5656test('when negated with string preset used then value is preset', () => {57 const program = new Command();58 program.addOption(new Option('--no-colour').preset('foo'));59 program.parse(['--no-colour'], { from: 'user' });60 assert.equal(program.opts().colour, 'foo');57 test('when negated with string preset used then value is preset', () => {58 const program = new Command();59 program.addOption(new Option('--no-colour').preset('foo'));60 program.parse(['--no-colour'], { from: 'user' });61 assert.equal(program.opts().colour, 'foo');62 });63});
modified:tests/options.registerClash.test.js+1 added-1 removed
1const { Command, Option } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45describe('.option()', () => {5describe('registering clashing options', () => {6 test('when short option flag conflicts then throws', () => {7 assert.throws(8 () => {9 const program = new Command();
57 unmodified lines
modified:tests/options.required.test.js+2 added-2 removed
2 unmodified lines
3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56// option with required value, no default7describe('option with required value, no default', () => {7describe('option with required option-argument, no default', () => {8 test('when option not specified then value is undefined', () => {9 const program = new commander.Command();10 program.option('--cheese <type>', 'cheese type');11 program.parse(['node', 'test']);
24 unmodified lines
36 });37});3839// option with required value, with default40describe('option with required value, with default', () => {40describe('option with required option-argument, with default', () => {41 test('when option not specified then value is default', () => {42 const defaultValue = 'default';43 const program = new commander.Command();44 program.option('--cheese <type>', 'cheese type', defaultValue);
26 unmodified lines
modified:tests/options.twice.test.js+38 added-36 removed
1const { Command, Option } = require('../');2const { test } = require('node:test');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');45// Test that when option specified twice, second use wins.6// Seems pretty obvious for boolean options, but there was a bug before Commander v9.78describe('last repeated option wins', () => {8test('when boolean option used twice then value is true', () => {9 const program = new Command();10 program.option('-d, --debug');11 program.parse(['-d', '-d'], { from: 'user' });12 assert.equal(program.opts().debug, true);13});9 test('when boolean option used twice then value is true', () => {10 const program = new Command();11 program.option('-d, --debug');12 program.parse(['-d', '-d'], { from: 'user' });13 assert.equal(program.opts().debug, true);14 });1515test('when boolean option with default used twice then value is true', () => {16 const program = new Command();17 program.option('-d, --debug', 'description', 'foo');18 program.parse(['-d', '-d'], { from: 'user' });19 assert.equal(program.opts().debug, true);20});16 test('when boolean option with default used twice then value is true', () => {17 const program = new Command();18 program.option('-d, --debug', 'description', 'foo');19 program.parse(['-d', '-d'], { from: 'user' });20 assert.equal(program.opts().debug, true);21 });2222test('when boolean option with preset used twice then value is preset', () => {23 const program = new Command();24 program.addOption(new Option('-d, --debug').preset('foo'));25 program.parse(['-d', '-d'], { from: 'user' });26 assert.equal(program.opts().debug, 'foo');27});23 test('when boolean option with preset used twice then value is preset', () => {24 const program = new Command();25 program.addOption(new Option('-d, --debug').preset('foo'));26 program.parse(['-d', '-d'], { from: 'user' });27 assert.equal(program.opts().debug, 'foo');28 });2929test('when option with required argument used twice then value is from second use', () => {30 const program = new Command();31 program.option('-p, --port <port-number>');32 program.parse(['-p', '1', '-p', '2'], { from: 'user' });33 assert.equal(program.opts().port, '2');34});30 test('when option with required argument used twice then value is from second use', () => {31 const program = new Command();32 program.option('-p, --port <port-number>');33 program.parse(['-p', '1', '-p', '2'], { from: 'user' });34 assert.equal(program.opts().port, '2');35 });3636test('when option with optional argument used second time without value then value is true', () => {37 const program = new Command();38 program.option('--donate [amount]');39 program.parse(['--donate', '123', '--donate'], { from: 'user' });40 assert.equal(program.opts().donate, true);41});37 test('when option with optional argument used second time without value then value is true', () => {38 const program = new Command();39 program.option('--donate [amount]');40 program.parse(['--donate', '123', '--donate'], { from: 'user' });41 assert.equal(program.opts().donate, true);42 });4343test('when option with optional argument used second time with value then value is from second use', () => {44 const program = new Command();45 program.option('--donate [amount]');46 program.parse(['--donate', '--donate', '123'], { from: 'user' });47 assert.equal(program.opts().donate, '123');44 test('when option with optional argument used second time with value then value is from second use', () => {45 const program = new Command();46 program.option('--donate [amount]');47 program.parse(['--donate', '--donate', '123'], { from: 'user' });48 assert.equal(program.opts().donate, '123');49 });50});
modified:tests/options.values.test.js+2 added-2 removed
6 unmodified lines
78// options with required values can eat values starting with a dash, including just dash sometimes used as alias for stdin9//10// option with required value, using loop to test all matrix of values and tests11describe('option with required value', () => {11describe('option with required option-argument', () => {12 const valuesList = [['str'], ['80'], ['-'], ['-5'], ['--flag']];1314 for (const [value] of valuesList) {15 function createPortProgram() {
28 unmodified lines
44 }45});4647// option with optional value48describe('option with optional value', () => {48describe('option with optional option-argument', () => {49 function createPortProgram() {50 const program = new commander.Command();51 program.option('-p,--port [number]', 'specify port');52 return program;
36 unmodified lines
modified:tests/options.variadic.test.js+132 added-122 removed
1 unmodified line
2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');56describe('variadic options', () => {6describe('variadic option with required value', () => {7 test('when variadic with value missing then error', () => {8 const program = createTestCommand();9 program.option('-r,--required <value...>');7 describe('variadic option with required option-argument', () => {8 test('when variadic with value missing then error', () => {9 const program = createTestCommand();10 program.option('-r,--required <value...>');1111 assert.throws(() => {12 program.parse(['--required'], { from: 'user' });12 assert.throws(() => {13 program.parse(['--required'], { from: 'user' });14 });15 });14 });1616 test('when variadic with one value then set in array', () => {17 const program = new commander.Command();18 program.option('-r,--required <value...>');17 test('when variadic with one value then set in array', () => {18 const program = new commander.Command();19 program.option('-r,--required <value...>');2020 program.parse(['--required', 'one'], { from: 'user' });21 assert.deepEqual(program.opts().required, ['one']);22 });21 program.parse(['--required', 'one'], { from: 'user' });22 assert.deepEqual(program.opts().required, ['one']);23 });2424 test('when variadic with two values then set in array', () => {25 const program = new commander.Command();26 program.option('-r,--required <value...>');25 test('when variadic with two values then set in array', () => {26 const program = new commander.Command();27 program.option('-r,--required <value...>');2828 program.parse(['--required', 'one', 'two'], { from: 'user' });29 assert.deepEqual(program.opts().required, ['one', 'two']);30 });29 program.parse(['--required', 'one', 'two'], { from: 'user' });30 assert.deepEqual(program.opts().required, ['one', 'two']);31 });3232 test('when variadic with repeated values then set in array', () => {33 const program = new commander.Command();34 program.option('-r,--required <value...>');33 test('when variadic with repeated values then set in array', () => {34 const program = new commander.Command();35 program.option('-r,--required <value...>');3636 program.parse(['--required', 'one', '--required', 'two'], { from: 'user' });37 assert.deepEqual(program.opts().required, ['one', 'two']);38 });37 program.parse(['--required', 'one', '--required', 'two'], {38 from: 'user',39 });40 assert.deepEqual(program.opts().required, ['one', 'two']);41 });4240 test('when variadic used with choices and one value then set in array', () => {41 const program = new commander.Command();42 program.addOption(43 new commander.Option('-r,--required <value...>').choices(['one', 'two']),44 );43 test('when variadic used with choices and one value then set in array', () => {44 const program = new commander.Command();45 program.addOption(46 new commander.Option('-r,--required <value...>').choices([47 'one',48 'two',49 ]),50 );5146 program.parse(['--required', 'one'], { from: 'user' });47 assert.deepEqual(program.opts().required, ['one']);48 });52 program.parse(['--required', 'one'], { from: 'user' });53 assert.deepEqual(program.opts().required, ['one']);54 });5550 test('when variadic used with choices and two values then set in array', () => {51 const program = new commander.Command();52 program.addOption(53 new commander.Option('-r,--required <value...>').choices(['one', 'two']),54 );56 test('when variadic used with choices and two values then set in array', () => {57 const program = new commander.Command();58 program.addOption(59 new commander.Option('-r,--required <value...>').choices([60 'one',61 'two',62 ]),63 );6456 program.parse(['--required', 'one', 'two'], { from: 'user' });57 assert.deepEqual(program.opts().required, ['one', 'two']);58 });65 program.parse(['--required', 'one', 'two'], { from: 'user' });66 assert.deepEqual(program.opts().required, ['one', 'two']);67 });6860 test('when variadic with short combined argument then not variadic', () => {61 const program = new commander.Command();62 program.option('-r,--required <value...>').argument('[arg]');69 test('when variadic with short combined argument then not variadic', () => {70 const program = new commander.Command();71 program.option('-r,--required <value...>').argument('[arg]');7264 program.parse(['-rone', 'operand'], { from: 'user' });65 assert.deepEqual(program.opts().required, ['one']);66 });73 program.parse(['-rone', 'operand'], { from: 'user' });74 assert.deepEqual(program.opts().required, ['one']);75 });7668 test('when variadic with long combined argument then not variadic', () => {69 const program = new commander.Command();70 program.option('-r,--required <value...>').argument('[arg]');77 test('when variadic with long combined argument then not variadic', () => {78 const program = new commander.Command();79 program.option('-r,--required <value...>').argument('[arg]');8072 program.parse(['--required=one', 'operand'], { from: 'user' });73 assert.deepEqual(program.opts().required, ['one']);74 });81 program.parse(['--required=one', 'operand'], { from: 'user' });82 assert.deepEqual(program.opts().required, ['one']);83 });8476 test('when variadic with value followed by option then option not eaten', () => {77 const program = new commander.Command();78 program79 .option('-r,--required <value...>')80 .option('-f, --flag')81 .argument('[arg]');85 test('when variadic with value followed by option then option not eaten', () => {86 const program = new commander.Command();87 program88 .option('-r,--required <value...>')89 .option('-f, --flag')90 .argument('[arg]');9183 program.parse(['-r', 'one', '-f'], { from: 'user' });84 const opts = program.opts();85 assert.deepEqual(opts.required, ['one']);86 assert.equal(opts.flag, true);87 });92 program.parse(['-r', 'one', '-f'], { from: 'user' });93 const opts = program.opts();94 assert.deepEqual(opts.required, ['one']);95 assert.equal(opts.flag, true);96 });9789 test('when variadic with no value and default then set to default', () => {90 const program = new commander.Command();91 program.option(92 '-r,--required <value...>',93 'variadic description',94 'default',95 );98 test('when variadic with no value and default then set to default', () => {99 const program = new commander.Command();100 program.option(101 '-r,--required <value...>',102 'variadic description',103 'default',104 );10597 program.parse([], { from: 'user' });98 assert.equal(program.opts().required, 'default');99 });106 program.parse([], { from: 'user' });107 assert.equal(program.opts().required, 'default');108 });109101 test('when variadic with coercion then coercion sets value', () => {102 const program = new commander.Command();103 program.option(104 '-r,--required <value...>',105 'variadic description',106 parseFloat,107 );110 test('when variadic with coercion then coercion sets value', () => {111 const program = new commander.Command();112 program.option(113 '-r,--required <value...>',114 'variadic description',115 parseFloat,116 );117109 // variadic processing reads the multiple values, but up to custom coercion what it does.110 program.parse(['--required', '1e2', '1e3'], { from: 'user' });111 assert.equal(program.opts().required, 1000);118 // variadic processing reads the multiple values, but up to custom coercion what it does.119 program.parse(['--required', '1e2', '1e3'], { from: 'user' });120 assert.equal(program.opts().required, 1000);121 });122 });113});123115// Not retesting everything, but do some tests on variadic with optional116describe('variadic option with optional value', () => {117 test('when variadic not specified then value undefined', () => {118 const program = new commander.Command();119 program.option('-o,--optional [value...]');124 // Not retesting everything, but do some tests on variadic with optional125 describe('variadic option with optional option-argument', () => {126 test('when variadic not specified then value undefined', () => {127 const program = new commander.Command();128 program.option('-o,--optional [value...]');129121 program.parse([], { from: 'user' });122 assert.equal(program.opts().optional, undefined);123 });130 program.parse([], { from: 'user' });131 assert.equal(program.opts().optional, undefined);132 });133125 test('when variadic used as boolean flag then value true', () => {126 const program = new commander.Command();127 program.option('-o,--optional [value...]');134 test('when variadic used as boolean flag then value true', () => {135 const program = new commander.Command();136 program.option('-o,--optional [value...]');137129 program.parse(['--optional'], { from: 'user' });130 assert.equal(program.opts().optional, true);131 });138 program.parse(['--optional'], { from: 'user' });139 assert.equal(program.opts().optional, true);140 });141133 test('when variadic with one value then set in array', () => {134 const program = new commander.Command();135 program.option('-o,--optional [value...]');142 test('when variadic with one value then set in array', () => {143 const program = new commander.Command();144 program.option('-o,--optional [value...]');145137 program.parse(['--optional', 'one'], { from: 'user' });138 assert.deepEqual(program.opts().optional, ['one']);139 });146 program.parse(['--optional', 'one'], { from: 'user' });147 assert.deepEqual(program.opts().optional, ['one']);148 });149141 test('when variadic with two values then set in array', () => {142 const program = new commander.Command();143 program.option('-o,--optional [value...]');150 test('when variadic with two values then set in array', () => {151 const program = new commander.Command();152 program.option('-o,--optional [value...]');153145 program.parse(['--optional', 'one', 'two'], { from: 'user' });146 assert.deepEqual(program.opts().optional, ['one', 'two']);154 program.parse(['--optional', 'one', 'two'], { from: 'user' });155 assert.deepEqual(program.opts().optional, ['one', 'two']);156 });157 });148});158150describe('variadic special cases', () => {151 test('when option flags has word character before dots then is variadic', () => {152 const program = new commander.Command();153 program.option('-c,--comma [value...]');159 describe('variadic special cases', () => {160 test('when option flags has word character before dots then is variadic', () => {161 const program = new commander.Command();162 program.option('-c,--comma [value...]');163155 assert.equal(program.options[0].variadic, true);156 });164 assert.equal(program.options[0].variadic, true);165 });166158 test('when option flags has special characters before dots then not variadic', () => {159 // This might be used to describe coercion for comma separated values, and is not variadic.160 const program = new commander.Command();161 program.option('-c,--comma [value,...]');167 test('when option flags has special characters before dots then not variadic', () => {168 // This might be used to describe coercion for comma separated values, and is not variadic.169 const program = new commander.Command();170 program.option('-c,--comma [value,...]');171163 assert.equal(program.options[0].variadic, false);172 assert.equal(program.options[0].variadic, false);173 });174 });175});
modified:tests/options.version.test.js+1 added-1 removed
2 unmodified lines
3const assert = require('node:assert/strict');45// Test .version. Using exitOverride to check behaviour (instead of mocking process.exit).67describe('.version', () => {7describe('Command.version()', () => {8 test('when no .version and specify --version then unknown option error', () => {9 const program = new commander.Command();10 program.exitOverride().configureOutput({ writeErr: () => {} });11
172 unmodified lines