-
-
Notifications
You must be signed in to change notification settings - Fork 606
/
options_test.py
1823 lines (1572 loc) · 76.2 KB
/
options_test.py
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
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import json
import os
import shlex
import unittest.mock
from enum import Enum
from functools import partial
from textwrap import dedent
from typing import Any, Dict, List, Optional, Union, cast
import pytest
import toml
import yaml
from packaging.version import Version
from pants.base.deprecated import CodeRemovedError
from pants.base.hash_utils import CoercingEncoder
from pants.option.config import Config
from pants.option.custom_types import UnsetBool, file_option, shell_str, target_option
from pants.option.errors import (
BooleanConversionError,
BooleanOptionNameWithNo,
FromfileError,
ImplicitValIsNone,
InvalidKwarg,
InvalidMemberType,
MemberTypeNotAllowed,
MutuallyExclusiveOptionError,
NoOptionNames,
OptionAlreadyRegistered,
OptionNameDash,
OptionNameDoubleDash,
ParseError,
RecursiveSubsystemOption,
Shadowing,
)
from pants.option.global_options import GlobalOptions
from pants.option.optionable import Optionable
from pants.option.options import Options
from pants.option.options_bootstrapper import OptionsBootstrapper
from pants.option.parser import Parser
from pants.option.ranked_value import Rank, RankedValue
from pants.option.scope import GLOBAL_SCOPE, ScopeInfo
from pants.testutil.option.fakes import create_options
from pants.testutil.test_base import TestBase
from pants.util.collections import assert_single_element
from pants.util.contextutil import temporary_file, temporary_file_path
from pants.util.dirutil import safe_mkdtemp
from pants.util.strutil import safe_shlex_join
_FAKE_CUR_VERSION = "1.0.0.dev0"
def global_scope() -> ScopeInfo:
return ScopeInfo(GLOBAL_SCOPE, GlobalOptions)
def task(scope: str) -> ScopeInfo:
return ScopeInfo(scope)
def intermediate(scope: str) -> ScopeInfo:
return ScopeInfo(scope)
def subsystem(scope: str) -> ScopeInfo:
return ScopeInfo(scope)
class OptionsTest(TestBase):
@staticmethod
def _create_config(config: Optional[Dict[str, Dict[str, str]]] = None) -> Config:
with open(os.path.join(safe_mkdtemp(), "test_config.toml"), "w") as fp:
toml.dump(config or {}, fp)
return Config.load(config_paths=[fp.name])
def _parse(
self,
*,
flags: str = "",
env: Optional[Dict[str, str]] = None,
config: Optional[Dict[str, Dict[str, Any]]] = None,
bootstrap_option_values=None,
) -> Options:
args = ["./pants", *shlex.split(flags)]
options = Options.create(
env=env or {},
config=self._create_config(config),
known_scope_infos=OptionsTest._known_scope_infos,
args=args,
bootstrap_option_values=bootstrap_option_values,
)
self._register(options)
return options
_known_scope_infos = [
global_scope(),
intermediate("compile"),
task("compile.java"),
task("compile.scala"),
task("cache.compile.scala"),
intermediate("stale"),
intermediate("test"),
task("test.junit"),
subsystem("passconsumer"),
task("simple"),
task("simple-dashed"),
task("scoped.a.bit"),
task("scoped.and-dashed"),
task("fromfile"),
task("fingerprinting"),
task("enum-opt"),
task("separate-enum-opt-scope"),
task("other-enum-scope"),
]
class SomeEnumOption(Enum):
a_value = "a-value"
another_value = "another-value"
yet_another = "yet-another"
one_more = "one-more"
def _register(self, options):
def register_global(*args, **kwargs):
options.register(GLOBAL_SCOPE, *args, **kwargs)
register_global("-z", "--verbose", type=bool, help="Verbose output.", recursive=True)
register_global("-n", "--num", type=int, default=99, recursive=True, fingerprint=True)
register_global("--y", type=list, member_type=int)
register_global(
"--v2", help="Two-letter long-form option, used to test option name suggestions."
)
register_global("--config-override", type=list)
register_global("--pants-foo")
register_global("--bar-baz")
register_global("--store-true-flag", type=bool, fingerprint=True)
register_global("--store-false-flag", type=bool, implicit_value=False)
register_global("--store-true-def-true-flag", type=bool, default=True)
register_global("--store-true-def-false-flag", type=bool, default=False)
register_global(
"--store-false-def-false-flag", type=bool, implicit_value=False, default=False
)
register_global(
"--store-false-def-true-flag", type=bool, implicit_value=False, default=True
)
register_global("--def-unset-bool-flag", type=bool, default=UnsetBool)
# Choices.
register_global("--str-choices", choices=["foo", "bar"])
register_global("--int-choices", choices=[42, 99], type=list, member_type=int)
# Custom types.
register_global("--listy", type=list, member_type=int, default="[1, 2, 3]")
register_global("--dicty", type=dict, default='{"a": "b"}')
register_global(
"--dict-listy", type=list, member_type=dict, default='[{"a": 1, "b": 2}, {"c": 3}]'
)
register_global("--targety", type=target_option, default="//:a")
register_global(
"--target-listy", type=list, member_type=target_option, default=["//:a", "//:b"]
)
register_global("--filey", type=file_option, default=None)
register_global("--file-listy", type=list, member_type=file_option)
register_global(
"--shell-str-listy",
type=list,
member_type=shell_str,
default="--default1 --default2=test",
)
# Implicit value.
register_global("--implicit-valuey", default="default", implicit_value="implicit")
# For the design doc example test.
register_global("--a", type=int, recursive=True)
register_global("--b", type=int, recursive=True)
# Deprecated global options
register_global(
"--global-crufty",
removal_version="999.99.9.dev0",
removal_hint="use a less crufty global option",
)
register_global(
"--global-crufty-boolean",
type=bool,
removal_version="999.99.9.dev0",
removal_hint="say no to crufty global options",
)
register_global(
"--global-delayed-deprecated-option",
removal_version="999.99.9.dev0",
deprecation_start_version="500.0.0.dev0",
)
register_global(
"--global-delayed-but-already-passed-deprecated-option",
removal_version="999.99.9.dev0",
deprecation_start_version=_FAKE_CUR_VERSION,
)
# Test that an option past the `removal_version` fails at option registration time.
with self.assertRaises(CodeRemovedError):
register_global(
"--global-crufty-expired",
removal_version="0.0.1.dev0",
removal_hint="use a less crufty global option",
)
# Mutual Exclusive options
register_global("--mutex-foo", mutually_exclusive_group="mutex")
register_global("--mutex-bar", mutually_exclusive_group="mutex")
register_global("--mutex-baz", mutually_exclusive_group="mutex")
register_global("--new-name")
register_global("--old-name", mutually_exclusive_group="new_name")
# For the design doc example test.
options.register("compile", "--c", type=int)
# Test deprecated options with a scope
options.register("stale", "--still-good")
options.register(
"stale",
"--crufty",
removal_version="999.99.9.dev0",
removal_hint="use a less crufty stale scoped option",
)
options.register(
"stale",
"--crufty-boolean",
type=bool,
removal_version="999.99.9.dev0",
removal_hint="say no to crufty, stale scoped options",
)
# Test mutual exclusive options with a scope
options.register("stale", "--mutex-a", mutually_exclusive_group="crufty_mutex")
options.register("stale", "--mutex-b", mutually_exclusive_group="crufty_mutex")
options.register("stale", "--crufty-old", mutually_exclusive_group="crufty_new")
options.register("stale", "--crufty-new")
# For task identity test
options.register("compile.scala", "--modifycompile", fingerprint=True)
options.register("compile.scala", "--modifylogs")
options.register(
"compile.scala",
"--modifypassthrough",
fingerprint=True,
passthrough=True,
type=list,
member_type=str,
)
# For scoped env vars test
options.register("simple", "--spam")
options.register("simple-dashed", "--spam")
options.register("scoped.a.bit", "--spam")
options.register("scoped.and-dashed", "--spam")
# For fromfile test
options.register("fromfile", "--string")
options.register("fromfile", "--intvalue", type=int)
options.register("fromfile", "--dictvalue", type=dict)
options.register("fromfile", "--listvalue", type=list)
options.register("fromfile", "--passthru-listvalue", type=list, passthrough=True)
options.register("fromfile", "--appendvalue", type=list, member_type=int)
# For fingerprint tests
options.register("fingerprinting", "--inverted") # Implicitly: daemon=True
options.register("fingerprinting", "--definitely-not-inverted", daemon=False)
options.register("fingerprinting", "--fingerprinted", fingerprint=True)
options.register("fingerprinting", "--definitely-not-fingerprinted", fingerprint=False)
# For enum tests
options.register("enum-opt", "--some-enum", type=self.SomeEnumOption)
options.register(
"other-enum-scope", "--some-list-enum", type=list, member_type=self.SomeEnumOption
)
options.register(
"other-enum-scope",
"--some-list-enum-with-default",
type=list,
member_type=self.SomeEnumOption,
default=[self.SomeEnumOption.yet_another],
)
# For testing the default value
options.register(
"separate-enum-opt-scope",
"--some-enum-with-default",
default=self.SomeEnumOption.a_value,
type=self.SomeEnumOption,
)
def test_env_var_of_type_int(self) -> None:
create_options_object = partial(
Options.create,
config=self._create_config(),
known_scope_infos=OptionsTest._known_scope_infos,
args=shlex.split("./pants"),
)
options = create_options_object(env={"PANTS_FOO_BAR": "123"})
options.register(GLOBAL_SCOPE, "--foo-bar", type=int)
self.assertEqual(123, options.for_global_scope().foo_bar)
options = create_options_object(env={"PANTS_FOO_BAR": "['123','456']"})
options.register(GLOBAL_SCOPE, "--foo-bar", type=list, member_type=int)
self.assertEqual([123, 456], options.for_global_scope().foo_bar)
def test_arg_scoping(self) -> None:
# Some basic smoke tests.
options = self._parse(flags="--verbose")
self.assertEqual(True, options.for_global_scope().verbose)
options = self._parse(flags="-z compile path/to/tgt")
self.assertEqual(["path/to/tgt"], options.specs)
self.assertEqual(True, options.for_global_scope().verbose)
with self.assertRaises(ParseError):
self._parse(flags="--unregistered-option compile").for_global_scope()
# Scoping of different values of the same option.
# Also tests the --no-* boolean flag inverses.
options = self._parse(flags="--verbose compile.java --no-verbose")
self.assertEqual(True, options.for_global_scope().verbose)
self.assertEqual(True, options.for_scope("compile").verbose)
self.assertEqual(False, options.for_scope("compile.java").verbose)
options = self._parse(
flags="--verbose compile --no-verbose compile.java -z test test.junit --no-verbose"
)
self.assertEqual(True, options.for_global_scope().verbose)
self.assertEqual(False, options.for_scope("compile").verbose)
self.assertEqual(True, options.for_scope("compile.java").verbose)
self.assertEqual(True, options.for_scope("test").verbose)
self.assertEqual(False, options.for_scope("test.junit").verbose)
# Test list-typed option.
global_options = self._parse(config={"DEFAULT": {"y": ["88", "-99"]}}).for_global_scope()
self.assertEqual([88, -99], global_options.y)
global_options = self._parse(
flags="--y=5 --y=-6 --y=77", config={"DEFAULT": {"y": ["88", "-99"]}}
).for_global_scope()
self.assertEqual([88, -99, 5, -6, 77], global_options.y)
global_options = self._parse().for_global_scope()
self.assertEqual([], global_options.y)
global_options = self._parse(
env={"PANTS_CONFIG_OVERRIDE": "['123','456']"}
).for_global_scope()
self.assertEqual(["123", "456"], global_options.config_override)
global_options = self._parse(env={"PANTS_CONFIG_OVERRIDE": "['']"}).for_global_scope()
self.assertEqual([""], global_options.config_override)
global_options = self._parse(
flags="--listy='[1, 2]'", config={"DEFAULT": {"listy": "[3, 4]"}}
).for_global_scope()
self.assertEqual([1, 2], global_options.listy)
# Test dict-typed option.
global_options = self._parse(flags='--dicty=\'{"c": "d"}\'').for_global_scope()
self.assertEqual({"c": "d"}, global_options.dicty)
# Test list-of-dict-typed option.
global_options = self._parse(
flags='--dict-listy=\'[{"c": "d"}, {"e": "f"}]\''
).for_global_scope()
self.assertEqual([{"c": "d"}, {"e": "f"}], global_options.dict_listy)
# Test target-typed option.
global_options = self._parse().for_global_scope()
self.assertEqual("//:a", global_options.targety)
global_options = self._parse(flags="--targety=//:foo").for_global_scope()
self.assertEqual("//:foo", global_options.targety)
# Test list-of-target-typed option.
global_options = self._parse(
flags='--target-listy=\'["//:foo", "//:bar"]\''
).for_global_scope()
self.assertEqual(["//:foo", "//:bar"], global_options.target_listy)
# Test file-typed option.
with temporary_file_path() as fp:
global_options = self._parse(flags=f'--filey="{fp}"').for_global_scope()
self.assertEqual(fp, global_options.filey)
# Test list-of-file-typed option.
with temporary_file_path() as fp1:
with temporary_file_path() as fp2:
global_options = self._parse(
flags=f'--file-listy="{fp1}" --file-listy="{fp2}"'
).for_global_scope()
self.assertEqual([fp1, fp2], global_options.file_listy)
def test_explicit_boolean_values(self) -> None:
def assert_boolean_value(*, arg: str, expected: bool) -> None:
global_options = self._parse(flags=f"--verbose={arg}").for_global_scope()
assert global_options.verbose is expected
assert_boolean_value(arg="false", expected=False)
assert_boolean_value(arg="False", expected=False)
assert_boolean_value(arg="true", expected=True)
assert_boolean_value(arg="True", expected=True)
def test_boolean_defaults(self) -> None:
global_options = self._parse().for_global_scope()
self.assertFalse(global_options.store_true_flag)
self.assertTrue(global_options.store_false_flag)
self.assertFalse(global_options.store_true_def_false_flag)
self.assertTrue(global_options.store_true_def_true_flag)
self.assertFalse(global_options.store_false_def_false_flag)
self.assertTrue(global_options.store_false_def_true_flag)
self.assertIsNone(global_options.def_unset_bool_flag)
def test_boolean_set_option(self) -> None:
global_options = self._parse(
flags="--store-true-flag --store-false-flag --store-true-def-true-flag "
"--store-true-def-false-flag --store-false-def-true-flag --store-false-def-false-flag "
"--def-unset-bool-flag"
).for_global_scope()
self.assertTrue(global_options.store_true_flag)
self.assertFalse(global_options.store_false_flag)
self.assertTrue(global_options.store_true_def_false_flag)
self.assertTrue(global_options.store_true_def_true_flag)
self.assertFalse(global_options.store_false_def_false_flag)
self.assertFalse(global_options.store_false_def_true_flag)
self.assertTrue(global_options.def_unset_bool_flag)
def test_boolean_negate_option(self) -> None:
global_options = self._parse(
flags="--no-store-true-flag --no-store-false-flag --no-store-true-def-true-flag "
"--no-store-true-def-false-flag --no-store-false-def-true-flag "
"--no-store-false-def-false-flag --no-def-unset-bool-flag"
).for_global_scope()
self.assertFalse(global_options.store_true_flag)
self.assertTrue(global_options.store_false_flag)
self.assertFalse(global_options.store_true_def_false_flag)
self.assertFalse(global_options.store_true_def_true_flag)
self.assertTrue(global_options.store_false_def_false_flag)
self.assertTrue(global_options.store_false_def_true_flag)
self.assertFalse(global_options.def_unset_bool_flag)
def test_boolean_config_override(self) -> None:
def assert_options_set(value: bool) -> None:
global_options = self._parse(
config={
"DEFAULT": {
"store_true_flag": value,
"store_false_flag": value,
"store_true_def_true_flag": value,
"store_true_def_false_flag": value,
"store_false_def_true_flag": value,
"store_false_def_false_flag": value,
"def_unset_bool_flag": value,
},
},
).for_global_scope()
assert global_options.store_true_flag == value
assert global_options.store_false_flag == value
assert global_options.store_true_def_false_flag == value
assert global_options.store_true_def_true_flag == value
assert global_options.store_false_def_false_flag == value
assert global_options.store_false_def_true_flag == value
assert global_options.def_unset_bool_flag == value
assert_options_set(False)
assert_options_set(True)
def test_boolean_invalid_value(self) -> None:
def assert_invalid_value(val) -> None:
with self.assertRaises(BooleanConversionError):
self._parse(config={"DEFAULT": {"store_true_flag": val}}).for_global_scope()
assert_invalid_value(11)
assert_invalid_value("AlmostTrue")
def test_list_option(self) -> None:
def check(
*,
expected: List[int],
flags: str = "",
env_val: Optional[str] = None,
config_val: Optional[str] = None,
) -> None:
env = {"PANTS_GLOBAL_LISTY": env_val} if env_val else None
config = {"GLOBAL": {"listy": config_val}} if config_val else None
global_options = self._parse(flags=flags, env=env, config=config).for_global_scope()
assert global_options.listy == expected
default = [1, 2, 3]
check(expected=default)
# Appending to the default.
check(flags="--listy=4", expected=[*default, 4])
check(flags="--listy=4 --listy=5", expected=[*default, 4, 5])
check(flags="--listy=+[4,5]", expected=[*default, 4, 5])
# Filtering from the default.
check(flags="--listy=-[2]", expected=[1, 3])
# Replacing the default.
check(flags="--listy=[4,5]", expected=[4, 5])
# Appending across env, config and flags (in the right order).
check(
flags="--listy=+[8,9]",
env_val="+[6,7]",
config_val="+[4,5]",
expected=[*default, 4, 5, 6, 7, 8, 9],
)
# Appending and filtering across env, config and flags (in the right order).
check(
flags="--listy=-[1,5,6]", env_val="+[6,7]", config_val="+[4,5]", expected=[2, 3, 4, 7],
)
check(
flags="--listy=+[8,9]",
env_val="-[4,5]",
config_val="+[4,5],-[3]",
expected=[1, 2, 8, 9],
)
# Overwriting from env, then appending and filtering.
check(
flags="--listy=+[8,9],-[6]", env_val="[6,7]", config_val="+[4,5]", expected=[7, 8, 9],
)
# Overwriting from config, then appending.
check(
flags="--listy=+[8,9]",
env_val="+[6,7]",
config_val="[4,5]",
expected=[4, 5, 6, 7, 8, 9],
)
# Overwriting from flags.
check(
flags="--listy=[8,9]", env_val="+[6,7]", config_val="+[4,5],-[8]", expected=[8, 9],
)
# Filtering all instances of repeated values.
check(
flags="--listy=-[5]",
config_val="[1, 2, 5, 3, 4, 5, 6, 5, 5]",
expected=[1, 2, 3, 4, 6],
)
# Filtering a value even though it was appended again at a higher rank.
check(
flags="--listy=+[4]", env_val="-[4]", config_val="+[4,5]", expected=[*default, 5],
)
# Filtering a value even though it was appended again at the same rank.
check(
env_val="-[4],+[4]", config_val="+[4,5]", expected=[*default, 5],
)
# Overwriting cancels filters.
check(env_val="[4]", config_val="-[4]", expected=[4])
def test_dict_list_option(self) -> None:
def check(
*,
expected: List[Dict[str, int]],
flags: str = "",
env_val: Optional[str] = None,
config_val: Optional[str] = None,
) -> None:
env = {"PANTS_GLOBAL_DICT_LISTY": env_val} if env_val else None
config = {"GLOBAL": {"dict_listy": config_val}} if config_val else None
global_options = self._parse(flags=flags, env=env, config=config).for_global_scope()
assert global_options.dict_listy == expected
default = [{"a": 1, "b": 2}, {"c": 3}]
one_element_appended = [*default, {"d": 4, "e": 5}]
two_elements_appended = [*one_element_appended, {"f": 6}]
replaced = [{"d": 4, "e": 5}, {"f": 6}]
check(expected=default)
check(flags='--dict-listy=\'{"d": 4, "e": 5}\'', expected=one_element_appended)
check(
flags='--dict-listy=\'{"d": 4, "e": 5}\' --dict-listy=\'{"f": 6}\'',
expected=two_elements_appended,
)
check(
flags='--dict-listy=\'+[{"d": 4, "e": 5}, {"f": 6}]\'', expected=two_elements_appended,
)
check(flags='--dict-listy=\'[{"d": 4, "e": 5}, {"f": 6}]\'', expected=replaced)
check(env_val='{"d": 4, "e": 5}', expected=one_element_appended)
check(env_val='+[{"d": 4, "e": 5}, {"f": 6}]', expected=two_elements_appended)
check(env_val='[{"d": 4, "e": 5}, {"f": 6}]', expected=replaced)
check(config_val='{"d": 4, "e": 5}', expected=one_element_appended)
check(config_val='+[{"d": 4, "e": 5}, {"f": 6}]', expected=two_elements_appended)
check(config_val='[{"d": 4, "e": 5}, {"f": 6}]', expected=replaced)
def test_target_list_option(self) -> None:
def check(
*,
expected: List[str],
flags: str = "",
env_val: Optional[str] = None,
config_val: Optional[str] = None,
) -> None:
env = {"PANTS_GLOBAL_TARGET_LISTY": env_val} if env_val else None
config = {"GLOBAL": {"target_listy": config_val}} if config_val else None
global_options = self._parse(flags=flags, env=env, config=config).for_global_scope()
assert global_options.target_listy == expected
default = ["//:a", "//:b"]
specified_args = ["//:c", "//:d"]
all_args = [*default, *specified_args]
check(expected=default)
check(flags="--target-listy=//:c --target-listy=//:d", expected=all_args)
check(flags='--target-listy=\'+["//:c", "//:d"]\'', expected=all_args)
check(flags='--target-listy=\'["//:c", "//:d"]\'', expected=specified_args)
check(env_val="//:c", expected=[*default, "//:c"])
check(env_val='+["//:c", "//:d"]', expected=all_args)
check(env_val='["//:c", "//:d"]', expected=specified_args)
check(config_val="//:c", expected=[*default, "//:c"])
check(config_val='+["//:c", "//:d"]', expected=all_args)
check(config_val='["//:c", "//:d"]', expected=specified_args)
def test_shell_str_list(self) -> None:
def check(
*,
expected: List[str],
flags: str = "",
env_val: Optional[str] = None,
config_val: Optional[str] = None,
) -> None:
env = {"PANTS_GLOBAL_SHELL_STR_LISTY": env_val} if env_val else None
config = {"GLOBAL": {"shell_str_listy": config_val}} if config_val else None
global_options = self._parse(flags=flags, env=env, config=config).for_global_scope()
assert global_options.shell_str_listy == expected
default = ["--default1", "--default2=test"]
specified_args = ["arg1", "arg2=foo", "--arg3"]
all_args = [*default, *specified_args]
check(expected=default)
check(
flags="--shell-str-listy='arg1 arg2=foo' --shell-str-listy='--arg3'", expected=all_args
)
check(flags="""--shell-str-listy='+["arg1 arg2=foo", "--arg3"]'""", expected=all_args)
check(flags="""--shell-str-listy='["arg1 arg2=foo", "--arg3"]'""", expected=specified_args)
check(env_val="arg1 arg2=foo --arg3", expected=all_args)
check(env_val='+["arg1 arg2=foo", "--arg3"]', expected=all_args)
check(env_val='["arg1 arg2=foo", "--arg3"]', expected=specified_args)
check(config_val="arg1 arg2=foo --arg3", expected=all_args)
check(config_val='+["arg1 arg2=foo", "--arg3"]', expected=all_args)
check(config_val='["arg1 arg2=foo", "--arg3"]', expected=specified_args)
def test_dict_option(self) -> None:
def check(
*, expected: Dict[str, str], flags: str = "", config_val: Optional[str] = None,
) -> None:
config = {"GLOBAL": {"dicty": config_val}} if config_val else None
global_options = self._parse(flags=flags, config=config).for_global_scope()
assert global_options.dicty == expected
default = {"a": "b"}
specified_args = {"c": "d"}
all_args = {**default, **specified_args}
check(expected=default)
check(flags='--dicty=\'{"c": "d"}\'', expected=specified_args)
check(flags='--dicty=\'+{"c": "d"}\'', expected=all_args)
check(config_val='{"c": "d"}', expected=specified_args)
check(config_val='+{"c": "d"}', expected=all_args)
check(
config_val='+{"c": "d"}',
flags='--dicty=\'+{"e": "f"}\'',
expected={**all_args, "e": "f"},
)
# Check that highest rank wins if we have multiple values for the same key.
check(config_val='+{"a": "b+", "c": "d"}', expected={"a": "b+", "c": "d"})
check(
config_val='+{"a": "b+", "c": "d"}',
flags='--dicty=\'+{"a": "b++"}\'',
expected={"a": "b++", "c": "d"},
)
def test_defaults(self) -> None:
# Hard-coded defaults.
options = self._parse(flags="compile.java -n33")
self.assertEqual(99, options.for_global_scope().num)
self.assertEqual(99, options.for_scope("compile").num)
self.assertEqual(33, options.for_scope("compile.java").num)
self.assertEqual(99, options.for_scope("test").num)
self.assertEqual(99, options.for_scope("test.junit").num)
options = self._parse(flags="compile -n22 compile.java -n33")
self.assertEqual(99, options.for_global_scope().num)
self.assertEqual(22, options.for_scope("compile").num)
self.assertEqual(33, options.for_scope("compile.java").num)
# Get defaults from config and environment.
config = {"DEFAULT": {"num": "88"}, "compile": {"num": "77"}, "compile.java": {"num": "66"}}
options = self._parse(flags="compile.java -n22", config=config)
self.assertEqual(88, options.for_global_scope().num)
self.assertEqual(77, options.for_scope("compile").num)
self.assertEqual(22, options.for_scope("compile.java").num)
env = {"PANTS_COMPILE_NUM": "55"}
options = self._parse(flags="compile", env=env, config=config)
self.assertEqual(88, options.for_global_scope().num)
self.assertEqual(55, options.for_scope("compile").num)
self.assertEqual(55, options.for_scope("compile.java").num)
options = self._parse(flags="compile.java -n44", env=env, config=config)
self.assertEqual(88, options.for_global_scope().num)
self.assertEqual(55, options.for_scope("compile").num)
self.assertEqual(44, options.for_scope("compile.java").num)
def test_choices(self) -> None:
options = self._parse(flags="--str-choices=foo")
self.assertEqual("foo", options.for_global_scope().str_choices)
options = self._parse(config={"DEFAULT": {"str_choices": "bar"}})
self.assertEqual("bar", options.for_global_scope().str_choices)
with self.assertRaises(ParseError):
options = self._parse(flags="--str-choices=baz")
options.for_global_scope()
with self.assertRaises(ParseError):
options = self._parse(config={"DEFAULT": {"str_choices": "baz"}})
options.for_global_scope()
options = self._parse(flags="--int-choices=42 --int-choices=99")
self.assertEqual([42, 99], options.for_global_scope().int_choices)
def test_parse_dest(self) -> None:
self.assertEqual("thing", Parser.parse_dest("--thing"))
self.assertEqual("other_thing", Parser.parse_dest("--thing", dest="other_thing"))
def test_validation(self) -> None:
def assertError(expected_error, *args, **kwargs):
with self.assertRaises(expected_error):
options = Options.create(
args=["./pants"],
env={},
config=self._create_config(),
known_scope_infos=[global_scope()],
)
options.register(GLOBAL_SCOPE, *args, **kwargs)
options.for_global_scope()
assertError(NoOptionNames)
assertError(OptionNameDash, "badname")
assertError(OptionNameDoubleDash, "-badname")
assertError(InvalidKwarg, "--foo", badkwarg=42)
assertError(ImplicitValIsNone, "--foo", implicit_value=None)
assertError(BooleanOptionNameWithNo, "--no-foo", type=bool)
assertError(MemberTypeNotAllowed, "--foo", member_type=int)
assertError(MemberTypeNotAllowed, "--foo", type=dict, member_type=int)
assertError(InvalidMemberType, "--foo", type=list, member_type=set)
assertError(InvalidMemberType, "--foo", type=list, member_type=list)
assertError(InvalidMemberType, "--foo", type=list, member_type=list)
def test_implicit_value(self) -> None:
def check(*, flag: str = "", expected: str) -> None:
options = self._parse(flags=flag)
assert options.for_global_scope().implicit_valuey == expected
check(expected="default")
check(flag="--implicit-valuey", expected="implicit")
check(flag="--implicit-valuey=explicit", expected="explicit")
def test_shadowing(self) -> None:
options = Options.create(
env={},
config=self._create_config(),
known_scope_infos=[global_scope(), task("bar"), intermediate("foo"), task("foo.bar")],
args=["./pants"],
)
options.register("", "--opt1")
options.register("foo", "-o", "--opt2")
def assert_raises_shadowing(*, scope: str, args: List[str]) -> None:
with self.assertRaises(Shadowing):
options.register(scope, *args)
assert_raises_shadowing(scope="", args=["--opt2"])
assert_raises_shadowing(scope="bar", args=["--opt1"])
assert_raises_shadowing(scope="foo.bar", args=["--opt1"])
assert_raises_shadowing(scope="foo.bar", args=["--opt2"])
assert_raises_shadowing(scope="foo.bar", args=["--opt1", "--opt3"])
assert_raises_shadowing(scope="foo.bar", args=["--opt3", "--opt2"])
def test_recursion(self) -> None:
# Recursive option.
options = self._parse(flags="-n=5 compile -n=6")
self.assertEqual(5, options.for_global_scope().num)
self.assertEqual(6, options.for_scope("compile").num)
# Non-recursive option.
options = self._parse(flags="--bar-baz=foo")
self.assertEqual("foo", options.for_global_scope().bar_baz)
options = self._parse(flags="compile --bar-baz=foo")
with self.assertRaises(ParseError):
options.for_scope("compile")
def test_no_recursive_subsystem_options(self) -> None:
options = Options.create(
env={},
config=self._create_config(),
known_scope_infos=[global_scope(), subsystem("foo")],
args=["./pants"],
)
# All subsystem options are implicitly recursive (a subscope of subsystem scope represents
# a separate instance of the subsystem, so it needs all the options).
# We disallow explicit specification of recursive (even if set to True), to avoid confusion.
with self.assertRaises(RecursiveSubsystemOption):
options.register("foo", "--bar", recursive=False)
options.for_scope("foo")
with self.assertRaises(RecursiveSubsystemOption):
options.register("foo", "--baz", recursive=True)
options.for_scope("foo")
def test_is_known_scope(self) -> None:
options = self._parse()
for scope_info in self._known_scope_infos:
self.assertTrue(options.is_known_scope(scope_info.scope))
self.assertFalse(options.is_known_scope("nonexistent_scope"))
def test_designdoc_example(self) -> None:
# The example from the design doc.
# Get defaults from config and environment.
config = {
"DEFAULT": {"b": "99"},
"compile": {"a": "88", "c": "77"},
}
env = {"PANTS_COMPILE_C": "66"}
options = self._parse(
flags="--a=1 compile --b=2 compile.java --a=3 --c=4", env=env, config=config,
)
self.assertEqual(1, options.for_global_scope().a)
self.assertEqual(99, options.for_global_scope().b)
with self.assertRaises(AttributeError):
options.for_global_scope().c
self.assertEqual(1, options.for_scope("compile").a)
self.assertEqual(2, options.for_scope("compile").b)
self.assertEqual(66, options.for_scope("compile").c)
self.assertEqual(3, options.for_scope("compile.java").a)
self.assertEqual(2, options.for_scope("compile.java").b)
self.assertEqual(4, options.for_scope("compile.java").c)
def test_file_spec_args(self) -> None:
with temporary_file(binary_mode=False) as tmp:
tmp.write(
dedent(
"""
foo
bar
"""
)
)
tmp.flush()
# Note that we prevent loading a real pants.toml during get_bootstrap_options().
flags = f'--spec-file={tmp.name} --pants-config-files="[]" compile morx:tgt fleem:tgt'
bootstrapper = OptionsBootstrapper.create(env={}, args=shlex.split(f"./pants {flags}"))
bootstrap_options = bootstrapper.bootstrap_options.for_global_scope()
options = self._parse(flags=flags, bootstrap_option_values=bootstrap_options)
sorted_specs = sorted(options.specs)
self.assertEqual(["bar", "fleem:tgt", "foo", "morx:tgt"], sorted_specs)
def test_passthru_args_subsystems_and_goals(self):
# Test that passthrough args are applied.
options = Options.create(
env={},
config=self._create_config(),
known_scope_infos=[global_scope(), task("test"), subsystem("passconsumer")],
args=["./pants", "test", "target", "--", "bar", "--baz", "@dont_fromfile_expand_me"],
)
options.register(
"passconsumer", "--passthing", passthrough=True, type=list, member_type=str
)
self.assertEqual(
["bar", "--baz", "@dont_fromfile_expand_me"],
options.for_scope("passconsumer").passthing,
)
def test_at_most_one_goal_with_passthru_args(self):
with self.assertRaisesWithMessageContaining(
Options.AmbiguousPassthroughError,
"""Specifying multiple goals (in this case: ['test', 'fmt']) """
"""along with passthrough args (args after `--`) is ambiguous.""",
):
_ = Options.create(
env={},
config={},
known_scope_infos=[global_scope(), task("test"), task("fmt")],
args=["./pants", "test", "fmt", "target", "--", "bar", "--baz"],
)
def test_global_scope_env_vars(self):
def check_pants_foo(expected_val, env):
val = self._parse(env=env).for_global_scope().pants_foo
self.assertEqual(expected_val, val)
check_pants_foo(
"AAA", {"PANTS_GLOBAL_PANTS_FOO": "AAA", "PANTS_PANTS_FOO": "BBB", "PANTS_FOO": "CCC"}
)
check_pants_foo("BBB", {"PANTS_PANTS_FOO": "BBB", "PANTS_FOO": "CCC"})
check_pants_foo("CCC", {"PANTS_FOO": "CCC"})
check_pants_foo(None, {})
# Check that an empty string is distinct from no value being specified.
check_pants_foo("", {"PANTS_PANTS_FOO": "", "PANTS_FOO": "CCC"})
# A global option that doesn't begin with 'pants-': Setting BAR_BAZ should have no effect.
def check_bar_baz(expected_val, env):
val = self._parse(env=env).for_global_scope().bar_baz
self.assertEqual(expected_val, val)
check_bar_baz(
"AAA", {"PANTS_GLOBAL_BAR_BAZ": "AAA", "PANTS_BAR_BAZ": "BBB", "BAR_BAZ": "CCC"}
)
check_bar_baz("BBB", {"PANTS_BAR_BAZ": "BBB", "BAR_BAZ": "CCC"})
check_bar_baz(None, {"BAR_BAZ": "CCC"})
check_bar_baz(None, {})
def test_scoped_env_vars(self) -> None:
def check_scoped_spam(scope, expected_val, env):
val = self._parse(env=env).for_scope(scope).spam
self.assertEqual(expected_val, val)
check_scoped_spam("simple", "value", {"PANTS_SIMPLE_SPAM": "value"})
check_scoped_spam("simple-dashed", "value", {"PANTS_SIMPLE_DASHED_SPAM": "value"})
check_scoped_spam("scoped.a.bit", "value", {"PANTS_SCOPED_A_BIT_SPAM": "value"})
check_scoped_spam("scoped.and-dashed", "value", {"PANTS_SCOPED_AND_DASHED_SPAM": "value"})
def test_drop_flag_values(self) -> None:
options = self._parse(
flags="--bar-baz=fred -n33 --pants-foo=red enum-opt --some-enum=another-value simple -n1",
env={"PANTS_FOO": "BAR"},
config={"simple": {"num": 42}, "enum-opt": {"some-enum": "a-value"}},
)
defaulted_only_options = options.drop_flag_values()
# No option value supplied in any form.
self.assertEqual("fred", options.for_global_scope().bar_baz)
self.assertIsNone(defaulted_only_options.for_global_scope().bar_baz)
# A defaulted option value.
self.assertEqual(33, options.for_global_scope().num)
self.assertEqual(99, defaulted_only_options.for_global_scope().num)
# A config specified option value.
self.assertEqual(1, options.for_scope("simple").num)
self.assertEqual(42, defaulted_only_options.for_scope("simple").num)
# An env var specified option value.
self.assertEqual("red", options.for_global_scope().pants_foo)
self.assertEqual("BAR", defaulted_only_options.for_global_scope().pants_foo)
# Overriding an enum option value.
self.assertEqual(self.SomeEnumOption.another_value, options.for_scope("enum-opt").some_enum)
# Getting the default value for an enum option.
self.assertEqual(
self.SomeEnumOption.a_value,
defaulted_only_options.for_scope("separate-enum-opt-scope").some_enum_with_default,
)
def test_enum_option_type_parse_error(self) -> None:
self.maxDiff = None
with self.assertRaisesWithMessageContaining(
ParseError,
"Error applying type 'SomeEnumOption' to option value 'invalid-value', for option "
"'--some_enum' in scope 'enum-opt'",
):
options = self._parse(flags="enum-opt --some-enum=invalid-value")
options.for_scope("enum-opt").some_enum
def assertOptionWarning(self, w, option_string):
single_warning = assert_single_element(w)
self.assertEqual(single_warning.category, DeprecationWarning)