-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathrunners.py
More file actions
1857 lines (1575 loc) · 68.9 KB
/
runners.py
File metadata and controls
1857 lines (1575 loc) · 68.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import errno
import os
import signal
import struct
import sys
import termios
import threading
import types
from io import StringIO
from io import BytesIO
from itertools import chain, repeat
from pytest import raises, skip
from pytest_relaxed import trap
from unittest.mock import patch, Mock, call
from invoke import (
CommandTimedOut,
Config,
Context,
Failure,
Local,
Promise,
Responder,
Result,
Runner,
StreamWatcher,
SubprocessPipeError,
ThreadException,
UnexpectedExit,
WatcherError,
)
from invoke.runners import default_encoding
from invoke.terminals import WINDOWS
from _util import (
mock_subprocess,
mock_pty,
skip_if_windows,
_Dummy,
_KeyboardInterruptingRunner,
OhNoz,
_,
)
class _RaisingWatcher(StreamWatcher):
def submit(self, stream):
raise WatcherError("meh")
class _GenericException(Exception):
pass
class _GenericExceptingRunner(_Dummy):
def wait(self):
raise _GenericException
def _run(*args, **kwargs):
klass = kwargs.pop("klass", _Dummy)
settings = kwargs.pop("settings", {})
context = Context(config=Config(overrides=settings))
return klass(context).run(*args, **kwargs)
def _runner(out="", err="", **kwargs):
klass = kwargs.pop("klass", _Dummy)
runner = klass(Context(config=Config(overrides=kwargs)))
if "exits" in kwargs:
runner.returncode = Mock(return_value=kwargs.pop("exits"))
out_file = BytesIO(out.encode())
err_file = BytesIO(err.encode())
runner.read_proc_stdout = out_file.read
runner.read_proc_stderr = err_file.read
return runner
def _expect_platform_shell(shell):
if WINDOWS:
assert shell.endswith("cmd.exe")
else:
assert shell == "bash"
def _make_tcattrs(cc_is_ints=True, echo=False):
# Set up the control character sub-array; it's technically platform
# dependent so we need to be dynamic.
# NOTE: setting this up so we can test both potential values for
# the 'cc' members...docs say ints, reality says one-byte
# bytestrings...
cc_base = [None] * (max(termios.VMIN, termios.VTIME) + 1)
cc_ints, cc_bytes = cc_base.copy(), cc_base.copy()
cc_ints[termios.VMIN], cc_ints[termios.VTIME] = 1, 0
cc_bytes[termios.VMIN], cc_bytes[termios.VTIME] = b"\x01", b"\x00"
# Set tcgetattr to look like it's already cbroken...
attrs = [
# iflag, oflag, cflag - don't care
None,
None,
None,
# lflag needs to have ECHO and ICANON unset
~(termios.ECHO | termios.ICANON),
# ispeed, ospeed - don't care
None,
None,
# cc - care about its VMIN and VTIME members.
cc_ints if cc_is_ints else cc_bytes,
]
# Undo the ECHO unset if caller wants this to look like a non-cbroken term
if echo:
attrs[3] = attrs[3] | termios.ECHO
return attrs
class _TimingOutRunner(_Dummy):
@property
def timed_out(self):
return True
class Runner_:
_stop_methods = ["generate_result", "stop"]
# NOTE: these copies of _run and _runner form the base case of "test Runner
# subclasses via self._run/_runner helpers" functionality. See how e.g.
# Local_ uses the same approach but bakes in the dummy class used.
def _run(self, *args, **kwargs):
return _run(*args, **kwargs)
def _runner(self, *args, **kwargs):
return _runner(*args, **kwargs)
def _mock_stdin_writer(self):
"""
Return new _Dummy subclass whose write_proc_stdin() method is a mock.
"""
class MockedStdin(_Dummy):
pass
MockedStdin.write_proc_stdin = Mock()
return MockedStdin
class init:
"__init__"
def takes_a_context_instance(self):
c = Context()
assert Runner(c).context == c
def context_instance_is_required(self):
with raises(TypeError):
Runner()
class run:
def handles_invalid_kwargs_like_any_other_function(self):
try:
self._run(_, nope_noway_nohow="as if")
except TypeError as e:
assert "got an unexpected keyword argument" in str(e)
else:
assert False, "Invalid run() kwarg didn't raise TypeError"
class warn:
def honors_config(self):
runner = self._runner(run={"warn": True}, exits=1)
# Doesn't raise Failure -> all good
runner.run(_)
def kwarg_beats_config(self):
runner = self._runner(run={"warn": False}, exits=1)
# Doesn't raise Failure -> all good
runner.run(_, warn=True)
def does_not_apply_to_watcher_errors(self):
runner = self._runner(out="stuff")
try:
watcher = _RaisingWatcher()
runner.run(_, watchers=[watcher], warn=True, hide=True)
except Failure as e:
assert isinstance(e.reason, WatcherError)
else:
assert False, "Did not raise Failure for WatcherError!"
def does_not_apply_to_timeout_errors(self):
with raises(CommandTimedOut):
self._runner(klass=_TimingOutRunner).run(
_, timeout=1, warn=True
)
class hide:
@trap
def honors_config(self):
runner = self._runner(out="stuff", run={"hide": True})
r = runner.run(_)
assert r.stdout == "stuff"
assert sys.stdout.getvalue() == ""
@trap
def kwarg_beats_config(self):
runner = self._runner(out="stuff")
r = runner.run(_, hide=True)
assert r.stdout == "stuff"
assert sys.stdout.getvalue() == ""
class pty:
def pty_defaults_to_off(self):
assert self._run(_).pty is False
def honors_config(self):
runner = self._runner(run={"pty": True})
assert runner.run(_).pty is True
def kwarg_beats_config(self):
runner = self._runner(run={"pty": False})
assert runner.run(_, pty=True).pty is True
class shell:
def defaults_to_bash_or_cmdexe_when_pty_True(self):
_expect_platform_shell(self._run(_, pty=True).shell)
def defaults_to_bash_or_cmdexe_when_pty_False(self):
_expect_platform_shell(self._run(_, pty=False).shell)
def may_be_overridden(self):
assert self._run(_, shell="/bin/zsh").shell == "/bin/zsh"
def may_be_configured(self):
runner = self._runner(run={"shell": "/bin/tcsh"})
assert runner.run(_).shell == "/bin/tcsh"
def kwarg_beats_config(self):
runner = self._runner(run={"shell": "/bin/tcsh"})
assert runner.run(_, shell="/bin/zsh").shell == "/bin/zsh"
class env:
def defaults_to_os_environ(self):
assert self._run(_).env == os.environ
def updates_when_dict_given(self):
expected = dict(os.environ, FOO="BAR")
assert self._run(_, env={"FOO": "BAR"}).env == expected
def replaces_when_replace_env_True(self):
env = self._run(_, env={"JUST": "ME"}, replace_env=True).env
assert env == {"JUST": "ME"}
def config_can_be_used(self):
env = self._run(_, settings={"run": {"env": {"FOO": "BAR"}}}).env
assert env == dict(os.environ, FOO="BAR")
def kwarg_wins_over_config(self):
settings = {"run": {"env": {"FOO": "BAR"}}}
kwarg = {"FOO": "NOTBAR"}
foo = self._run(_, settings=settings, env=kwarg).env["FOO"]
assert foo == "NOTBAR"
class return_value:
def return_code(self):
"""
Result has .return_code (and .exited) containing exit code int
"""
runner = self._runner(exits=17)
r = runner.run(_, warn=True)
assert r.return_code == 17
assert r.exited == 17
def ok_attr_indicates_success(self):
runner = self._runner()
assert runner.run(_).ok is True # default dummy retval is 0
def ok_attr_indicates_failure(self):
runner = self._runner(exits=1)
assert runner.run(_, warn=True).ok is False
def failed_attr_indicates_success(self):
runner = self._runner()
assert runner.run(_).failed is False # default dummy retval is 0
def failed_attr_indicates_failure(self):
runner = self._runner(exits=1)
assert runner.run(_, warn=True).failed is True
@trap
def stdout_attribute_contains_stdout(self):
runner = self._runner(out="foo")
assert runner.run(_).stdout == "foo"
assert sys.stdout.getvalue() == "foo"
@trap
def stderr_attribute_contains_stderr(self):
runner = self._runner(err="foo")
assert runner.run(_).stderr == "foo"
assert sys.stderr.getvalue() == "foo"
def whether_pty_was_used(self):
assert self._run(_).pty is False
assert self._run(_, pty=True).pty is True
def command_executed(self):
assert self._run(_).command == _
def shell_used(self):
_expect_platform_shell(self._run(_).shell)
def hide_param_exposed_and_normalized(self):
assert self._run(_, hide=True).hide, "stdout" == "stderr"
assert self._run(_, hide=False).hide == tuple()
assert self._run(_, hide="stderr").hide == ("stderr",)
class command_echoing:
@trap
def off_by_default(self):
self._run("my command")
assert sys.stdout.getvalue() == ""
@trap
def enabled_via_kwarg(self):
self._run("my command", echo=True)
assert "my command" in sys.stdout.getvalue()
@trap
def enabled_via_config(self):
self._run("yup", settings={"run": {"echo": True}})
assert "yup" in sys.stdout.getvalue()
@trap
def kwarg_beats_config(self):
self._run("yup", echo=True, settings={"run": {"echo": False}})
assert "yup" in sys.stdout.getvalue()
@trap
def uses_ansi_bold(self):
self._run("my command", echo=True)
# TODO: vendor & use a color module
assert sys.stdout.getvalue() == "\x1b[1;37mmy command\x1b[0m\n"
@trap
def uses_custom_format(self):
self._run(
"my command",
echo=True,
settings={"run": {"echo_format": "AA{command}ZZ"}},
)
assert sys.stdout.getvalue() == "AAmy commandZZ\n"
class dry_running:
@trap
def sets_echo_to_True(self):
self._run("what up", settings={"run": {"dry": True}})
assert "what up" in sys.stdout.getvalue()
@trap
def short_circuits_with_dummy_result(self):
runner = self._runner(run={"dry": True})
# Using the call to self.start() in _run_body() as a sentinel for
# all the work beyond it.
runner.start = Mock()
result = runner.run(_)
assert not runner.start.called
assert isinstance(result, Result)
assert result.command == _
assert result.stdout == ""
assert result.stderr == ""
assert result.exited == 0
assert result.pty is False
class encoding:
# NOTE: these tests just check what Runner.encoding ends up as; it's
# difficult/impossible to mock string objects themselves to see what
# .decode() is being given :(
#
# TODO: consider using truly "nonstandard"-encoded byte sequences as
# fixtures, encoded with something that isn't compatible with UTF-8
# (UTF-7 kinda is, so...) so we can assert that the decoded string is
# equal to its Unicode equivalent.
#
# Use UTF-7 as a valid encoding unlikely to be a real default derived
# from test-runner's locale.getpreferredencoding()
def defaults_to_encoding_method_result(self):
# Setup
runner = self._runner()
encoding = "UTF-7"
runner.default_encoding = Mock(return_value=encoding)
# Execution & assertion
runner.run(_)
runner.default_encoding.assert_called_with()
assert runner.encoding == "UTF-7"
def honors_config(self):
c = Context(Config(overrides={"run": {"encoding": "UTF-7"}}))
runner = _Dummy(c)
runner.default_encoding = Mock(return_value="UTF-not-7")
runner.run(_)
assert runner.encoding == "UTF-7"
def honors_kwarg(self):
skip()
def uses_locale_module_for_default_encoding(self):
# Actually testing this highly OS/env specific stuff is very
# error-prone; so we degrade to just testing expected function
# calls for now :(
with patch("invoke.runners.locale") as fake_locale:
fake_locale.getdefaultlocale.return_value = ("meh", "UHF-8")
fake_locale.getpreferredencoding.return_value = "FALLBACK"
assert self._runner().default_encoding() == "FALLBACK"
def falls_back_to_defaultlocale_when_preferredencoding_is_None(self):
with patch("invoke.runners.locale") as fake_locale:
fake_locale.getdefaultlocale.return_value = (None, None)
fake_locale.getpreferredencoding.return_value = "FALLBACK"
assert self._runner().default_encoding() == "FALLBACK"
class output_hiding:
@trap
def _expect_hidden(self, hide, expect_out="", expect_err=""):
self._runner(out="foo", err="bar").run(_, hide=hide)
assert sys.stdout.getvalue() == expect_out
assert sys.stderr.getvalue() == expect_err
def both_hides_everything(self):
self._expect_hidden("both")
def True_hides_everything(self):
self._expect_hidden(True)
def out_only_hides_stdout(self):
self._expect_hidden("out", expect_out="", expect_err="bar")
def err_only_hides_stderr(self):
self._expect_hidden("err", expect_out="foo", expect_err="")
def accepts_stdout_alias_for_out(self):
self._expect_hidden("stdout", expect_out="", expect_err="bar")
def accepts_stderr_alias_for_err(self):
self._expect_hidden("stderr", expect_out="foo", expect_err="")
def None_hides_nothing(self):
self._expect_hidden(None, expect_out="foo", expect_err="bar")
def False_hides_nothing(self):
self._expect_hidden(False, expect_out="foo", expect_err="bar")
def unknown_vals_raises_ValueError(self):
with raises(ValueError):
self._run(_, hide="wat?")
def unknown_vals_mention_value_given_in_error(self):
value = "penguinmints"
try:
self._run(_, hide=value)
except ValueError as e:
msg = "Error from run(hide=xxx) did not tell user what the bad value was!" # noqa
msg += "\nException msg: {}".format(e)
assert value in str(e), msg
else:
assert (
False
), "run() did not raise ValueError for bad hide= value" # noqa
def does_not_affect_capturing(self):
assert self._runner(out="foo").run(_, hide=True).stdout == "foo"
@trap
def overrides_echoing(self):
self._runner().run("invisible", hide=True, echo=True)
assert "invisible" not in sys.stdout.getvalue()
class output_stream_overrides:
@trap
def out_defaults_to_sys_stdout(self):
"out_stream defaults to sys.stdout"
self._runner(out="sup").run(_)
assert sys.stdout.getvalue() == "sup"
@trap
def err_defaults_to_sys_stderr(self):
"err_stream defaults to sys.stderr"
self._runner(err="sup").run(_)
assert sys.stderr.getvalue() == "sup"
@trap
def out_can_be_overridden(self):
"out_stream can be overridden"
out = StringIO()
self._runner(out="sup").run(_, out_stream=out)
assert out.getvalue() == "sup"
assert sys.stdout.getvalue() == ""
@trap
def overridden_out_is_never_hidden(self):
out = StringIO()
self._runner(out="sup").run(_, out_stream=out, hide=True)
assert out.getvalue() == "sup"
assert sys.stdout.getvalue() == ""
@trap
def err_can_be_overridden(self):
"err_stream can be overridden"
err = StringIO()
self._runner(err="sup").run(_, err_stream=err)
assert err.getvalue() == "sup"
assert sys.stderr.getvalue() == ""
@trap
def overridden_err_is_never_hidden(self):
err = StringIO()
self._runner(err="sup").run(_, err_stream=err, hide=True)
assert err.getvalue() == "sup"
assert sys.stderr.getvalue() == ""
@trap
def pty_defaults_to_sys(self):
self._runner(out="sup").run(_, pty=True)
assert sys.stdout.getvalue() == "sup"
@trap
def pty_out_can_be_overridden(self):
out = StringIO()
self._runner(out="yo").run(_, pty=True, out_stream=out)
assert out.getvalue() == "yo"
assert sys.stdout.getvalue() == ""
class output_stream_handling:
# Mostly corner cases, generic behavior's covered above
def writes_and_flushes_to_stdout(self):
out = Mock(spec=StringIO)
self._runner(out="meh").run(_, out_stream=out)
out.write.assert_called_once_with("meh")
out.flush.assert_called_once_with()
def writes_and_flushes_to_stderr(self):
err = Mock(spec=StringIO)
self._runner(err="whatever").run(_, err_stream=err)
err.write.assert_called_once_with("whatever")
err.flush.assert_called_once_with()
class input_stream_handling:
# NOTE: actual autoresponder tests are elsewhere. These just test that
# stdin works normally & can be overridden.
@patch("invoke.runners.sys.stdin", StringIO("Text!"))
def defaults_to_sys_stdin(self):
# Execute w/ runner class that has a mocked stdin_writer
klass = self._mock_stdin_writer()
self._runner(klass=klass).run(_, out_stream=StringIO())
# Check that mocked writer was called w/ the data from our patched
# sys.stdin.
# NOTE: this also tests that non-fileno-bearing streams read/write
# 1 byte at a time. See farther-down test for fileno-bearing stdin
calls = list(map(lambda x: call(x), "Text!"))
klass.write_proc_stdin.assert_has_calls(calls, any_order=False)
def can_be_overridden(self):
klass = self._mock_stdin_writer()
in_stream = StringIO("Hey, listen!")
self._runner(klass=klass).run(
_, in_stream=in_stream, out_stream=StringIO()
)
# stdin mirroring occurs char-by-char
calls = list(map(lambda x: call(x), "Hey, listen!"))
klass.write_proc_stdin.assert_has_calls(calls, any_order=False)
def can_be_disabled_entirely(self):
# Mock handle_stdin so we can assert it's not even called
class MockedHandleStdin(_Dummy):
pass
MockedHandleStdin.handle_stdin = Mock()
self._runner(klass=MockedHandleStdin).run(
_, in_stream=False # vs None or a stream
)
assert not MockedHandleStdin.handle_stdin.called
@patch("invoke.util.debug")
def exceptions_get_logged(self, mock_debug):
# Make write_proc_stdin asplode
klass = self._mock_stdin_writer()
klass.write_proc_stdin.side_effect = OhNoz("oh god why")
# Execute with some stdin to trigger that asplode (but skip the
# actual bubbled-up raising of it so we can check things out)
try:
stdin = StringIO("non-empty")
self._runner(klass=klass).run(_, in_stream=stdin)
except ThreadException:
pass
# Assert debug() was called w/ expected format
# TODO: make the debug call a method on ExceptionHandlingThread,
# then make thread class configurable somewhere in Runner, and pass
# in a customized ExceptionHandlingThread that has a Mock for that
# method?
# NOTE: splitting into a few asserts to work around python 3.7
# change re: trailing comma, which kills ability to just statically
# assert the entire string. Sigh. Also I'm too lazy to regex.
msg = mock_debug.call_args[0][0]
assert "Encountered exception OhNoz" in msg
assert "'oh god why'" in msg
assert "in thread for 'handle_stdin'" in msg
def EOF_triggers_closing_of_proc_stdin(self):
class Fake(_Dummy):
pass
Fake.close_proc_stdin = Mock()
self._runner(klass=Fake).run(_, in_stream=StringIO("what?"))
Fake.close_proc_stdin.assert_called_once_with()
def EOF_does_not_close_proc_stdin_when_pty_True(self):
class Fake(_Dummy):
pass
Fake.close_proc_stdin = Mock()
self._runner(klass=Fake).run(
_, in_stream=StringIO("what?"), pty=True
)
assert not Fake.close_proc_stdin.called
@patch("invoke.runners.sys.stdin")
def EBADF_on_stdin_read_ignored(self, fake_stdin):
# Issue #659: nohup is a jerk
fake_stdin.read.side_effect = OSError(errno.EBADF, "Ugh")
# No boom == fixed
self._runner().run(_)
@patch("invoke.runners.sys.stdin")
def non_EBADF_on_stdin_read_not_ignored(self, fake_stdin):
# Issue #659: nohup is a jerk, inverse case
eio = OSError(errno.EIO, "lol")
fake_stdin.read.side_effect = eio
with raises(ThreadException) as info:
self._runner().run(_)
assert info.value.exceptions[0].value is eio
class failure_handling:
def fast_failures(self):
with raises(UnexpectedExit):
self._runner(exits=1).run(_)
def non_1_return_codes_still_act_as_failure(self):
r = self._runner(exits=17).run(_, warn=True)
assert r.failed is True
class Failure_repr:
def defaults_to_just_class_and_command(self):
expected = "<Failure: cmd='oh hecc'>"
assert repr(Failure(Result(command="oh hecc"))) == expected
def subclasses_may_add_more_kv_pairs(self):
class TotalFailure(Failure):
def _repr(self, **kwargs):
return super()._repr(mood="dejected")
expected = "<TotalFailure: cmd='onoz' mood=dejected>"
assert repr(TotalFailure(Result(command="onoz"))) == expected
class UnexpectedExit_repr:
def similar_to_just_the_result_repr(self):
try:
self._runner(exits=23).run(_)
except UnexpectedExit as e:
expected = "<UnexpectedExit: cmd='{}' exited=23>"
assert repr(e) == expected.format(_)
class UnexpectedExit_str:
def setup_method(self):
def lines(prefix):
prefixed = "\n".join(
"{} {}".format(prefix, x) for x in range(1, 26)
)
return prefixed + "\n"
self._stdout = lines("stdout")
self._stderr = lines("stderr")
@trap
def displays_command_and_exit_code_by_default(self):
try:
self._runner(
exits=23, out=self._stdout, err=self._stderr
).run(_)
except UnexpectedExit as e:
expected = """Encountered a bad command exit code!
Command: '{}'
Exit code: 23
Stdout: already printed
Stderr: already printed
"""
assert str(e) == expected.format(_)
else:
assert False, "Failed to raise UnexpectedExit!"
@trap
def does_not_display_stderr_when_pty_True(self):
try:
self._runner(
exits=13, out=self._stdout, err=self._stderr
).run(_, pty=True)
except UnexpectedExit as e:
expected = """Encountered a bad command exit code!
Command: '{}'
Exit code: 13
Stdout: already printed
Stderr: n/a (PTYs have no stderr)
"""
assert str(e) == expected.format(_)
@trap
def pty_stderr_message_wins_over_hidden_stderr(self):
try:
self._runner(
exits=1, out=self._stdout, err=self._stderr
).run(_, pty=True, hide=True)
except UnexpectedExit as e:
r = str(e)
assert "Stderr: n/a (PTYs have no stderr)" in r
assert "Stderr: already printed" not in r
@trap
def explicit_hidden_stream_tail_display(self):
# All the permutations of what's displayed when, are in
# subsequent test, which does 'x in y' assertions; this one
# here ensures the actual format of the display (newlines, etc)
# is as desired.
try:
self._runner(
exits=77, out=self._stdout, err=self._stderr
).run(_, hide=True)
except UnexpectedExit as e:
expected = """Encountered a bad command exit code!
Command: '{}'
Exit code: 77
Stdout:
stdout 16
stdout 17
stdout 18
stdout 19
stdout 20
stdout 21
stdout 22
stdout 23
stdout 24
stdout 25
Stderr:
stderr 16
stderr 17
stderr 18
stderr 19
stderr 20
stderr 21
stderr 22
stderr 23
stderr 24
stderr 25
"""
assert str(e) == expected.format(_)
@trap
def displays_tails_of_streams_only_when_hidden(self):
def oops(msg, r, hide):
return "{}! hide={}; str output:\n\n{}".format(
msg, hide, r
)
for hide, expect_out, expect_err in (
(False, False, False),
(True, True, True),
("stdout", True, False),
("stderr", False, True),
("both", True, True),
):
try:
self._runner(
exits=1, out=self._stdout, err=self._stderr
).run(_, hide=hide)
except UnexpectedExit as e:
r = str(e)
# Expect that the top of output is never displayed
err = oops("Too much stdout found", r, hide)
assert "stdout 15" not in r, err
err = oops("Too much stderr found", r, hide)
assert "stderr 15" not in r, err
# Expect to see tail of stdout if we expected it
if expect_out:
err = oops("Didn't see stdout", r, hide)
assert "stdout 16" in r, err
# Expect to see tail of stderr if we expected it
if expect_err:
err = oops("Didn't see stderr", r, hide)
assert "stderr 16" in r, err
else:
assert False, "Failed to raise UnexpectedExit!"
def _regular_error(self):
self._runner(exits=1).run(_)
def _watcher_error(self):
klass = self._mock_stdin_writer()
# Exited=None because real procs will have no useful .returncode()
# result if they're aborted partway via an exception.
runner = self._runner(klass=klass, out="stuff", exits=None)
runner.run(_, watchers=[_RaisingWatcher()], hide=True)
# TODO: may eventually turn into having Runner raise distinct Failure
# subclasses itself, at which point `reason` would probably go away.
class reason:
def is_None_for_regular_nonzero_exits(self):
try:
self._regular_error()
except Failure as e:
assert e.reason is None
else:
assert False, "Failed to raise Failure!"
def is_None_for_custom_command_exits(self):
# TODO: when we implement 'exitcodes 1 and 2 are actually OK'
skip()
def is_exception_when_WatcherError_raised_internally(self):
try:
self._watcher_error()
except Failure as e:
assert isinstance(e.reason, WatcherError)
else:
assert False, "Failed to raise Failure!"
# TODO: should these move elsewhere, eg to Result specific test file?
# TODO: *is* there a nice way to split into multiple Response and/or
# Failure subclasses? Given the split between "returned as a value when
# no problem" and "raised as/attached to an exception when problem",
# possibly not - complicates how the APIs need to be adhered to.
class wrapped_result:
def most_attrs_are_always_present(self):
attrs = ("command", "shell", "env", "stdout", "stderr", "pty")
for method in (self._regular_error, self._watcher_error):
try:
method()
except Failure as e:
for attr in attrs:
assert getattr(e.result, attr) is not None
else:
assert False, "Did not raise Failure!"
class shell_exit_failure:
def exited_is_integer(self):
try:
self._regular_error()
except Failure as e:
assert isinstance(e.result.exited, int)
else:
assert False, "Did not raise Failure!"
def ok_bool_etc_are_falsey(self):
try:
self._regular_error()
except Failure as e:
assert e.result.ok is False
assert e.result.failed is True
assert not bool(e.result)
assert not e.result
else:
assert False, "Did not raise Failure!"
def stringrep_notes_exit_status(self):
try:
self._regular_error()
except Failure as e:
assert "exited with status 1" in str(e.result)
else:
assert False, "Did not raise Failure!"
class watcher_failure:
def exited_is_None(self):
try:
self._watcher_error()
except Failure as e:
exited = e.result.exited
err = "Expected None, got {!r}".format(exited)
assert exited is None, err
def ok_and_bool_still_are_falsey(self):
try:
self._watcher_error()
except Failure as e:
assert e.result.ok is False
assert e.result.failed is True
assert not bool(e.result)
assert not e.result
else:
assert False, "Did not raise Failure!"
def stringrep_lacks_exit_status(self):
try:
self._watcher_error()
except Failure as e:
assert "exited with status" not in str(e.result)
expected = "not fully executed due to watcher error"
assert expected in str(e.result)
else:
assert False, "Did not raise Failure!"
class threading:
# NOTE: see also the more generic tests in concurrency.py
def errors_within_io_thread_body_bubble_up(self):
class Oops(_Dummy):
def handle_stdout(self, **kwargs):
raise OhNoz()
def handle_stderr(self, **kwargs):
raise OhNoz()
runner = Oops(Context())
try:
runner.run("nah")
except ThreadException as e:
# Expect two separate OhNoz objects on 'e'
assert len(e.exceptions) == 2
for tup in e.exceptions:
assert isinstance(tup.value, OhNoz)
assert isinstance(tup.traceback, types.TracebackType)
assert tup.type == OhNoz
# TODO: test the arguments part of the tuple too. It's pretty
# implementation-specific, though, so possibly not worthwhile.
else:
assert False, "Did not raise ThreadException as expected!"
def io_thread_errors_str_has_details(self):
class Oops(_Dummy):
def handle_stdout(self, **kwargs):
raise OhNoz()
runner = Oops(Context())
try:
runner.run("nah")
except ThreadException as e:
message = str(e)
# Just make sure salient bits appear present, vs e.g. default
# representation happening instead.
assert "Saw 1 exceptions within threads" in message
assert "{'kwargs': " in message
assert "Traceback (most recent call last):\n\n" in message
assert "OhNoz" in message
else:
assert False, "Did not raise ThreadException as expected!"
class watchers:
# NOTE: it's initially tempting to consider using mocks or stub
# Responder instances for many of these, but it really doesn't save
# appreciable runtime or code read/write time.
# NOTE: these strictly test interactions between
# StreamWatcher/Responder and their host Runner; Responder-only tests
# are in tests/watchers.py.
def nothing_is_written_to_stdin_by_default(self):
# NOTE: technically if some goofus ran the tests by hand and mashed
# keys while doing so...this would fail. LOL?
# NOTE: this test seems not too useful but is a) a sanity test and
# b) guards against e.g. breaking the autoresponder such that it
# responds to "" or "\n" or etc.
klass = self._mock_stdin_writer()
self._runner(klass=klass).run(_)
assert not klass.write_proc_stdin.called
def _expect_response(self, **kwargs):
"""
Execute a run() w/ ``watchers`` set from ``responses``.
Any other ``**kwargs`` given are passed direct to ``_runner()``.
:returns: The mocked ``write_proc_stdin`` method of the runner.
"""
watchers = [
Responder(pattern=key, response=value)
for key, value in kwargs.pop("responses").items()
]
kwargs["klass"] = klass = self._mock_stdin_writer()
runner = self._runner(**kwargs)
runner.run(_, watchers=watchers, hide=True)
return klass.write_proc_stdin
def watchers_responses_get_written_to_proc_stdin(self):