-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathtest_argparse.js
5777 lines (4756 loc) · 187 KB
/
test_argparse.js
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
// Port of python's argparse module, version 3.9.0:
// https://github.com/python/cpython/blob/v3.9.0rc1/Lib/test/test_argparse.py
// Copyright (C) 2010-2020 Python Software Foundation.
// Copyright (C) 2020 argparse.js authors
/* global describe, it, before, after */
/* eslint-disable quotes, new-cap, new-parens, no-extra-semi, comma-dangle */
// eslint-disable-next-line strict
'use strict'
const assert = require('assert')
const fs = require('fs')
const os = require('os')
const path = require('path')
const stream = require('stream')
const util = require('util')
const argparse = require('../')
const textwrap = require('../lib/textwrap')
const sub = require('../lib/sub')
class JSTestCase {
run() {
describe(this.constructor.name, () => {
for (let method of this) {
if (method === 'setUp') {
before(() => this[method]())
} else if (method === 'tearDown') {
after(() => this[method]())
} else if (typeof method === 'string' && method.startsWith('skip_test') &&
this[method] !== undefined) {
it.skip(method, () => this[method]())
} else if (typeof method === 'string' && method.startsWith('test') &&
this[method] !== undefined) {
it(method, () => this[method]())
}
}
})
}
* [Symbol.iterator]() {
/* eslint-disable consistent-this */
let self = this
let member_names = new Set()
while (self) {
for (let k of Reflect.ownKeys(self)) member_names.add(k)
self = Object.getPrototypeOf(self)
}
yield* Array.from(member_names)
/* eslint-enable consistent-this */
}
assertEqual(expected, actual) { assert.deepStrictEqual(actual, expected) }
assertNotEqual(expected, actual) { assert.notDeepStrictEqual(actual, expected) }
assertIsNone(value) { assert.strictEqual(value, undefined) }
assertRegex(string, regex) { assert.match(string, regex) }
assertNotRegex(string, regex) { assert.doesNotMatch(string, regex) }
assertIn(key, object) { assert(key in object) }
assertNotIn(key, object) { assert(!(key in object)) }
assertRaises(error, fn) {
let _err
assert.throws(() => {
try {
fn()
} catch (err) {
_err = err
throw err
}
}, error)
return { exception: _err }
}
}
class StdIOBuffer extends stream.Writable {
constructor() {
super()
this.buffer = []
}
_write(chunk, enc, callback) {
this.buffer.push(chunk)
callback()
}
getvalue() {
return Buffer.concat(this.buffer).toString('utf8')
}
}
class TestCase extends JSTestCase {
setUp() {
// The tests assume that line wrapping occurs at 80 columns, but this
// behaviour can be overridden by setting the COLUMNS environment
// variable. To ensure that this width is used, set COLUMNS to 80.
process.env.COLUMNS = '80'
}
}
function TempDirMixin(cls) {
return class TempDirMixin extends cls {
setUp() {
this.temp_dir = path.join(os.tmpdir(), sub('test_argparse_%s', Math.random()))
this.old_dir = process.cwd()
fs.mkdirSync(this.temp_dir)
process.chdir(this.temp_dir)
}
tearDown() {
process.chdir(this.old_dir)
fs.rmdirSync(this.temp_dir, { recursive: true })
}
create_readonly_file(filename) {
let file_path = path.join(this.temp_dir, filename)
fs.writeFileSync(file_path, filename)
fs.chmodSync(file_path, 0o400)
}
}
}
function Sig(...args) {
return args
}
function NS(dict) {
return argparse.Namespace(dict)
}
class ArgumentParserError extends Error {
constructor(message, stdout, stderr, error_code) {
super()
this.m = message
this.stdout = stdout
this.stderr = stderr
this.error_code = error_code
this.message = this.toString()
}
toString() {
return '(' + [ this.m, this.stdout, this.stderr, this.error_code ].join(', ') + ')'
}
}
class SystemExit extends Error {
constructor(code) {
super()
this.code = code
}
}
function stderr_to_parser_error(fn) {
// if this is being called recursively and stderr or stdout is already being
// redirected, simply call the function and let the enclosing function
// catch the exception
if (process.stderr instanceof StdIOBuffer || process.stdout instanceof StdIOBuffer) {
return fn()
}
// if this is not being called recursively, redirect stderr and
// use it as the ArgumentParserError message
let old_stdout = Object.getOwnPropertyDescriptor(process, 'stdout')
let old_stderr = Object.getOwnPropertyDescriptor(process, 'stderr')
Object.defineProperty(process, 'stdout', { value: new StdIOBuffer() })
Object.defineProperty(process, 'stderr', { value: new StdIOBuffer() })
try {
try {
let result = fn()
for (let key of Object.keys(result || {})) {
if (result[key] === process.stdout) result[key] = old_stdout.get()
if (result[key] === process.stderr) result[key] = old_stderr.get()
}
return result
} catch (err) {
if (!(err instanceof SystemExit)) throw err
let code = err.code
let stdout = process.stdout.getvalue()
let stderr = process.stderr.getvalue()
throw new ArgumentParserError(
"SystemExit", stdout, stderr, code)
}
} finally {
Object.defineProperty(process, 'stdout', old_stdout)
Object.defineProperty(process, 'stderr', old_stderr)
}
}
class ErrorRaisingArgumentParser extends argparse.ArgumentParser {
parse_args(...args) {
return stderr_to_parser_error(() => super.parse_args(...args))
}
exit(code, message) {
return stderr_to_parser_error(() => {
this._print_message(message, process.stderr)
throw new SystemExit(code)
})
}
error(...args) {
return stderr_to_parser_error(() => super.error(...args))
}
}
class ParserTestCase extends TestCase {
/*
* Adds parser tests using the class attributes.
*
* Classes of this type should specify the following attributes:
*
* argument_signatures -- a list of Sig objects which specify
* the signatures of Argument objects to be created
* failures -- a list of args lists that should cause the parser
* to fail
* successes -- a list of (initial_args, options, remaining_args) tuples
* where initial_args specifies the string args to be parsed,
* options is a dict that should match the vars() of the options
* parsed out of initial_args, and remaining_args should be any
* remaining unparsed arguments
*/
constructor() {
super()
// default parser signature is empty
if (!('parser_signature' in this)) {
this.parser_signature = Sig()
}
if (!('parser_class' in this)) {
this.parser_class = ErrorRaisingArgumentParser
}
// ---------------------------------------
// functions for adding optional arguments
// ---------------------------------------
function no_groups(parser, argument_signatures) {
/* Add all arguments directly to the parser */
for (let sig of argument_signatures) {
parser.add_argument(...sig)
}
}
function one_group(parser, argument_signatures) {
/* Add all arguments under a single group in the parser */
let group = parser.add_argument_group('foo')
for (let sig of argument_signatures) {
group.add_argument(...sig)
}
}
function many_groups(parser, argument_signatures) {
/* Add each argument in its own group to the parser */
for (let [ i, sig ] of Object.entries(argument_signatures)) {
let group = parser.add_argument_group(sub('foo:%i', +i))
group.add_argument(...sig)
}
}
// --------------------------
// functions for parsing args
// --------------------------
function listargs(parser, args) {
/* Parse the args by passing in a list */
return parser.parse_args(args)
}
function sysargs(parser, args) {
/* Parse the args by defaulting to sys.argv */
let old_sys_argv = process.argv
process.argv = [old_sys_argv[0], old_sys_argv[1]].concat(args)
try {
return parser.parse_args()
} finally {
process.argv = old_sys_argv
}
}
// class that holds the combination of one optional argument
// addition method and one arg parsing method
class AddTests {
constructor(tester_cls, add_arguments, parse_args) {
this._add_arguments = add_arguments
this._parse_args = parse_args
let add_arguments_name = this._add_arguments.name
let parse_args_name = this._parse_args.name
for (let test_func of [this.test_failures, this.test_successes]) {
let func_name = test_func.name
let names = [ func_name, add_arguments_name, parse_args_name ]
let test_name = names.join('_')
tester_cls[test_name] = () => test_func.call(this, tester_cls)
}
}
_get_parser(tester) {
let parser = new tester.parser_class(...tester.parser_signature)
this._add_arguments(parser, tester.argument_signatures)
return parser
}
test_failures(tester) {
let parser = this._get_parser(tester)
for (let args_str of tester.failures) {
let args = args_str.split(/\s+/).filter(Boolean)
tester.assertRaises(ArgumentParserError, () => parser.parse_args(args))
}
}
test_successes(tester) {
let parser = this._get_parser(tester)
for (let [ args, expected_ns ] of tester.successes) {
if (typeof args === 'string') {
args = args.split(/\s+/).filter(Boolean)
}
let result_ns = tester._normalize_ns(this._parse_args(parser, args))
tester.assertEqual(expected_ns, result_ns)
}
}
}
// add tests for each combination of an optionals adding method
// and an arg parsing method
for (let add_arguments of [no_groups, one_group, many_groups]) {
for (let parse_args of [listargs, sysargs]) {
// eslint-disable-next-line no-new
new AddTests(this, add_arguments, parse_args)
}
}
}
_normalize_ns(ns) {
return ns
}
}
// ===============
// Optionals tests
// ===============
;(new class TestOptionalsSingleDash extends ParserTestCase {
/* Test an Optional with a single-dash option string */
argument_signatures = [Sig('-x')]
failures = ['-x', 'a', '--foo', '-x --foo', '-x -y']
successes = [
['', NS({ x: undefined })],
['-x a', NS({ x: 'a' })],
['-xa', NS({ x: 'a' })],
['-x -1', NS({ x: '-1' })],
['-x-1', NS({ x: '-1' })],
]
}).run()
;(new class TestOptionalsSingleDashCombined extends ParserTestCase {
/* Test an Optional with a single-dash option string */
argument_signatures = [
Sig('-x', { action: 'store_true' }),
Sig('-yyy', { action: 'store_const', const: 42 }),
Sig('-z'),
]
failures = ['a', '--foo', '-xa', '-x --foo', '-x -z', '-z -x',
'-yx', '-yz a', '-yyyx', '-yyyza', '-xyza']
successes = [
['', NS({ x: false, yyy: undefined, z: undefined })],
['-x', NS({ x: true, yyy: undefined, z: undefined })],
['-za', NS({ x: false, yyy: undefined, z: 'a' })],
['-z a', NS({ x: false, yyy: undefined, z: 'a' })],
['-xza', NS({ x: true, yyy: undefined, z: 'a' })],
['-xz a', NS({ x: true, yyy: undefined, z: 'a' })],
['-x -za', NS({ x: true, yyy: undefined, z: 'a' })],
['-x -z a', NS({ x: true, yyy: undefined, z: 'a' })],
['-y', NS({ x: false, yyy: 42, z: undefined })],
['-yyy', NS({ x: false, yyy: 42, z: undefined })],
['-x -yyy -za', NS({ x: true, yyy: 42, z: 'a' })],
['-x -yyy -z a', NS({ x: true, yyy: 42, z: 'a' })],
]
}).run()
;(new class TestOptionalsSingleDashLong extends ParserTestCase {
/* Test an Optional with a multi-character single-dash option string */
argument_signatures = [Sig('-foo')]
failures = ['-foo', 'a', '--foo', '-foo --foo', '-foo -y', '-fooa']
successes = [
['', NS({ foo: undefined })],
['-foo a', NS({ foo: 'a' })],
['-foo -1', NS({ foo: '-1' })],
['-fo a', NS({ foo: 'a' })],
['-f a', NS({ foo: 'a' })],
]
}).run()
;(new class TestOptionalsSingleDashSubsetAmbiguous extends ParserTestCase {
/* Test Optionals where option strings are subsets of each other */
argument_signatures = [Sig('-f'), Sig('-foobar'), Sig('-foorab')]
failures = ['-f', '-foo', '-fo', '-foo b', '-foob', '-fooba', '-foora']
successes = [
['', NS({ f: undefined, foobar: undefined, foorab: undefined })],
['-f a', NS({ f: 'a', foobar: undefined, foorab: undefined })],
['-fa', NS({ f: 'a', foobar: undefined, foorab: undefined })],
['-foa', NS({ f: 'oa', foobar: undefined, foorab: undefined })],
['-fooa', NS({ f: 'ooa', foobar: undefined, foorab: undefined })],
['-foobar a', NS({ f: undefined, foobar: 'a', foorab: undefined })],
['-foorab a', NS({ f: undefined, foobar: undefined, foorab: 'a' })],
]
}).run()
;(new class TestOptionalsSingleDashAmbiguous extends ParserTestCase {
/* Test Optionals that partially match but are not subsets */
argument_signatures = [Sig('-foobar'), Sig('-foorab')]
failures = ['-f', '-f a', '-fa', '-foa', '-foo', '-fo', '-foo b']
successes = [
['', NS({ foobar: undefined, foorab: undefined })],
['-foob a', NS({ foobar: 'a', foorab: undefined })],
['-foor a', NS({ foobar: undefined, foorab: 'a' })],
['-fooba a', NS({ foobar: 'a', foorab: undefined })],
['-foora a', NS({ foobar: undefined, foorab: 'a' })],
['-foobar a', NS({ foobar: 'a', foorab: undefined })],
['-foorab a', NS({ foobar: undefined, foorab: 'a' })],
]
}).run()
;(new class TestOptionalsNumeric extends ParserTestCase {
/* Test an Optional with a short opt string */
argument_signatures = [Sig('-1', { dest: 'one' })]
failures = ['-1', 'a', '-1 --foo', '-1 -y', '-1 -1', '-1 -2']
successes = [
['', NS({ one: undefined })],
['-1 a', NS({ one: 'a' })],
['-1a', NS({ one: 'a' })],
['-1-2', NS({ one: '-2' })],
]
}).run()
;(new class TestOptionalsDoubleDash extends ParserTestCase {
/* Test an Optional with a double-dash option string */
argument_signatures = [Sig('--foo')]
failures = ['--foo', '-f', '-f a', 'a', '--foo -x', '--foo --bar']
successes = [
['', NS({ foo: undefined })],
['--foo a', NS({ foo: 'a' })],
['--foo=a', NS({ foo: 'a' })],
['--foo -2.5', NS({ foo: '-2.5' })],
['--foo=-2.5', NS({ foo: '-2.5' })],
]
}).run()
;(new class TestOptionalsDoubleDashPartialMatch extends ParserTestCase {
/* Tests partial matching with a double-dash option string */
argument_signatures = [
Sig('--badger', { action: 'store_true' }),
Sig('--bat'),
]
failures = ['--bar', '--b', '--ba', '--b: 2', '--ba: 4', '--badge 5']
successes = [
['', NS({ badger: false, bat: undefined })],
['--bat X', NS({ badger: false, bat: 'X' })],
['--bad', NS({ badger: true, bat: undefined })],
['--badg', NS({ badger: true, bat: undefined })],
['--badge', NS({ badger: true, bat: undefined })],
['--badger', NS({ badger: true, bat: undefined })],
]
}).run()
;(new class TestOptionalsDoubleDashPrefixMatch extends ParserTestCase {
/* Tests when one double-dash option string is a prefix of another */
argument_signatures = [
Sig('--badger', { action: 'store_true' }),
Sig('--ba'),
]
failures = ['--bar', '--b', '--ba', '--b: 2', '--badge 5']
successes = [
['', NS({ badger: false, ba: undefined })],
['--ba X', NS({ badger: false, ba: 'X' })],
['--ba=X', NS({ badger: false, ba: 'X' })],
['--bad', NS({ badger: true, ba: undefined })],
['--badg', NS({ badger: true, ba: undefined })],
['--badge', NS({ badger: true, ba: undefined })],
['--badger', NS({ badger: true, ba: undefined })],
]
}).run()
;(new class TestOptionalsSingleDoubleDash extends ParserTestCase {
/* Test an Optional with single- and double-dash option strings */
argument_signatures = [
Sig('-f', { action: 'store_true' }),
Sig('--bar'),
Sig('-baz', { action: 'store_const', const: 42 }),
]
failures = ['--bar', '-fbar', '-fbaz', '-bazf', '-b B', 'B']
successes = [
['', NS({ f: false, bar: undefined, baz: undefined })],
['-f', NS({ f: true, bar: undefined, baz: undefined })],
['--ba B', NS({ f: false, bar: 'B', baz: undefined })],
['-f --bar B', NS({ f: true, bar: 'B', baz: undefined })],
['-f -b', NS({ f: true, bar: undefined, baz: 42 })],
['-ba -f', NS({ f: true, bar: undefined, baz: 42 })],
]
}).run()
;(new class TestOptionalsAlternatePrefixChars extends ParserTestCase {
/* Test an Optional with option strings with custom prefixes */
parser_signature = Sig({ prefix_chars: '+:/', add_help: false })
argument_signatures = [
Sig('+f', { action: 'store_true' }),
Sig('::bar'),
Sig('/baz', { action: 'store_const', const: 42 }),
]
failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help']
successes = [
['', NS({ f: false, bar: undefined, baz: undefined })],
['+f', NS({ f: true, bar: undefined, baz: undefined })],
['::ba B', NS({ f: false, bar: 'B', baz: undefined })],
['+f ::bar B', NS({ f: true, bar: 'B', baz: undefined })],
['+f /b', NS({ f: true, bar: undefined, baz: 42 })],
['/ba +f', NS({ f: true, bar: undefined, baz: 42 })],
]
}).run()
;(new class TestOptionalsAlternatePrefixCharsAddedHelp extends ParserTestCase {
/*
* When ``-`` not in prefix_chars, default operators created for help
* should use the prefix_chars in use rather than - or --
* http://bugs.python.org/issue9444
*/
parser_signature = Sig({ prefix_chars: '+:/', add_help: true })
argument_signatures = [
Sig('+f', { action: 'store_true' }),
Sig('::bar'),
Sig('/baz', { action: 'store_const', const: 42 }),
]
failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz']
successes = [
['', NS({ f: false, bar: undefined, baz: undefined })],
['+f', NS({ f: true, bar: undefined, baz: undefined })],
['::ba B', NS({ f: false, bar: 'B', baz: undefined })],
['+f ::bar B', NS({ f: true, bar: 'B', baz: undefined })],
['+f /b', NS({ f: true, bar: undefined, baz: 42 })],
['/ba +f', NS({ f: true, bar: undefined, baz: 42 })]
]
}).run()
;(new class TestOptionalsAlternatePrefixCharsMultipleShortArgs extends ParserTestCase {
/* Verify that Optionals must be called with their defined prefixes */
parser_signature = Sig({ prefix_chars: '+-', add_help: false })
argument_signatures = [
Sig('-x', { action: 'store_true' }),
Sig('+y', { action: 'store_true' }),
Sig('+z', { action: 'store_true' }),
]
failures = ['-w',
'-xyz',
'+x',
'-y',
'+xyz',
]
successes = [
['', NS({ x: false, y: false, z: false })],
['-x', NS({ x: true, y: false, z: false })],
['+y -x', NS({ x: true, y: true, z: false })],
['+yz -x', NS({ x: true, y: true, z: true })],
]
}).run()
;(new class TestOptionalsShortLong extends ParserTestCase {
/* Test a combination of single- and double-dash option strings */
argument_signatures = [
Sig('-v', '--verbose', '-n', '--noisy', { action: 'store_true' }),
]
failures = ['--x --verbose', '-N', 'a', '-v x']
successes = [
['', NS({ verbose: false })],
['-v', NS({ verbose: true })],
['--verbose', NS({ verbose: true })],
['-n', NS({ verbose: true })],
['--noisy', NS({ verbose: true })],
]
}).run()
;(new class TestOptionalsDest extends ParserTestCase {
/* Tests various means of setting destination */
argument_signatures = [Sig('--foo-bar'), Sig('--baz', { dest: 'zabbaz' })]
failures = ['a']
successes = [
['--foo-bar f', NS({ foo_bar: 'f', zabbaz: undefined })],
['--baz g', NS({ foo_bar: undefined, zabbaz: 'g' })],
['--foo-bar h --baz i', NS({ foo_bar: 'h', zabbaz: 'i' })],
['--baz j --foo-bar k', NS({ foo_bar: 'k', zabbaz: 'j' })],
]
}).run()
;(new class TestOptionalsDefault extends ParserTestCase {
/* Tests specifying a default for an Optional */
argument_signatures = [Sig('-x'), Sig('-y', { default: 42 })]
failures = ['a']
successes = [
['', NS({ x: undefined, y: 42 })],
['-xx', NS({ x: 'x', y: 42 })],
['-yy', NS({ x: undefined, y: 'y' })],
]
}).run()
;(new class TestOptionalsNargsDefault extends ParserTestCase {
/* Tests not specifying the number of args for an Optional */
argument_signatures = [Sig('-x')]
failures = ['a', '-x']
successes = [
['', NS({ x: undefined })],
['-x a', NS({ x: 'a' })],
]
}).run()
;(new class TestOptionalsNargs1 extends ParserTestCase {
/* Tests specifying 1 arg for an Optional */
argument_signatures = [Sig('-x', { nargs: 1 })]
failures = ['a', '-x']
successes = [
['', NS({ x: undefined })],
['-x a', NS({ x: ['a'] })],
]
}).run()
;(new class TestOptionalsNargs3 extends ParserTestCase {
/* Tests specifying 3 args for an Optional */
argument_signatures = [Sig('-x', { nargs: 3 })]
failures = ['a', '-x', '-x a', '-x a b', 'a -x', 'a -x b']
successes = [
['', NS({ x: undefined })],
['-x a b c', NS({ x: ['a', 'b', 'c'] })],
]
}).run()
;(new class TestOptionalsNargsOptional extends ParserTestCase {
/* Tests specifying an Optional arg for an Optional */
argument_signatures = [
Sig('-w', { nargs: '?' }),
Sig('-x', { nargs: '?', const: 42 }),
Sig('-y', { nargs: '?', default: 'spam' }),
Sig('-z', { nargs: '?', type: 'int', const: '42', default: '84' }),
]
failures = ['2']
successes = [
['', NS({ w: undefined, x: undefined, y: 'spam', z: 84 })],
['-w', NS({ w: undefined, x: undefined, y: 'spam', z: 84 })],
['-w 2', NS({ w: '2', x: undefined, y: 'spam', z: 84 })],
['-x', NS({ w: undefined, x: 42, y: 'spam', z: 84 })],
['-x 2', NS({ w: undefined, x: '2', y: 'spam', z: 84 })],
['-y', NS({ w: undefined, x: undefined, y: undefined, z: 84 })],
['-y 2', NS({ w: undefined, x: undefined, y: '2', z: 84 })],
['-z', NS({ w: undefined, x: undefined, y: 'spam', z: 42 })],
['-z 2', NS({ w: undefined, x: undefined, y: 'spam', z: 2 })],
]
}).run()
;(new class TestOptionalsNargsZeroOrMore extends ParserTestCase {
/* Tests specifying args for an Optional that accepts zero or more */
argument_signatures = [
Sig('-x', { nargs: '*' }),
Sig('-y', { nargs: '*', default: 'spam' }),
]
failures = ['a']
successes = [
['', NS({ x: undefined, y: 'spam' })],
['-x', NS({ x: [], y: 'spam' })],
['-x a', NS({ x: ['a'], y: 'spam' })],
['-x a b', NS({ x: ['a', 'b'], y: 'spam' })],
['-y', NS({ x: undefined, y: [] })],
['-y a', NS({ x: undefined, y: ['a'] })],
['-y a b', NS({ x: undefined, y: ['a', 'b'] })],
]
}).run()
;(new class TestOptionalsNargsOneOrMore extends ParserTestCase {
/* Tests specifying args for an Optional that accepts one or more */
argument_signatures = [
Sig('-x', { nargs: '+' }),
Sig('-y', { nargs: '+', default: 'spam' }),
]
failures = ['a', '-x', '-y', 'a -x', 'a -y b']
successes = [
['', NS({ x: undefined, y: 'spam' })],
['-x a', NS({ x: ['a'], y: 'spam' })],
['-x a b', NS({ x: ['a', 'b'], y: 'spam' })],
['-y a', NS({ x: undefined, y: ['a'] })],
['-y a b', NS({ x: undefined, y: ['a', 'b'] })],
]
}).run()
;(new class TestOptionalsChoices extends ParserTestCase {
/* Tests specifying the choices for an Optional */
argument_signatures = [
Sig('-f', { choices: 'abc' }),
Sig('-g', { type: 'int', choices: Array(5).fill(0).map((x, i) => i) })]
failures = ['a', '-f d', '-fad', '-ga', '-g 6']
successes = [
['', NS({ f: undefined, g: undefined })],
['-f a', NS({ f: 'a', g: undefined })],
['-f c', NS({ f: 'c', g: undefined })],
['-g 0', NS({ f: undefined, g: 0 })],
['-g 03', NS({ f: undefined, g: 3 })],
['-fb -g4', NS({ f: 'b', g: 4 })],
]
}).run()
;(new class TestOptionalsRequired extends ParserTestCase {
/* Tests an optional action that is required */
argument_signatures = [
Sig('-x', { type: 'int', required: true }),
]
failures = ['a', '']
successes = [
['-x 1', NS({ x: 1 })],
['-x42', NS({ x: 42 })],
]
}).run()
;(new class TestOptionalsActionStore extends ParserTestCase {
/* Tests the store action for an Optional */
argument_signatures = [Sig('-x', { action: 'store' })]
failures = ['a', 'a -x']
successes = [
['', NS({ x: undefined })],
['-xfoo', NS({ x: 'foo' })],
]
}).run()
;(new class TestOptionalsActionStoreConst extends ParserTestCase {
/* Tests the store_const action for an Optional */
argument_signatures = [Sig('-y', { action: 'store_const', const: Object })]
failures = ['a']
successes = [
['', NS({ y: undefined })],
['-y', NS({ y: Object })],
]
}).run()
;(new class TestOptionalsActionStoreFalse extends ParserTestCase {
/* Tests the store_false action for an Optional */
argument_signatures = [Sig('-z', { action: 'store_false' })]
failures = ['a', '-za', '-z a']
successes = [
['', NS({ z: true })],
['-z', NS({ z: false })],
]
}).run()
;(new class TestOptionalsActionStoreTrue extends ParserTestCase {
/* Tests the store_true action for an Optional */
argument_signatures = [Sig('--apple', { action: 'store_true' })]
failures = ['a', '--apple=b', '--apple b']
successes = [
['', NS({ apple: false })],
['--apple', NS({ apple: true })],
]
}).run()
;(new class TestBooleanOptionalAction extends ParserTestCase {
/* Tests BooleanOptionalAction */
argument_signatures = [Sig('--foo', { action: argparse.BooleanOptionalAction })]
failures = ['--foo bar', '--foo=bar']
successes = [
['', NS({ foo: undefined })],
['--foo', NS({ foo: true })],
['--no-foo', NS({ foo: false })],
['--foo --no-foo', NS({ foo: false })], // useful for aliases
['--no-foo --foo', NS({ foo: true })],
]
test_const() {
// See bpo-40862
let parser = argparse.ArgumentParser()
let cm = this.assertRaises(TypeError, () =>
parser.add_argument('--foo', { const: true, action: argparse.BooleanOptionalAction }))
this.assertRegex(String(cm.exception), /got an unexpected keyword argument 'const'/)
}
}).run()
;(new class TestBooleanOptionalActionRequired extends ParserTestCase {
/* Tests BooleanOptionalAction required */
argument_signatures = [
Sig('--foo', { required: true, action: argparse.BooleanOptionalAction })
]
failures = ['']
successes = [
['--foo', NS({ foo: true })],
['--no-foo', NS({ foo: false })],
]
}).run()
;(new class TestOptionalsActionAppend extends ParserTestCase {
/* Tests the append action for an Optional */
argument_signatures = [Sig('--baz', { action: 'append' })]
failures = ['a', '--baz', 'a --baz', '--baz a b']
successes = [
['', NS({ baz: undefined })],
['--baz a', NS({ baz: ['a'] })],
['--baz a --baz b', NS({ baz: ['a', 'b'] })],
]
}).run()
;(new class TestOptionalsActionAppendWithDefault extends ParserTestCase {
/* Tests the append action for an Optional */
argument_signatures = [Sig('--baz', { action: 'append', default: ['X'] })]
failures = ['a', '--baz', 'a --baz', '--baz a b']
successes = [
['', NS({ baz: ['X'] })],
['--baz a', NS({ baz: ['X', 'a'] })],
['--baz a --baz b', NS({ baz: ['X', 'a', 'b'] })],
]
}).run()
;(new class TestOptionalsActionAppendConst extends ParserTestCase {
/* Tests the append_const action for an Optional */
argument_signatures = [
Sig('-b', { action: 'append_const', const: Error }),
Sig('-c', { action: 'append', dest: 'b' }),
]
failures = ['a', '-c', 'a -c', '-bx', '-b x']
successes = [
['', NS({ b: undefined })],
['-b', NS({ b: [Error] })],
['-b -cx -b -cyz', NS({ b: [Error, 'x', Error, 'yz'] })],
]
}).run()
;(new class TestOptionalsActionAppendConstWithDefault extends ParserTestCase {
/* Tests the append_const action for an Optional */
argument_signatures = [
Sig('-b', { action: 'append_const', const: Error, default: ['X'] }),
Sig('-c', { action: 'append', dest: 'b' }),
]
failures = ['a', '-c', 'a -c', '-bx', '-b x']
successes = [
['', NS({ b: ['X'] })],
['-b', NS({ b: ['X', Error] })],
['-b -cx -b -cyz', NS({ b: ['X', Error, 'x', Error, 'yz'] })],
]
}).run()
;(new class TestOptionalsActionCount extends ParserTestCase {
/* Tests the count action for an Optional */
argument_signatures = [Sig('-x', { action: 'count' })]
failures = ['a', '-x a', '-x b', '-x a -x b']
successes = [
['', NS({ x: undefined })],
['-x', NS({ x: 1 })],
]
}).run()
;(new class TestOptionalsAllowLongAbbreviation extends ParserTestCase {
/* Allow long options to be abbreviated unambiguously */
argument_signatures = [
Sig('--foo'),
Sig('--foobaz'),
Sig('--fooble', { action: 'store_true' }),
]
failures = ['--foob 5', '--foob']
successes = [
['', NS({ foo: undefined, foobaz: undefined, fooble: false })],
['--foo 7', NS({ foo: '7', foobaz: undefined, fooble: false })],
['--fooba a', NS({ foo: undefined, foobaz: 'a', fooble: false })],
['--foobl --foo g', NS({ foo: 'g', foobaz: undefined, fooble: true })],
]
}).run()
;(new class TestOptionalsDisallowLongAbbreviation extends ParserTestCase {
/* Do not allow abbreviations of long options at all */
parser_signature = Sig({ allow_abbrev: false })
argument_signatures = [
Sig('--foo'),
Sig('--foodle', { action: 'store_true' }),
Sig('--foonly'),
]
failures = ['-foon 3', '--foon 3', '--food', '--food --foo 2']
successes = [
['', NS({ foo: undefined, foodle: false, foonly: undefined })],
['--foo 3', NS({ foo: '3', foodle: false, foonly: undefined })],
['--foonly 7 --foodle --foo 2', NS({ foo: '2', foodle: true, foonly: '7' })],
]
}).run()
;(new class TestOptionalsDisallowLongAbbreviationPrefixChars extends ParserTestCase {
/* Disallowing abbreviations works with alternative prefix characters */
parser_signature = Sig({ prefix_chars: '+', allow_abbrev: false })
argument_signatures = [
Sig('++foo'),
Sig('++foodle', { action: 'store_true' }),
Sig('++foonly'),
]
failures = ['+foon 3', '++foon 3', '++food', '++food ++foo 2']
successes = [
['', NS({ foo: undefined, foodle: false, foonly: undefined })],
['++foo 3', NS({ foo: '3', foodle: false, foonly: undefined })],
['++foonly 7 ++foodle ++foo 2', NS({ foo: '2', foodle: true, foonly: '7' })],
]
}).run()
;(new class TestDisallowLongAbbreviationAllowsShortGrouping extends ParserTestCase {
/* Do not allow abbreviations of long options at all */
parser_signature = Sig({ allow_abbrev: false })
argument_signatures = [
Sig('-r'),
Sig('-c', { action: 'count' }),
]
failures = ['-r', '-c -r']
successes = [
['', NS({ r: undefined, c: undefined })],
['-ra', NS({ r: 'a', c: undefined })],
['-rcc', NS({ r: 'cc', c: undefined })],
['-cc', NS({ r: undefined, c: 2 })],
['-cc -ra', NS({ r: 'a', c: 2 })],
['-ccrcc', NS({ r: 'cc', c: 2 })],