-
Notifications
You must be signed in to change notification settings - Fork 372
/
Copy pathprogram.py
1415 lines (1181 loc) · 55 KB
/
program.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
import json
import os
import sys
from io import BytesIO
from pathlib import Path
from invoke.util import Lexicon
from unittest.mock import patch, Mock, ANY
import pytest
from pytest import skip
from pytest_relaxed import trap
from invoke import (
Argument,
Collection,
Config,
Executor,
Exit,
FilesystemLoader,
ParserContext,
ParseResult,
Program,
Result,
Task,
UnexpectedExit,
)
from invoke import main
from invoke.util import cd
from invoke.config import merge_dicts
from _util import (
ROOT,
expect,
load,
run,
skip_if_windows,
support_file,
support_path,
support,
)
pytestmark = pytest.mark.usefixtures("integration")
class Program_:
class init:
"__init__"
def may_specify_version(self):
assert Program(version="1.2.3").version == "1.2.3"
def default_version_is_unknown(self):
assert Program().version == "unknown"
def may_specify_namespace(self):
foo = load("foo")
assert Program(namespace=foo).namespace is foo
def may_specify_name(self):
assert Program(name="Myapp").name == "Myapp"
def may_specify_binary(self):
assert Program(binary="myapp").binary == "myapp"
def loader_class_defaults_to_FilesystemLoader(self):
assert Program().loader_class is FilesystemLoader
def may_specify_loader_class(self):
klass = object()
assert Program(loader_class=klass).loader_class == klass
def executor_class_defaults_to_Executor(self):
assert Program().executor_class is Executor
def may_specify_executor_class(self):
klass = object()
assert Program(executor_class=klass).executor_class == klass
def config_class_defaults_to_Config(self):
assert Program().config_class is Config
def may_specify_config_class(self):
klass = object()
assert Program(config_class=klass).config_class == klass
class miscellaneous:
"miscellaneous behaviors"
def debug_flag_activates_logging(self):
# Have to patch our logger to get in before logcapture kicks in.
with patch("invoke.util.debug") as debug:
Program().run("invoke -d -c debugging foo")
debug.assert_called_with("my-sentinel")
def debug_honored_as_env_var_too(self, reset_environ):
os.environ["INVOKE_DEBUG"] = "1"
with patch("invoke.util.debug") as debug:
# NOTE: no use of -d/--debug
Program().run("invoke -c debugging foo")
debug.assert_called_with("my-sentinel")
def bytecode_skipped_by_default(self):
expect("-c foo mytask")
assert sys.dont_write_bytecode
def write_pyc_explicitly_enables_bytecode_writing(self):
expect("--write-pyc -c foo mytask")
assert not sys.dont_write_bytecode
class normalize_argv:
@patch("invoke.program.sys")
def defaults_to_sys_argv(self, mock_sys):
argv = ["inv", "--version"]
mock_sys.argv = argv
p = Program()
p.print_version = Mock()
p.run(exit=False)
p.print_version.assert_called()
def uses_a_list_unaltered(self):
p = Program()
p.print_version = Mock()
p.run(["inv", "--version"], exit=False)
p.print_version.assert_called()
def splits_a_string(self):
p = Program()
p.print_version = Mock()
p.run("inv --version", exit=False)
p.print_version.assert_called()
class name:
def defaults_to_capitalized_binary_when_None(self):
expect("myapp --version", out="Myapp unknown\n", invoke=False)
def benefits_from_binary_absolute_behavior(self):
"benefits from binary()'s absolute path behavior"
expect(
"/usr/local/bin/myapp --version",
out="Myapp unknown\n",
invoke=False,
)
def uses_overridden_value_when_given(self):
p = Program(name="NotInvoke")
expect("--version", out="NotInvoke unknown\n", program=p)
class binary:
def defaults_to_argv_when_None(self):
stdout, _ = run("myapp --help", invoke=False)
assert "myapp [--core-opts]" in stdout
def uses_overridden_value_when_given(self):
stdout, _ = run(
"myapp --help", invoke=False, program=Program(binary="nope")
)
assert "nope [--core-opts]" in stdout
@trap
def use_binary_basename_when_invoked_absolutely(self):
Program().run("/usr/local/bin/myapp --help", exit=False)
stdout = sys.stdout.getvalue()
assert "myapp [--core-opts]" in stdout
assert "/usr/local/bin" not in stdout
class called_as:
# NOTE: these tests are meh due to Program's lifecycle design
# (attributes get modified during run(), such as things based on
# observed argv). It's not great, but, whatever.
@trap
def is_the_whole_deal_when_just_a_name(self):
p = Program()
p.run("whatever --help", exit=False)
assert p.called_as == "whatever"
@trap
def is_basename_when_given_a_path(self):
p = Program()
p.run("/usr/local/bin/whatever --help", exit=False)
assert p.called_as == "whatever"
class binary_names:
# NOTE: this is currently only used for completion stuff, so we use
# that to test. TODO: maybe make this more unit-y...
def defaults_to_argv_when_None(self):
stdout, _ = run("foo --print-completion-script zsh", invoke=False)
assert " foo" in stdout
def can_be_given_directly(self):
program = Program(binary_names=["foo", "bar"])
stdout, _ = run(
"foo --print-completion-script zsh",
invoke=False,
program=program,
)
assert " foo bar" in stdout
class print_version:
def displays_name_and_version(self):
expect(
"--version",
program=Program(name="MyProgram", version="0.1.0"),
out="MyProgram 0.1.0\n",
)
class initial_context:
def contains_truly_core_arguments_regardless_of_namespace_value(self):
# Spot check. See integration-style --help tests for full argument
# checkup.
for program in (Program(), Program(namespace=Collection())):
for arg in ("--complete", "--debug", "--warn-only", "--list"):
stdout, _ = run("--help", program=program)
assert arg in stdout
def null_namespace_triggers_task_related_args(self):
program = Program(namespace=None)
for arg in program.task_args():
stdout, _ = run("--help", program=program)
assert arg.name in stdout
def non_null_namespace_does_not_trigger_task_related_args(self):
for arg in Program().task_args():
program = Program(namespace=Collection(mytask=Task(Mock())))
stdout, _ = run("--help", program=program)
assert arg.name not in stdout
class load_collection:
def complains_when_default_collection_not_found(self):
# NOTE: assumes system under test has no tasks.py in root. Meh.
with cd(ROOT):
expect("-l", err="Can't find any collection named 'tasks'!\n")
def complains_when_explicit_collection_not_found(self):
expect(
"-c huhwhat -l",
err="Can't find any collection named 'huhwhat'!\n",
)
@trap
def uses_loader_class_given(self):
klass = Mock(side_effect=FilesystemLoader)
Program(loader_class=klass).run("myapp --help foo", exit=False)
klass.assert_called_with(start=ANY, config=ANY)
def config_location_correct_for_package_type_task_trees(self):
with cd(Path(support) / "configs" / "package"):
expect("mytask") # will assert if config not loaded right
class execute:
def uses_executor_class_given(self):
klass = Mock()
Program(executor_class=klass).run("myapp foo", exit=False)
klass.assert_called_with(ANY, ANY, ANY)
klass.return_value.execute.assert_called_with(ANY)
def executor_class_may_be_overridden_via_configured_string(self):
class ExecutorOverridingConfig(Config):
@staticmethod
def global_defaults():
defaults = Config.global_defaults()
path = "custom_executor.CustomExecutor"
merge_dicts(defaults, {"tasks": {"executor_class": path}})
return defaults
mock = load("custom_executor").CustomExecutor
p = Program(config_class=ExecutorOverridingConfig)
p.run("myapp noop", exit=False)
assert mock.assert_called
assert mock.return_value.execute.called
def executor_is_given_access_to_core_args_and_remainder(self):
klass = Mock()
cmd = "myapp -e foo -- myremainder"
Program(executor_class=klass).run(cmd, exit=False)
core = klass.call_args[0][2]
assert core[0].args["echo"].value
assert core.remainder == "myremainder"
class core_args:
def returns_core_args_list(self):
# Mostly so we encode explicity doc'd public API member in tests.
# Spot checks good enough, --help tests include the full deal.
core_args = Program().core_args()
core_arg_names = [x.names[0] for x in core_args]
for name in ("complete", "help", "pty", "version"):
assert name in core_arg_names
# Also make sure it's a list for easier tweaking/appending
assert isinstance(core_args, list)
class args_property:
def shorthand_for_self_core_args(self):
"is shorthand for self.core[0].args"
p = Program()
p.run("myapp -e noop", exit=False)
args = p.args
assert isinstance(args, Lexicon)
assert args.echo.value is True
class core_args_from_task_contexts:
# NOTE: many of these use Program.args in lieu of Program.core[0], for
# convenience, tho also because initially the behavior was _in_ .args
def core_context_gets_updated_with_core_flags_from_tasks(self):
# Part of #466.
p = Program()
p.run("myapp -e noop --hide both", exit=False)
# Was given in core
assert p.args.echo.value is True
# Was given in per-task
assert p.args.hide.value == "both"
def copying_from_task_context_does_not_set_empty_list_values(self):
# Less of an issue for scalars, but for list-type args, doing
# .value = <default value> actually ends up creating a
# list-of-lists.
p = Program()
# Set up core-args parser context with an iterable arg that hasn't
# seen any value yet
def filename_args():
return [Argument("filename", kind=list)]
p.core = ParseResult([ParserContext(args=filename_args())])
# And a core-via-tasks context with a copy of that same arg, which
# also hasn't seen any value yet
p.core_via_tasks = ParserContext(args=filename_args())
# Now the behavior of .args can be tested as desired
assert p.args["filename"].value == [] # Not [[]]!
def copying_from_task_context_does_not_overwrite_good_values(self):
# Another subcase, also mostly applying to list types: core context
# got a useful value, nothing was found in the per-task context;
# when a naive 'is not None' check is used, this overwrites the
# good value with an empty list.
# (Other types tend to not have this problem because their ._value
# is always None when not set. TODO: maybe this should be
# considered incorrect behavior for list type args?)
def make_arg():
return Argument("filename", kind=list)
p = Program()
# Core arg, which got a value
arg = make_arg()
arg.value = "some-file" # appends to list
p.core = ParseResult([ParserContext(args=[arg])])
# Set core-via-tasks version to vanilla/blank/empty-list version
p.core_via_tasks = ParserContext(args=[make_arg()])
# Call .args, expect that the initial value was not overwritten
assert p.args.filename.value == ["some-file"]
class run:
# NOTE: some of these are integration-style tests, but they are still
# fast tests (so not needing to go into the integration suite) and
# touch on transformations to the command line that occur above, or
# around, the actual parser classes/methods (thus not being suitable
# for the parser's own unit tests).
def seeks_and_loads_tasks_module_by_default(self):
expect("foo", out="Hm\n")
def does_not_seek_tasks_module_if_namespace_was_given(self):
expect(
"foo",
err="Task 'foo' not recognised.",
program=Program(namespace=Collection("blank")),
)
def explicit_namespace_works_correctly(self):
# Regression-ish test re #288
ns = Collection.from_module(load("integration"))
expect("print-foo", out="foo\n", program=Program(namespace=ns))
def allows_explicit_task_module_specification(self):
expect("-c integration print-foo", out="foo\n")
def handles_task_arguments(self):
expect("-c integration print-name --name inigo", out="inigo\n")
def can_change_collection_search_root(self):
for flag in ("-r", "--search-root"):
expect(
"{} branch/ alt-root".format(flag),
out="Down with the alt-root!\n",
)
def can_change_collection_search_root_with_explicit_module_name(self):
for flag in ("-r", "--search-root"):
expect(
"{} branch/ -c explicit lyrics".format(flag),
out="Don't swear!\n",
)
@trap
@patch("invoke.program.sys.exit")
def ParseErrors_display_message_and_exit_1(self, mock_exit):
p = Program()
# Run with a definitely-parser-angering incorrect input; the fact
# that this line doesn't raise an exception and thus fail the
# test, is what we're testing...
nah = "nopenotvalidsorry"
p.run("myapp {}".format(nah))
# Expect that we did print the core body of the ParseError (e.g.
# "Command 'foo' not recognised.") and exit 1. (Intent is to display that
# info w/o a full traceback, basically.)
stderr = sys.stderr.getvalue()
assert stderr == "Command '{}' not recognised.\n".format(nah)
mock_exit.assert_called_with(1)
@trap
@patch("invoke.program.sys.exit")
def UnexpectedExit_exits_with_code_when_no_hiding(self, mock_exit):
p = Program()
oops = UnexpectedExit(
Result(command="meh", exited=17, hide=tuple())
)
p.execute = Mock(side_effect=oops)
p.run("myapp foo")
# Expect NO repr printed, because stdout/err were not hidden, so we
# don't want to add extra annoying verbosity - we want to be more
# Make-like here.
assert sys.stderr.getvalue() == ""
# But we still exit with expected code (vs e.g. 1 or 0)
mock_exit.assert_called_with(17)
@trap
@patch("invoke.program.sys.exit")
def shows_UnexpectedExit_str_when_streams_hidden(self, mock_exit):
p = Program()
oops = UnexpectedExit(
Result(
command="meh",
exited=54,
stdout="things!",
stderr="ohnoz!",
encoding="utf-8",
hide=("stdout", "stderr"),
)
)
p.execute = Mock(side_effect=oops)
p.run("myapp foo")
# Expect repr() of exception prints to stderr
# NOTE: this partially duplicates a test in runners.py; whatever.
stderr = sys.stderr.getvalue()
expected = """Encountered a bad command exit code!
Command: 'meh'
Exit code: 54
Stdout:
things!
Stderr:
ohnoz!
"""
assert stderr == expected
# And exit with expected code (vs e.g. 1 or 0)
mock_exit.assert_called_with(54)
@trap
@patch("invoke.program.sys.exit")
def UnexpectedExit_str_encodes_stdout_and_err(self, mock_exit):
p = Program()
oops = UnexpectedExit(
Result(
command="meh",
exited=54,
stdout="this is not ascii: \u1234",
stderr="this is also not ascii: \u4321",
encoding="utf-8",
hide=("stdout", "stderr"),
)
)
p.execute = Mock(side_effect=oops)
p.run("myapp foo")
# NOTE: using explicit binary ASCII here, & accessing raw
# getvalue() of the faked sys.stderr (spec.trap auto-decodes it
# normally) to have a not-quite-tautological test. otherwise we'd
# just be comparing unicode to unicode. shrug?
expected = b"""Encountered a bad command exit code!
Command: 'meh'
Exit code: 54
Stdout:
this is not ascii: \xe1\x88\xb4
Stderr:
this is also not ascii: \xe4\x8c\xa1
"""
got = BytesIO.getvalue(sys.stderr)
assert got == expected
class Exit_:
@patch("invoke.program.sys.exit")
def defaults_to_exiting_0(self, mock_exit):
p = Program()
p.execute = Mock(side_effect=Exit())
p.run("myapp foo")
mock_exit.assert_called_once_with(0)
@trap
@patch("invoke.program.sys.exit")
def prints_message_exiting_1_if_message_given(self, mock_exit):
p = Program()
p.execute = Mock(side_effect=Exit("onoz"))
p.run("myapp foo")
mock_exit.assert_called_once_with(1)
assert sys.stderr.getvalue() == "onoz\n"
@trap
@patch("invoke.program.sys.exit")
def may_explicitly_supply_code_with_message(self, mock_exit):
p = Program()
p.execute = Mock(side_effect=Exit("onoz", code=17))
p.run("myapp foo")
mock_exit.assert_called_once_with(17)
assert sys.stderr.getvalue() == "onoz\n"
@trap
@patch("invoke.program.sys.exit")
def may_explicitly_supply_code_without_message(self, mock_exit):
p = Program()
p.execute = Mock(side_effect=Exit(code=17))
p.run("myapp foo")
mock_exit.assert_called_once_with(17)
assert sys.stderr.getvalue() == ""
def should_show_core_usage_on_core_parse_failures(self):
skip()
def should_show_context_usage_on_context_parse_failures(self):
skip()
@trap
@patch("invoke.program.sys.exit")
def turns_KeyboardInterrupt_into_exit_code_1(self, mock_exit):
p = Program()
p.execute = Mock(side_effect=KeyboardInterrupt)
p.run("myapp -c foo mytask")
mock_exit.assert_called_with(1)
class help_:
"--help"
class core:
def empty_invocation_with_no_default_task_prints_help(self):
stdout, _ = run("-c foo")
assert "Core options:" in stdout
# TODO: On Windows, we don't get a pty, so we don't get a
# guaranteed terminal size of 80x24. Skip for now, but maybe
# a suitable fix would be to just strip all whitespace from the
# returned and expected values before testing. Then terminal
# size is ignored.
@skip_if_windows
def core_help_option_prints_core_help(self):
# TODO: change dynamically based on parser contents?
# e.g. no core args == no [--core-opts],
# no tasks == no task stuff?
# NOTE: test will trigger default pty size of 80x24, so the
# below string is formatted appropriately.
# TODO: add more unit-y tests for specific behaviors:
# * fill terminal w/ columns + spacing
# * line-wrap help text in its own column
expected = """
Usage: inv[oke] [--core-opts] task1 [--task1-opts] ... taskN [--taskN-opts]
Core options:
--complete Print tab-completion candidates for given
parse remainder.
--hide=STRING Set default value of run()'s 'hide' kwarg.
--no-dedupe Disable task deduplication.
--print-completion-script=STRING Print the tab-completion script for your
preferred shell (bash|zsh|fish).
--prompt-for-sudo-password Prompt user at start of session for the
sudo.password config value.
--write-pyc Enable creation of .pyc files.
-c STRING, --collection=STRING Specify collection name to load.
-d, --debug Enable debug output.
-D INT, --list-depth=INT When listing tasks, only show the first
INT levels.
-e, --echo Echo executed commands before running.
-f STRING, --config=STRING Runtime configuration file to use.
-F STRING, --list-format=STRING Change the display format used when
listing tasks. Should be one of: flat
(default), nested, json.
-h [STRING], --help[=STRING] Show core or per-task help and exit.
-l [STRING], --list[=STRING] List available tasks, optionally limited
to a namespace.
-p, --pty Use a pty when executing shell commands.
-r STRING, --search-root=STRING Change root directory used for finding
task modules.
-R, --dry Echo commands instead of running.
-T INT, --command-timeout=INT Specify a global command execution
timeout, in seconds.
-V, --version Show version and exit.
-w, --warn-only Warn, instead of failing, when shell
commands fail.
""".lstrip()
for flag in ["-h", "--help"]:
expect(flag, out=expected, program=main.program)
def bundled_namespace_help_includes_subcommand_listing(self):
t1, t2 = Task(Mock()), Task(Mock())
coll = Collection(task1=t1, task2=t2)
p = Program(namespace=coll)
# Spot checks for expected bits, so we don't have to change
# this every time core args change.
for expected in (
# Usage line changes somewhat
"Usage: myapp [--core-opts] <subcommand> [--subcommand-opts] ...\n", # noqa
# Core options are still present
"Core options:\n",
"--echo",
# Subcommands are listed
"Subcommands:\n",
" task1",
" task2",
):
stdout, _ = run("myapp --help", program=p, invoke=False)
assert expected in stdout
def core_help_doesnt_get_mad_if_loading_fails(self):
# Expects no tasks.py in root of FS
with cd(ROOT):
stdout, _ = run("--help")
assert "Usage: " in stdout
class per_task:
"per-task"
def prints_help_for_task_only(self):
expected = """
Usage: invoke [--core-opts] punch [--options] [other tasks here ...]
Docstring:
none
Options:
-h STRING, --why=STRING Motive
-w STRING, --who=STRING Who to punch
""".lstrip()
for flag in ["-h", "--help"]:
expect("-c decorators {} punch".format(flag), out=expected)
def works_for_unparameterized_tasks(self):
expected = """
Usage: invoke [--core-opts] biz [other tasks here ...]
Docstring:
none
Options:
none
""".lstrip()
expect("-c decorators -h biz", out=expected)
def honors_program_binary(self):
stdout, _ = run(
"-c decorators -h biz", program=Program(binary="notinvoke")
)
assert "Usage: notinvoke" in stdout
def displays_docstrings_if_given(self):
expected = """
Usage: invoke [--core-opts] foo [other tasks here ...]
Docstring:
Foo the bar.
Options:
none
""".lstrip()
expect("-c decorators -h foo", out=expected)
def dedents_correctly(self):
expected = """
Usage: invoke [--core-opts] foo2 [other tasks here ...]
Docstring:
Foo the bar:
example code
Added in 1.0
Options:
none
""".lstrip()
expect("-c decorators -h foo2", out=expected)
def dedents_correctly_for_alt_docstring_style(self):
expected = """
Usage: invoke [--core-opts] foo3 [other tasks here ...]
Docstring:
Foo the other bar:
example code
Added in 1.1
Options:
none
""".lstrip()
expect("-c decorators -h foo3", out=expected)
def exits_after_printing(self):
# TODO: find & test the other variants of this error case, such
# as core --help not exiting, --list not exiting, etc
expected = """
Usage: invoke [--core-opts] punch [--options] [other tasks here ...]
Docstring:
none
Options:
-h STRING, --why=STRING Motive
-w STRING, --who=STRING Who to punch
""".lstrip()
expect("-c decorators -h punch --list", out=expected)
def complains_if_given_invalid_task_name(self):
expect("-h this", err="Task 'this' not recognised.\n")
class task_list:
"--list"
def _listing(self, lines):
return """
Available tasks:
{}
""".format(
"\n".join(" " + x for x in lines)
).lstrip()
def _list_eq(self, collection, listing):
cmd = "-c {} --list".format(collection)
expect(cmd, out=self._listing(listing))
def simple_output(self):
expected = self._listing(
(
"bar",
"biz",
"boz",
"foo",
"post1",
"post2",
"print-foo",
"print-name",
"print-underscored-arg",
)
)
for flag in ("-l", "--list"):
expect("-c integration {}".format(flag), out=expected)
def namespacing(self):
self._list_eq("namespacing", ("toplevel", "module.mytask"))
def top_level_tasks_listed_first(self):
self._list_eq("simple_ns_list", ("z-toplevel", "a.b.subtask"))
def aliases_sorted_alphabetically(self):
self._list_eq("alias_sorting", ("toplevel (a, z)",))
def default_tasks(self):
# sub-ns default task display as "real.name (collection name)"
self._list_eq(
"explicit_root",
(
"top-level (other-top)",
"sub-level.sub-task (sub-level, sub-level.other-sub)",
),
)
def docstrings_shown_alongside(self):
self._list_eq(
"docstrings",
(
"leading-whitespace foo",
"no-docstring",
"one-line foo",
"two-lines foo",
"with-aliases (a, b) foo",
),
)
def docstrings_are_wrapped_to_terminal_width(self):
self._list_eq(
"nontrivial_docstrings",
(
"no-docstring",
"task-one Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n Nullam id dictum", # noqa
"task-two Nulla eget ultrices ante. Curabitur sagittis commodo posuere.\n Duis dapibus", # noqa
),
)
def empty_collections_say_no_tasks(self):
expect(
"-c empty -l", err="No tasks found in collection 'empty'!\n"
)
def nontrivial_trees_are_sorted_by_namespace_and_depth(self):
# By using a larger sample, we can guard against unintuitive
# behaviors arising from the above simple unit style tests. E.g.
# earlier implementations 'broke up' collections that had more than
# 2 levels of depth, because they displayed all 2nd-level tasks
# before any 3rd-level ones.
# The code must square that concern against "show shallow tasks
# before deep ones" (vs straight up alpha sorting)
expected = """Available tasks:
shell (ipython) Load a REPL with project state already
set up.
test (run-tests) Run the test suite with baked-in args.
build.all (build, build.everything) Build all necessary artifacts.
build.c-ext (build.ext) Build our internal C extension.
build.zap A silly way to clean.
build.docs.all (build.docs) Build all doc formats.
build.docs.html Build HTML output only.
build.docs.pdf Build PDF output only.
build.python.all (build.python) Build all Python packages.
build.python.sdist Build classic style tar.gz.
build.python.wheel Build a wheel.
deploy.db (deploy.db-servers) Deploy to our database servers.
deploy.everywhere (deploy) Deploy to all targets.
deploy.web Update and bounce the webservers.
provision.db Stand up one or more DB servers.
provision.web Stand up a Web server.
Default task: test
"""
stdout, _ = run("-c tree --list")
assert expected == stdout
class namespace_limiting:
def argument_limits_display_to_given_namespace(self):
stdout, _ = run("-c tree --list build")
expected = """Available 'build' tasks:
.all (.everything) Build all necessary artifacts.
.c-ext (.ext) Build our internal C extension.
.zap A silly way to clean.
.docs.all (.docs) Build all doc formats.
.docs.html Build HTML output only.
.docs.pdf Build PDF output only.
.python.all (.python) Build all Python packages.
.python.sdist Build classic style tar.gz.
.python.wheel Build a wheel.
Default 'build' task: .all
"""
assert expected == stdout
def argument_may_be_a_nested_namespace(self):
stdout, _ = run("-c tree --list build.docs")
expected = """Available 'build.docs' tasks:
.all Build all doc formats.
.html Build HTML output only.
.pdf Build PDF output only.
Default 'build.docs' task: .all
"""
assert expected == stdout
def empty_namespaces_say_no_tasks_in_namespace(self):
# In other words, outer namespace may not be empty, but the
# inner one is - this should act just like when there is no
# namespace explicitly requested and there's no tasks.
# TODO: should the name in the error message be the fully
# qualified one instead?
expect(
"-c empty_subcollection -l subcollection",
err="No tasks found in collection 'subcollection'!\n", # noqa
)
def invalid_namespaces_exit_with_message(self):
expect(
"-c empty -l nope",
err="Sub-collection 'nope' not found!\n",
)
class depth_limiting:
def limits_display_to_given_depth(self):
# Base case: depth=1 aka "show me the namespaces"
expected = """Available tasks (depth=1):
shell (ipython) Load a REPL with project state already set
up.
test (run-tests) Run the test suite with baked-in args.
build [3 tasks, 2 collections] Tasks for compiling static code and assets.
deploy [3 tasks] How to deploy our code and configs.
provision [2 tasks] System setup code.
Default task: test
"""
stdout, _ = run("-c tree --list -F flat --list-depth 1")
assert expected == stdout
def non_base_case(self):
# Middle case: depth=2
expected = """Available tasks (depth=2):
shell (ipython) Load a REPL with project state already
set up.
test (run-tests) Run the test suite with baked-in args.
build.all (build, build.everything) Build all necessary artifacts.
build.c-ext (build.ext) Build our internal C extension.
build.zap A silly way to clean.
build.docs [3 tasks] Tasks for managing Sphinx docs.
build.python [3 tasks] PyPI/etc distribution artifacts.
deploy.db (deploy.db-servers) Deploy to our database servers.
deploy.everywhere (deploy) Deploy to all targets.
deploy.web Update and bounce the webservers.
provision.db Stand up one or more DB servers.
provision.web Stand up a Web server.
Default task: test
"""
stdout, _ = run("-c tree --list --list-depth=2")
assert expected == stdout
def depth_can_be_deeper_than_real_depth(self):
# Edge case: depth > actual depth = same as no depth arg
expected = """Available tasks (depth=5):
shell (ipython) Load a REPL with project state already
set up.
test (run-tests) Run the test suite with baked-in args.
build.all (build, build.everything) Build all necessary artifacts.
build.c-ext (build.ext) Build our internal C extension.
build.zap A silly way to clean.
build.docs.all (build.docs) Build all doc formats.
build.docs.html Build HTML output only.
build.docs.pdf Build PDF output only.
build.python.all (build.python) Build all Python packages.
build.python.sdist Build classic style tar.gz.
build.python.wheel Build a wheel.
deploy.db (deploy.db-servers) Deploy to our database servers.
deploy.everywhere (deploy) Deploy to all targets.
deploy.web Update and bounce the webservers.
provision.db Stand up one or more DB servers.
provision.web Stand up a Web server.
Default task: test
"""
stdout, _ = run("-c tree --list --list-depth=5")
assert expected == stdout
def works_with_explicit_namespace(self):
expected = """Available 'build' tasks (depth=1):
.all (.everything) Build all necessary artifacts.
.c-ext (.ext) Build our internal C extension.
.zap A silly way to clean.
.docs [3 tasks] Tasks for managing Sphinx docs.
.python [3 tasks] PyPI/etc distribution artifacts.
Default 'build' task: .all
"""
stdout, _ = run("-c tree --list build --list-depth=1")
assert expected == stdout
def short_flag_is_D(self):
expected = """Available tasks (depth=1):
shell (ipython) Load a REPL with project state already set
up.
test (run-tests) Run the test suite with baked-in args.
build [3 tasks, 2 collections] Tasks for compiling static code and assets.
deploy [3 tasks] How to deploy our code and configs.
provision [2 tasks] System setup code.
Default task: test