-
Notifications
You must be signed in to change notification settings - Fork 382
Expand file tree
/
Copy pathCli.spec.ts
More file actions
2101 lines (1919 loc) · 68.9 KB
/
Cli.spec.ts
File metadata and controls
2101 lines (1919 loc) · 68.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import assert from 'assert';
import chalk from 'chalk';
import Table from 'easy-table';
import fs from 'fs';
import inquirer from 'inquirer';
import { createRequire } from 'module';
import os from 'os';
import path from 'path';
import sinon from 'sinon';
import url from 'url';
import Command, { CommandError, CommandErrorWithOutput } from '../Command.js';
import AnonymousCommand from '../m365/base/AnonymousCommand.js';
import cliCompletionUpdateCommand from '../m365/cli/commands/completion/completion-clink-update.js';
import { settingsNames } from '../settingsNames.js';
import { telemetry } from '../telemetry.js';
import { md } from '../utils/md.js';
import { pid } from '../utils/pid.js';
import { session } from '../utils/session.js';
import { sinonUtil } from '../utils/sinonUtil.js';
import { Cli, CommandOutput } from './Cli.js';
import { Logger } from './Logger.js';
const require = createRequire(import.meta.url);
const packageJSON = require('../../package.json');
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
class MockCommand extends AnonymousCommand {
public get name(): string {
return 'cli mock';
}
public get description(): string {
return 'Mock command';
}
constructor() {
super();
this.options.push(
{
option: '-x, --parameterX <parameterX>'
},
{
option: '-y, --parameterY [parameterY]'
}
);
this.types.string.push('x', 'y');
}
public async commandAction(logger: Logger, args: any): Promise<void> {
await logger.log(args.options.parameterX);
}
}
class MockCommandWithOptionSets extends AnonymousCommand {
public get name(): string {
return 'cli mock optionsets';
}
public get description(): string {
return 'Mock command with option sets';
}
constructor() {
super();
this.options.push(
{
option: '--opt1 [name]'
},
{
option: '--opt2 [name]'
},
{
option: '--opt3 [name]'
},
{
option: '--opt4 [name]'
},
{
option: '--opt5 [name]'
},
{
option: '--opt6 [name]'
}
);
this.optionSets.push(
{ options: ['opt1', 'opt2'] },
{
options: ['opt3', 'opt4'],
runsWhen: (args) => typeof args.options.opt2 !== 'undefined' // validate when opt2 is set
},
{
options: ['opt5', 'opt6'],
runsWhen: (args) => { return args.options.opt5 || args.options.opt6; } // validate when opt5 or opt6 is set
}
);
}
public async commandAction(): Promise<void> {
}
}
class MockCommandWithAlias extends AnonymousCommand {
public get name(): string {
return 'cli mock alias';
}
public get description(): string {
return 'Mock command with alias';
}
public alias(): string[] {
return ['cli mock alt'];
}
public async commandAction(): Promise<void> {
}
}
class MockCommandWithValidation extends AnonymousCommand {
public get name(): string {
return 'cli mock1 validation';
}
public get description(): string {
return 'Mock command with validation';
}
constructor() {
super();
this.options.push(
{
option: '-x, --parameterX <parameterX>'
},
{
option: '-y, --parameterY [parameterY]'
}
);
}
public async commandAction(): Promise<void> {
}
}
class MockCommandWithBooleanRewrite extends AnonymousCommand {
public get name(): string {
return 'cli mock boolean rewrite';
}
public get description(): string {
return 'Mock command with boolean rewrite';
}
constructor() {
super();
this.options.push(
{
option: '-x, --booleanParameterX [booleanParameterX]'
},
{
option: '-y, --booleanParameterY [booleanParameterY]'
}
);
this.types.boolean.push('x', 'booleanParameterX', 'y', 'booleanParameterY');
}
public async commandAction(logger: Logger, args: any): Promise<void> {
await logger.log(`booleanParameterX: ${args.options.booleanParameterX}`);
await logger.log(`booleanParameterY: ${args.options.booleanParameterY}`);
}
}
class MockCommandWithPrompt extends AnonymousCommand {
public get name(): string {
return 'cli mock prompt';
}
public get description(): string {
return 'Mock command with prompt';
}
public async commandAction(): Promise<void> {
await Cli.prompt({
type: 'confirm',
name: 'continue',
default: false,
message: `Continue?`
});
}
}
class MockCommandWithHandleMultipleResultsFound extends AnonymousCommand {
public get name(): string {
return 'cli mock interactive prompt';
}
public get description(): string {
return 'Mock command with interactive prompt';
}
public async commandAction(): Promise<void> {
await Cli.handleMultipleResultsFound(`Multiple values with name found. Pick one`, `Multiple values with name found.`, { '1': { 'id': '1', 'title': 'Option1' }, '2': { 'id': '2', 'title': 'Option2' } });
}
}
class MockCommandWithOutput extends AnonymousCommand {
public get name(): string {
return 'cli mock output';
}
public get description(): string {
return 'Mock command with output';
}
public async commandAction(logger: Logger): Promise<void> {
await logger.log('Command output');
}
}
class MockCommandWithRawOutput extends AnonymousCommand {
public get name(): string {
return 'cli mock output';
}
public get description(): string {
return 'Mock command with output';
}
public async commandAction(logger: Logger): Promise<void> {
if (this.debug) {
await logger.logToStderr('Debug output');
}
await logger.logRaw('Raw output');
}
}
describe('Cli', () => {
let cli: Cli;
let rootFolder: string;
let cliLogStub: sinon.SinonStub;
let cliErrorStub: sinon.SinonStub;
let cliFormatOutputSpy: sinon.SinonSpy;
let processExitStub: sinon.SinonStub;
let md2plainSpy: sinon.SinonSpy;
let mockCommandActionSpy: sinon.SinonSpy;
let mockCommand: Command;
let mockCommandWithOptionSets: Command;
let mockCommandWithAlias: Command;
let mockCommandWithValidation: Command;
let log: string[] = [];
let mockCommandWithBooleanRewrite: Command;
before(() => {
sinon.stub(telemetry, 'trackEvent').callsFake(() => { });
sinon.stub(pid, 'getProcessName').callsFake(() => '');
sinon.stub(session, 'getId').callsFake(() => '');
cliLogStub = sinon.stub((Cli as any), 'log').callsFake(message => {
log.push(message as string ?? '');
});
cliErrorStub = sinon.stub((Cli as any), 'error');
cliFormatOutputSpy = sinon.spy((Cli as any), 'formatOutput');
processExitStub = sinon.stub(process, 'exit').callsFake((() => { }) as any);
md2plainSpy = sinon.spy(md, 'md2plain');
mockCommand = new MockCommand();
mockCommandWithAlias = new MockCommandWithAlias();
mockCommandWithBooleanRewrite = new MockCommandWithBooleanRewrite();
mockCommandWithValidation = new MockCommandWithValidation();
mockCommandWithOptionSets = new MockCommandWithOptionSets();
mockCommandActionSpy = sinon.spy(mockCommand, 'action');
return new Promise((resolve) => {
fs.realpath(__dirname, (err: NodeJS.ErrnoException | null, resolvedPath: string): void => {
rootFolder = resolvedPath;
resolve(undefined);
});
});
});
beforeEach(() => {
log = [];
cli = Cli.getInstance();
(cli as any).loadCommand(mockCommand);
(cli as any).loadCommand(mockCommandWithOptionSets);
(cli as any).loadCommand(mockCommandWithAlias);
(cli as any).loadCommand(mockCommandWithValidation);
(cli as any).loadCommand(cliCompletionUpdateCommand);
(cli as any).loadCommand(mockCommandWithBooleanRewrite);
});
afterEach(() => {
(Cli as any).instance = undefined;
cliLogStub.resetHistory();
cliErrorStub.resetHistory();
cliFormatOutputSpy.resetHistory();
processExitStub.reset();
md2plainSpy.resetHistory();
mockCommandActionSpy.resetHistory();
sinonUtil.restore([
Cli.executeCommand,
fs.existsSync,
fs.readFileSync,
inquirer.prompt,
// eslint-disable-next-line no-console
console.log,
// eslint-disable-next-line no-console
console.error,
mockCommand.validate,
mockCommandWithValidation.action,
mockCommandWithValidation.validate,
mockCommand.commandAction,
mockCommand.processOptions,
Cli.prompt,
cli.getSettingWithDefaultValue
]);
});
after(() => {
sinon.restore();
});
it('shows generic help when no command specified', (done) => {
cli
.execute(rootFolder, [])
.then(_ => {
try {
assert(cliLogStub.calledWith(`CLI for Microsoft 365 v${packageJSON.version}`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('exits with 0 code when no command specified', (done) => {
cli
.execute(rootFolder, [])
.then(_ => {
try {
assert(processExitStub.calledWith(0));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows generic help when help command and no command name specified', (done) => {
cli
.execute(rootFolder, ['help'])
.then(_ => {
try {
assert(cliLogStub.calledWith(`CLI for Microsoft 365 v${packageJSON.version}`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows generic help when --help option specified', (done) => {
cli
.execute(rootFolder, ['--help'])
.then(_ => {
try {
assert(cliLogStub.calledWith(`CLI for Microsoft 365 v${packageJSON.version}`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows generic help when -h option specified', (done) => {
cli
.execute(rootFolder, ['-h'])
.then(_ => {
try {
assert(cliLogStub.calledWith(`CLI for Microsoft 365 v${packageJSON.version}`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows help for the specific command when help specified followed by a valid command name', (done) => {
sinon.stub(fs, 'existsSync').callsFake((path) => path.toString().endsWith('.mdx'));
const originalFsReadFileSync = fs.readFileSync;
sinon.stub(fs, 'readFileSync').callsFake(() => originalFsReadFileSync(path.join(rootFolder, '..', '..', 'docs', 'docs', 'cmd', 'cli', 'completion', 'completion-clink-update.mdx'), 'utf8'));
cli
.execute(rootFolder, ['help', 'cli', 'mock'])
.then(_ => {
try {
assert(md2plainSpy.called);
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows help for the specific command when valid command name specified followed by --help', (done) => {
sinon.stub(fs, 'existsSync').callsFake((path) => path.toString().endsWith('.mdx'));
const originalFsReadFileSync = fs.readFileSync;
sinon.stub(fs, 'readFileSync').callsFake(() => originalFsReadFileSync(path.join(rootFolder, '..', '..', 'docs', 'docs', 'cmd', 'cli', 'completion', 'completion-clink-update.mdx'), 'utf8'));
cli
.execute(rootFolder, ['cli', 'mock', '--help'])
.then(_ => {
try {
assert(md2plainSpy.called);
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows help for the specific command when valid command name specified followed by -h', (done) => {
sinon.stub(fs, 'existsSync').callsFake((path) => path.toString().endsWith('.mdx'));
const originalFsReadFileSync = fs.readFileSync;
sinon.stub(fs, 'readFileSync').callsFake(() => originalFsReadFileSync(path.join(rootFolder, '..', '..', 'docs', 'docs', 'cmd', 'cli', 'completion', 'completion-clink-update.mdx'), 'utf8'));
cli
.execute(rootFolder, ['cli', 'mock', '-h'])
.then(_ => {
try {
assert(md2plainSpy.called);
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows help for the specific command when valid command name specified followed by -h (single-word command)', (done) => {
cli
.execute(path.join(rootFolder, '..', 'm365'), ['status', '-h'])
.then(_ => {
try {
assert(md2plainSpy.called);
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows help for the specific command when help specified followed by a valid command alias', (done) => {
sinon.stub(fs, 'existsSync').callsFake((path) => path.toString().endsWith('.mdx'));
const originalFsReadFileSync = fs.readFileSync;
sinon.stub(fs, 'readFileSync').callsFake(() => originalFsReadFileSync(path.join(rootFolder, '..', '..', 'docs', 'docs', 'cmd', 'cli', 'completion', 'completion-clink-update.mdx'), 'utf8'));
cli
.execute(rootFolder, ['help', 'cli', 'mock', 'alt'])
.then(_ => {
try {
assert(cliLogStub.called);
assert(!cliLogStub.calledWith(`CLI for Microsoft 365 v${packageJSON.version}`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows full help when specified -h with a number', (done) => {
sinon.stub(cli, 'getSettingWithDefaultValue').callsFake(() => 'full');
cli
.execute(rootFolder, ['cli', 'completion', 'clink', 'update', '-h', '1'])
.then(_ => {
try {
assert(log.some(l => l.indexOf('OPTIONS') > -1), 'Options section not found');
assert(log.some(l => l.indexOf('EXAMPLES') > -1), 'Examples section not found');
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows full help when specified -h with full', (done) => {
cli
.execute(rootFolder, ['cli', 'completion', 'clink', 'update', '-h', 'full'])
.then(_ => {
try {
assert(log.some(l => l.indexOf('OPTIONS') > -1), 'Options section not found');
assert(log.some(l => l.indexOf('EXAMPLES') > -1), 'Examples section not found');
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows help with options section when specified -h with options', (done) => {
cli
.execute(rootFolder, ['cli', 'completion', 'clink', 'update', '-h', 'options'])
.then(_ => {
try {
assert(log.some(l => l.indexOf('OPTIONS') > -1), 'Options section not found');
assert(log.some(l => l.indexOf('EXAMPLES') === -1), 'Examples section found');
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows help with examples section when specified -h with examples', (done) => {
cli
.execute(rootFolder, ['cli', 'completion', 'clink', 'update', '-h', 'examples'])
.then(_ => {
try {
assert(log.some(l => l.indexOf('OPTIONS') === -1), 'Options section found');
assert(log.some(l => l.indexOf('EXAMPLES') > -1), 'Examples section not found');
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows help with remarks section when specified -h with remarks', (done) => {
cli
.execute(rootFolder, ['cli', 'completion', 'clink', 'update', '-h', 'remarks'])
.then(_ => {
try {
assert(log.some(l => l.indexOf('REMARKS') > -1), 'Remarks section not found');
assert(log.some(l => l.indexOf('OPTIONS') === -1), 'Options section found');
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it('shows error when specified -h with an invalid value', (done) => {
cli
.execute(rootFolder, ['cli', 'completion', 'clink', 'update', '-h', 'invalid'])
.then(_ => done('Expected error to be thrown'), _ => {
try {
assert(cliErrorStub.getCalls().some(c => c.firstArg.indexOf('Unknown help mode invalid. Allowed values are') > -1));
done();
}
catch (e) {
done(e);
}
});
});
it(`passes options validation if the command doesn't allow unknown options and specified options match command options`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', '-x', '123', '-y', '456'])
.then(_ => {
try {
assert(mockCommandActionSpy.called);
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`succeeds running with truthy/falsy values 'true' and 'false'`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'boolean', 'rewrite', '--booleanParameterX', 'true', '--booleanParameterY', 'false', '--output', 'text'])
.then(_ => {
try {
assert(cliLogStub.calledWith(`booleanParameterX: true`));
assert(cliLogStub.calledWith(`booleanParameterY: false`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`rewrites a truthy/falsy values '1' and '0' to 'true' and 'false' respectively`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'boolean', 'rewrite', '--booleanParameterX', '1', '--booleanParameterY', '0', '--output', 'text'])
.then(_ => {
try {
assert(cliLogStub.calledWith(`booleanParameterX: true`));
assert(cliLogStub.calledWith(`booleanParameterY: false`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`rewrites a truthy/falsy values 'on' and 'off' to 'true' and 'false' respectively`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'boolean', 'rewrite', '--booleanParameterX', 'on', '--booleanParameterY', 'off', '--output', 'text'])
.then(_ => {
try {
assert(cliLogStub.calledWith(`booleanParameterX: true`));
assert(cliLogStub.calledWith(`booleanParameterY: false`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`rewrites a truthy/falsy values 'yes' and 'no' to 'true' and 'false' respectively`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'boolean', 'rewrite', '--booleanParameterX', 'yes', '--booleanParameterY', 'no', '--output', 'text'])
.then(_ => {
try {
assert(cliLogStub.calledWith(`booleanParameterX: true`));
assert(cliLogStub.calledWith(`booleanParameterY: false`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`rewrites a truthy/falsy values 'True' and 'False' to 'true' and 'false' respectively`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'boolean', 'rewrite', '--booleanParameterX', 'True', '--booleanParameterY', 'False', '--output', 'text'])
.then(_ => {
try {
assert(cliLogStub.calledWith(`booleanParameterX: true`));
assert(cliLogStub.calledWith(`booleanParameterY: false`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`rewrites a truthy/falsy values 'yes' and 'no' to 'true' and 'false' respectively (using shorts)`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'boolean', 'rewrite', '-x', 'yes', '-y', 'no', '--output', 'text'])
.then(_ => {
try {
assert(cliLogStub.calledWith(`booleanParameterX: true`));
assert(cliLogStub.calledWith(`booleanParameterY: false`));
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`shows error when a boolean option does not contain a correct truthy/falsy value`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'boolean', 'rewrite', '--booleanParameterX', 'folse'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
assert(cliErrorStub.calledWith(chalk.red(`Error: The value 'folse' for option '--booleanParameterX' is not a valid boolean`)));
done();
});
});
it(`fails options validation if the command doesn't allow unknown options and specified options match command options`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', '-x', '123', '--paramZ'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
try {
assert(cliErrorStub.calledWith(chalk.red(`Error: Invalid option: 'paramZ'${os.EOL}`)));
done();
}
catch (e) {
done(e);
}
});
});
it(`doesn't execute command action when option validation failed`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', '-x', '123', '--paramZ'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
try {
assert(mockCommandActionSpy.notCalled);
done();
}
catch (e) {
done(e);
}
});
});
it(`exits with exit code 1 when option validation failed`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', '-x', '123', '--paramZ'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
try {
assert(processExitStub.calledWith(1));
done();
}
catch (e) {
done(e);
}
});
});
it(`does not prompt and fails validation if a required option is missing`, (done) => {
sinon.stub(Cli.getInstance(), 'getSettingWithDefaultValue').callsFake((settingName, defaultValue) => {
if (settingName === settingsNames.prompt) {
return undefined;
}
return defaultValue;
});
cli
.execute(rootFolder, ['cli', 'mock'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
try {
assert(cliErrorStub.calledWith(chalk.red(`Error: Required option parameterX not specified`)));
done();
}
catch (e) {
done(e);
}
});
});
it(`shows validation error when no option from a required set is specified`, (done) => {
sinon.stub(cli, 'getSettingWithDefaultValue').callsFake(((settingName, defaultValue) => defaultValue));
cli
.execute(rootFolder, ['cli', 'mock', 'optionsets'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
try {
assert(cliErrorStub.calledWith(chalk.red('Error: Specify one of the following options: opt1, opt2.')));
done();
}
catch (e) {
done(e);
}
});
});
it(`shows validation error when multiple options from a required set are specified`, (done) => {
sinon.stub(cli, 'getSettingWithDefaultValue').callsFake(((settingName, defaultValue) => defaultValue));
cli
.execute(rootFolder, ['cli', 'mock', 'optionsets', '--opt1', 'testvalue', '--opt2', 'testvalue'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
try {
assert(cliErrorStub.calledWith(chalk.red('Error: Specify one of the following options: opt1, opt2, but not multiple.')));
done();
}
catch (e) {
done(e);
}
});
});
it(`passes validation when one option from a required set is specified`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'optionsets', '--opt1', 'testvalue'])
.then(_ => {
try {
assert(cliErrorStub.notCalled);
done();
}
catch (e) {
done(e);
}
}, _ => done('Promise rejected while success expected'));
});
it(`shows validation error when no option from a dependent set is set`, (done) => {
sinon.stub(cli, 'getSettingWithDefaultValue').callsFake(((settingName, defaultValue) => defaultValue));
cli
.execute(rootFolder, ['cli', 'mock', 'optionsets', '--opt2', 'testvalue'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
try {
assert(cliErrorStub.calledWith(chalk.red('Error: Specify one of the following options: opt3, opt4.')));
done();
}
catch (e) {
done(e);
}
});
});
it(`passes validation when one option from a dependent set is specified`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'optionsets', '--opt2', 'testvalue', '--opt3', 'testvalue'])
.then(_ => {
try {
assert(cliErrorStub.notCalled);
done();
}
catch (e) {
done(e);
}
}, _ => done('Promise rejected while success expected'));
});
it(`shows validation error when multiple options from an optional set are specified`, (done) => {
sinon.stub(cli, 'getSettingWithDefaultValue').callsFake(((settingName, defaultValue) => defaultValue));
cli
.execute(rootFolder, ['cli', 'mock', 'optionsets', '--opt1', 'testvalue', '--opt5', 'testvalue', '--opt6', 'testvalue'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
try {
assert(cliErrorStub.calledWith(chalk.red('Error: Specify one of the following options: opt5, opt6, but not multiple.')));
done();
}
catch (e) {
done(e);
}
});
});
it(`passes validation when one option from an optional set is specified`, (done) => {
cli
.execute(rootFolder, ['cli', 'mock', 'optionsets', '--opt2', 'testvalue', '--opt3', 'testvalue', '--opt5', 'testvalue'])
.then(_ => {
try {
assert(cliErrorStub.notCalled);
done();
}
catch (e) {
done(e);
}
}, _ => done('Promise rejected while success expected'));
});
it(`prompts for required options`, (done) => {
const promptStub: sinon.SinonStub = sinon.stub(inquirer, 'prompt').callsFake(() => Promise.resolve({ missingRequireOptionValue: "test" }) as any);
sinon.stub(Cli.getInstance(), 'getSettingWithDefaultValue').callsFake((settingName, defaultValue) => {
if (settingName === settingsNames.prompt) {
return 'true';
}
return defaultValue;
});
cli
.execute(rootFolder, ['cli', 'mock'])
.then(_ => {
try {
assert(promptStub.called);
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`prompts for optionset name and value when optionset not specified`, async () => {
let firstOptionValue = '', secondOptionValue = '';
const promptStub: sinon.SinonStub = sinon.stub(inquirer, 'prompt').callsFake((opts: any, _) => {
if (opts.type === 'list' && opts.name === 'missingRequiredOptionName') {
firstOptionValue = opts.choices[0];
secondOptionValue = opts.choices[1];
return { missingRequiredOptionName: opts.choices[0] } as any;
}
if (opts.name === 'missingRequiredOptionValue') {
return { missingRequiredOptionValue: 'Test 123' } as any;
}
throw 'Specific prompt not found';
});
sinon.stub(Cli.getInstance(), 'getSettingWithDefaultValue').callsFake((settingName, defaultValue) => {
if (settingName === settingsNames.prompt) {
return 'true';
}
return defaultValue;
});
await cli.execute(rootFolder, ['cli', 'mock', 'optionsets']);
assert.strictEqual(promptStub.firstCall.args[0].choices[0], firstOptionValue);
assert.strictEqual(promptStub.firstCall.args[0].choices[1], secondOptionValue);
assert.strictEqual(promptStub.lastCall.args[0].message, `${firstOptionValue}:`);
assert(promptStub.calledTwice);
});
it(`prompts to choose which option you wish to use when multiple options in a specific optionset are specified`, async () => {
let firstOptionValue = '', secondOptionValue = '';
const promptStub: sinon.SinonStub = sinon.stub(inquirer, 'prompt').callsFake((opts: any, _) => {
if (opts.type === 'list' && opts.name === 'missingRequiredOptionName') {
firstOptionValue = opts.choices[0];
secondOptionValue = opts.choices[1];
return { missingRequiredOptionName: opts.choices[0] } as any;
}
throw 'Specific prompt not found';
});
sinon.stub(Cli.getInstance(), 'getSettingWithDefaultValue').callsFake((settingName, defaultValue) => {
if (settingName === settingsNames.prompt) {
return 'true';
}
return defaultValue;
});
await cli.execute(rootFolder, ['cli', 'mock', 'optionsets', '--opt1', 'testvalue', '--opt2', 'testvalue']);
assert.strictEqual(promptStub.lastCall.args[0].message, `Option to use:`);
assert.strictEqual(promptStub.lastCall.args[0].choices[0], firstOptionValue);
assert.strictEqual(promptStub.lastCall.args[0].choices[1], secondOptionValue);
assert(promptStub.calledOnce);
});
it(`prompts to choose runsWhen option from optionSet when dependant option is set and prompts for the value`, async () => {
let firstOptionValue = '', secondOptionValue = '';
const promptStub: sinon.SinonStub = sinon.stub(inquirer, 'prompt').callsFake((opts: any, _) => {
if (opts.type === 'list' && opts.name === 'missingRequiredOptionName') {
firstOptionValue = opts.choices[0];
secondOptionValue = opts.choices[1];
return { missingRequiredOptionName: opts.choices[0] } as any;
}
if (opts.name === 'missingRequiredOptionValue') {
return { missingRequiredOptionValue: 'Test 123' } as any;
}
throw 'Specific prompt not found';
});
sinon.stub(Cli.getInstance(), 'getSettingWithDefaultValue').callsFake((settingName, defaultValue) => {
if (settingName === settingsNames.prompt) {
return 'true';
}
return defaultValue;
});
await cli.execute(rootFolder, ['cli', 'mock', 'optionsets', '--opt2', 'testvalue']);
assert.strictEqual(promptStub.firstCall.args[0].message, `Option to use:`);
assert.strictEqual(promptStub.firstCall.args[0].choices[0], firstOptionValue);
assert.strictEqual(promptStub.firstCall.args[0].choices[1], secondOptionValue);
assert(promptStub.calledTwice);
});
it(`prompts to pick one of the options from an optionSet when runsWhen condition is matched`, async () => {
let firstOptionValue = '', secondOptionValue = '';
const promptStub: sinon.SinonStub = sinon.stub(inquirer, 'prompt').callsFake((opts: any, _) => {
if (opts.type === 'list' && opts.name === 'missingRequiredOptionName') {
firstOptionValue = opts.choices[0];
secondOptionValue = opts.choices[1];
return { missingRequiredOptionName: opts.choices[0] } as any;
}
throw 'Specific prompt not found';
});
sinon.stub(Cli.getInstance(), 'getSettingWithDefaultValue').callsFake((settingName, defaultValue) => {
if (settingName === settingsNames.prompt) {
return 'true';
}
return defaultValue;
});
await cli.execute(rootFolder, ['cli', 'mock', 'optionsets', '--opt2', 'testvalue', '--opt3', 'opt 3', '--opt4', 'opt 4']);
assert.strictEqual(promptStub.lastCall.args[0].choices[0], firstOptionValue);
assert.strictEqual(promptStub.lastCall.args[0].choices[1], secondOptionValue);
assert(promptStub.calledOnce);
});
it(`calls command's validation method when defined`, (done) => {
const mockCommandValidateSpy: sinon.SinonSpy = sinon.spy(mockCommandWithValidation, 'validate');
cli
.execute(rootFolder, ['cli', 'mock1', 'validation', '-x', '123'])
.then(_ => {
try {
assert(mockCommandValidateSpy.called);
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`passes validation when the command's validate method returns true`, (done) => {
sinon.stub(mockCommandWithValidation, 'validate').callsFake(() => Promise.resolve(true));
const mockCommandWithValidationActionSpy: sinon.SinonSpy = sinon.spy(mockCommandWithValidation, 'action');
cli
.execute(rootFolder, ['cli', 'mock1', 'validation', '-x', '123'])
.then(_ => {
try {
assert(mockCommandWithValidationActionSpy.called);
done();
}
catch (e) {
done(e);
}
}, e => done(e));
});
it(`fails validation when the command's validate method returns a string`, (done) => {
sinon.stub(mockCommandWithValidation, 'validate').callsFake(() => Promise.resolve('Error'));
const mockCommandWithValidationActionSpy: sinon.SinonSpy = sinon.spy(mockCommandWithValidation, 'action');
cli
.execute(rootFolder, ['cli', 'mock1', 'validation', '-x', '123'])
.then(_ => done('Promise fulfilled while error expected'), _ => {
try {
assert(mockCommandWithValidationActionSpy.notCalled);
done();