-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathtest_cmd2.py
More file actions
4626 lines (3438 loc) · 153 KB
/
test_cmd2.py
File metadata and controls
4626 lines (3438 loc) · 153 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
"""Cmd2 unit/functional testing"""
import io
import os
import signal
import sys
import tempfile
from code import InteractiveConsole
from typing import (
NoReturn,
cast,
)
from unittest import mock
import pytest
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import DummyCompleter
from prompt_toolkit.input import DummyInput, create_pipe_input
from prompt_toolkit.output import DummyOutput
from prompt_toolkit.shortcuts import PromptSession
from rich.text import Text
import cmd2
from cmd2 import (
COMMAND_NAME,
Cmd2Style,
Color,
CommandSet,
Completions,
RichPrintKwargs,
clipboard,
constants,
exceptions,
plugin,
stylize,
utils,
)
from cmd2 import rich_utils as ru
from cmd2 import string_utils as su
from cmd2.types import BoundCommandFunc
from .conftest import (
SHORTCUTS_TXT,
normalize,
odd_file_names,
run_cmd,
verify_help_text,
with_ansi_style,
)
def create_outsim_app():
c = cmd2.Cmd()
c.stdout = utils.StdSim(c.stdout)
return c
@pytest.fixture
def outsim_app():
return create_outsim_app()
def test_version(base_app) -> None:
assert cmd2.__version__
def test_not_in_main_thread(base_app, capsys) -> None:
import threading
# Mock threading.main_thread() to return our fake thread
saved_main_thread = threading.main_thread
fake_main = threading.Thread()
threading.main_thread = mock.MagicMock(name="main_thread", return_value=fake_main)
with pytest.raises(RuntimeError) as excinfo:
base_app.cmdloop()
# Restore threading.main_thread()
threading.main_thread = saved_main_thread
assert "cmdloop must be run in the main thread" in str(excinfo.value)
def test_empty_statement(base_app) -> None:
out, _err = run_cmd(base_app, "")
expected = normalize("")
assert out == expected
def test_base_help(base_app) -> None:
out, _err = run_cmd(base_app, "help")
assert base_app.last_result is True
verify_help_text(base_app, out)
def test_base_help_verbose(base_app) -> None:
out, _err = run_cmd(base_app, "help -v")
assert base_app.last_result is True
verify_help_text(base_app, out)
# Make sure :param type lines are filtered out of help summary
help_doc = base_app.do_help.__func__.__doc__
help_doc += "\n:param fake param"
base_app.do_help.__func__.__doc__ = help_doc
out, _err = run_cmd(base_app, "help --verbose")
assert base_app.last_result is True
verify_help_text(base_app, out)
assert ":param" not in "".join(out)
def test_base_argparse_help(base_app) -> None:
# Verify that "set -h" gives the same output as "help set" and that it starts in a way that makes sense
out1, _err1 = run_cmd(base_app, "set -h")
out2, _err2 = run_cmd(base_app, "help set")
assert out1 == out2
assert out1[0].startswith("Usage: set")
assert out1[1] == ""
assert out1[2].startswith("Set a settable parameter")
def test_base_invalid_option(base_app) -> None:
_out, err = run_cmd(base_app, "set -z")
assert err[0] == "Usage: set [-h] [param] [value]"
assert "Error: unrecognized arguments: -z" in err[1]
def test_base_shortcuts(base_app) -> None:
out, _err = run_cmd(base_app, "shortcuts")
expected = normalize(SHORTCUTS_TXT)
assert out == expected
assert base_app.last_result is True
def test_command_starts_with_shortcut() -> None:
expected_err = "Invalid command name 'help'"
with pytest.raises(ValueError, match=expected_err):
cmd2.Cmd(shortcuts={"help": "fake"})
def test_base_set(base_app) -> None:
# Make sure all settables appear in output.
out, _err = run_cmd(base_app, "set")
settables = sorted(base_app.settables.keys())
# The settables will appear in order in the table.
# Go line-by-line until all settables are found.
for line in out:
if not settables:
break
if line.lstrip().startswith(settables[0]):
settables.pop(0)
# This will be empty if we found all settables in the output.
assert not settables
# Make sure all settables appear in last_result.
assert len(base_app.last_result) == len(base_app.settables)
for param in base_app.last_result:
assert base_app.last_result[param] == base_app.settables[param].value
def test_set(base_app) -> None:
out, _err = run_cmd(base_app, "set quiet True")
expected = normalize(
"""
quiet - was: False
now: True
"""
)
assert out == expected
assert base_app.last_result is True
line_found = False
out, _err = run_cmd(base_app, "set quiet")
for line in out:
if "quiet" in line and "True" in line and "False" not in line:
line_found = True
break
assert line_found
assert len(base_app.last_result) == 1
assert base_app.last_result["quiet"] is True
def test_set_val_empty(base_app) -> None:
base_app.editor = "fake"
_out, _err = run_cmd(base_app, 'set editor ""')
assert base_app.editor == ""
assert base_app.last_result is True
def test_set_val_is_flag(base_app) -> None:
base_app.editor = "fake"
_out, _err = run_cmd(base_app, 'set editor "-h"')
assert base_app.editor == "-h"
assert base_app.last_result is True
def test_set_not_supported(base_app) -> None:
_out, err = run_cmd(base_app, "set qqq True")
expected = normalize(
"""
Parameter 'qqq' not supported (type 'set' for list of parameters).
"""
)
assert err == expected
assert base_app.last_result is False
def test_set_no_settables(base_app) -> None:
base_app._settables.clear()
_out, err = run_cmd(base_app, "set quiet True")
expected = normalize("There are no settable parameters")
assert err == expected
assert base_app.last_result is False
@pytest.mark.parametrize(
("new_val", "is_valid", "expected"),
[
(ru.AllowStyle.NEVER, True, ru.AllowStyle.NEVER),
("neVeR", True, ru.AllowStyle.NEVER),
(ru.AllowStyle.TERMINAL, True, ru.AllowStyle.TERMINAL),
("TeRMInal", True, ru.AllowStyle.TERMINAL),
(ru.AllowStyle.ALWAYS, True, ru.AllowStyle.ALWAYS),
("AlWaYs", True, ru.AllowStyle.ALWAYS),
("invalid", False, ru.AllowStyle.TERMINAL),
],
)
@with_ansi_style(ru.AllowStyle.TERMINAL)
def test_set_allow_style(base_app, new_val, is_valid, expected) -> None:
# Use the set command to alter allow_style
out, err = run_cmd(base_app, f"set allow_style {new_val}")
assert base_app.last_result is is_valid
# Verify the results
assert expected == ru.ALLOW_STYLE
if is_valid:
assert not err
assert out
def test_set_with_choices(base_app) -> None:
"""Test choices validation of Settables"""
fake_choices = ["valid", "choices"]
base_app.fake = fake_choices[0]
fake_settable = cmd2.Settable("fake", type(base_app.fake), "fake description", base_app, choices=fake_choices)
base_app.add_settable(fake_settable)
# Try a valid choice
_out, err = run_cmd(base_app, f"set fake {fake_choices[1]}")
assert base_app.last_result is True
assert not err
# Try an invalid choice
_out, err = run_cmd(base_app, "set fake bad_value")
assert base_app.last_result is False
assert err[0].startswith("Error setting fake: invalid choice")
class OnChangeHookApp(cmd2.Cmd):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_settable(utils.Settable("quiet", bool, "my description", self, onchange_cb=self._onchange_quiet))
def _onchange_quiet(self, name, old, new) -> None:
"""Runs when quiet is changed via set command"""
self.poutput("You changed " + name)
@pytest.fixture
def onchange_app():
return OnChangeHookApp()
def test_set_onchange_hook(onchange_app) -> None:
out, _err = run_cmd(onchange_app, "set quiet True")
expected = normalize(
"""
You changed quiet
quiet - was: False
now: True
"""
)
assert out == expected
assert onchange_app.last_result is True
def test_base_shell(base_app, monkeypatch) -> None:
m = mock.Mock()
monkeypatch.setattr("{}.Popen".format("subprocess"), m)
out, _err = run_cmd(base_app, "shell echo a")
assert out == []
assert m.called
def test_shell_last_result(base_app) -> None:
base_app.last_result = None
run_cmd(base_app, "shell fake")
assert base_app.last_result is not None
def test_shell_manual_call(base_app) -> None:
# Verifies crash from Issue #986 doesn't happen
cmds = ['echo "hi"', 'echo "there"', 'echo "cmd2!"']
cmd = ";".join(cmds)
base_app.do_shell(cmd)
cmd = "&&".join(cmds)
base_app.do_shell(cmd)
def test_base_error(base_app) -> None:
_out, err = run_cmd(base_app, "meow")
assert "is not a recognized command" in err[0]
def test_base_error_suggest_command(base_app) -> None:
try:
old_suggest_similar_command = base_app.suggest_similar_command
base_app.suggest_similar_command = True
_out, err = run_cmd(base_app, "historic")
assert "history" in err[1]
finally:
base_app.suggest_similar_command = old_suggest_similar_command
def test_run_script(base_app, request) -> None:
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "script.txt")
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Get output out the script
script_out, script_err = run_cmd(base_app, f"run_script {filename}")
assert base_app.last_result is True
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Now run the commands manually and compare their output to script's
with open(filename, encoding="utf-8") as file:
script_commands = file.read().splitlines()
manual_out = []
manual_err = []
for cmdline in script_commands:
out, err = run_cmd(base_app, cmdline)
manual_out.extend(out)
manual_err.extend(err)
assert script_out == manual_out
assert script_err == manual_err
def test_run_script_with_empty_args(base_app) -> None:
_out, err = run_cmd(base_app, "run_script")
assert "the following arguments are required" in err[1]
assert base_app.last_result is None
def test_run_script_with_invalid_file(base_app, request) -> None:
# Path does not exist
_out, err = run_cmd(base_app, "run_script does_not_exist.txt")
assert "Problem accessing script from " in err[0]
assert base_app.last_result is False
# Path is a directory
test_dir = os.path.dirname(request.module.__file__)
_out, err = run_cmd(base_app, f"run_script {test_dir}")
assert "Problem accessing script from " in err[0]
assert base_app.last_result is False
def test_run_script_with_empty_file(base_app, request) -> None:
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "scripts", "empty.txt")
out, err = run_cmd(base_app, f"run_script {filename}")
assert not out
assert not err
assert base_app.last_result is True
def test_run_script_with_binary_file(base_app, request) -> None:
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "scripts", "binary.bin")
_out, err = run_cmd(base_app, f"run_script {filename}")
assert "is not an ASCII or UTF-8 encoded text file" in err[0]
assert base_app.last_result is False
def test_run_script_with_python_file(base_app, request, monkeypatch) -> None:
read_input_mock = mock.MagicMock(name="read_input", return_value="2")
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "pyscript", "stop.py")
_out, err = run_cmd(base_app, f"run_script {filename}")
assert "appears to be a Python file" in err[0]
assert base_app.last_result is False
def test_run_script_with_utf8_file(base_app, request) -> None:
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "scripts", "utf8.txt")
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Get output out the script
script_out, script_err = run_cmd(base_app, f"run_script {filename}")
assert base_app.last_result is True
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Now run the commands manually and compare their output to script's
with open(filename, encoding="utf-8") as file:
script_commands = file.read().splitlines()
manual_out = []
manual_err = []
for cmdline in script_commands:
out, err = run_cmd(base_app, cmdline)
manual_out.extend(out)
manual_err.extend(err)
assert script_out == manual_out
assert script_err == manual_err
def test_scripts_add_to_history(base_app, request) -> None:
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "scripts", "help.txt")
command = f"run_script {filename}"
# Add to history
base_app.scripts_add_to_history = True
base_app.history.clear()
run_cmd(base_app, command)
assert len(base_app.history) == 2
assert base_app.history.get(1).raw == command
assert base_app.history.get(2).raw == "help -v"
# Do not add to history
base_app.scripts_add_to_history = False
base_app.history.clear()
run_cmd(base_app, command)
assert len(base_app.history) == 1
assert base_app.history.get(1).raw == command
def test_run_script_nested_run_scripts(base_app, request) -> None:
# Verify that running a script with nested run_script commands works correctly,
# and runs the nested script commands in the correct order.
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "scripts", "nested.txt")
# Run the top level script
initial_run = "run_script " + filename
run_cmd(base_app, initial_run)
assert base_app.last_result is True
# Check that the right commands were executed.
expected = f"""
{initial_run}
_relative_run_script precmds.txt
set always_show_hint True
help
shortcuts
_relative_run_script postcmds.txt
set always_show_hint False"""
out, _err = run_cmd(base_app, "history -s")
assert out == normalize(expected)
def test_runcmds_plus_hooks(base_app, request) -> None:
test_dir = os.path.dirname(request.module.__file__)
prefilepath = os.path.join(test_dir, "scripts", "precmds.txt")
postfilepath = os.path.join(test_dir, "scripts", "postcmds.txt")
base_app.runcmds_plus_hooks(["run_script " + prefilepath, "help", "shortcuts", "run_script " + postfilepath])
expected = f"""
run_script {prefilepath}
set always_show_hint True
help
shortcuts
run_script {postfilepath}
set always_show_hint False"""
out, _err = run_cmd(base_app, "history -s")
assert out == normalize(expected)
def test_runcmds_plus_hooks_ctrl_c(base_app, capsys) -> None:
"""Test Ctrl-C while in runcmds_plus_hooks"""
import types
def do_keyboard_interrupt(self, _) -> NoReturn:
raise KeyboardInterrupt("Interrupting this command")
base_app.do_keyboard_interrupt = types.MethodType(do_keyboard_interrupt, base_app)
# Default behavior is to not stop runcmds_plus_hooks() on Ctrl-C
base_app.history.clear()
base_app.runcmds_plus_hooks(["help", "keyboard_interrupt", "shortcuts"])
_out, err = capsys.readouterr()
assert not err
assert len(base_app.history) == 3
# Ctrl-C should stop runcmds_plus_hooks() in this case
base_app.history.clear()
base_app.runcmds_plus_hooks(["help", "keyboard_interrupt", "shortcuts"], stop_on_keyboard_interrupt=True)
_out, err = capsys.readouterr()
assert err.startswith("Interrupting this command")
assert len(base_app.history) == 2
def test_relative_run_script(base_app, request) -> None:
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "script.txt")
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Get output out the script
script_out, script_err = run_cmd(base_app, f"_relative_run_script {filename}")
assert base_app.last_result is True
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Now run the commands manually and compare their output to script's
with open(filename, encoding="utf-8") as file:
script_commands = file.read().splitlines()
manual_out = []
manual_err = []
for cmdline in script_commands:
out, err = run_cmd(base_app, cmdline)
manual_out.extend(out)
manual_err.extend(err)
assert script_out == manual_out
assert script_err == manual_err
@pytest.mark.parametrize("file_name", odd_file_names)
def test_relative_run_script_with_odd_file_names(base_app, file_name, monkeypatch) -> None:
"""Test file names with various patterns"""
# Mock out the do_run_script call to see what args are passed to it
run_script_mock = mock.MagicMock(name="do_run_script")
monkeypatch.setattr("cmd2.Cmd.do_run_script", run_script_mock)
run_cmd(base_app, f"_relative_run_script {su.quote(file_name)}")
run_script_mock.assert_called_once_with(su.quote(file_name))
def test_relative_run_script_requires_an_argument(base_app) -> None:
_out, err = run_cmd(base_app, "_relative_run_script")
assert "Error: the following arguments" in err[1]
assert base_app.last_result is None
def test_in_script(request) -> None:
class HookApp(cmd2.Cmd):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.register_cmdfinalization_hook(self.hook)
def hook(self: cmd2.Cmd, data: plugin.CommandFinalizationData) -> plugin.CommandFinalizationData:
if self.in_script():
self.poutput("WE ARE IN SCRIPT")
return data
hook_app = HookApp()
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "script.txt")
out, _err = run_cmd(hook_app, f"run_script {filename}")
assert "WE ARE IN SCRIPT" in out[-1]
def test_system_exit_in_command(base_app, capsys) -> None:
"""Test raising SystemExit in a command"""
import types
exit_code = 5
def do_system_exit(self, _) -> NoReturn:
raise SystemExit(exit_code)
base_app.do_system_exit = types.MethodType(do_system_exit, base_app)
stop = base_app.onecmd_plus_hooks("system_exit")
assert stop
assert base_app.exit_code == exit_code
def test_passthrough_exception_in_command(base_app) -> None:
"""Test raising a PassThroughException in a command"""
import types
expected_err = "Pass me up"
def do_passthrough(self, _) -> NoReturn:
wrapped_ex = OSError(expected_err)
raise exceptions.PassThroughException(wrapped_ex=wrapped_ex)
base_app.do_passthrough = types.MethodType(do_passthrough, base_app)
with pytest.raises(OSError, match=expected_err):
base_app.onecmd_plus_hooks("passthrough")
class RedirectionApp(cmd2.Cmd):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def do_print_output(self, _: str) -> None:
"""Print output to sys.stdout and self.stdout.."""
print("print")
self.poutput("poutput")
def do_print_feedback(self, _: str) -> None:
"""Call pfeedback."""
self.pfeedback("feedback")
@pytest.fixture
def redirection_app():
return RedirectionApp()
def test_output_redirection(redirection_app) -> None:
fd, filename = tempfile.mkstemp(prefix="cmd2_test", suffix=".txt")
os.close(fd)
try:
# Verify that writing to a file works
run_cmd(redirection_app, f"print_output > {filename}")
with open(filename) as f:
lines = f.read().splitlines()
assert lines[0] == "print"
assert lines[1] == "poutput"
# Verify that appending to a file also works
run_cmd(redirection_app, f"print_output >> {filename}")
with open(filename) as f:
lines = f.read().splitlines()
assert lines[0] == "print"
assert lines[1] == "poutput"
assert lines[2] == "print"
assert lines[3] == "poutput"
finally:
os.remove(filename)
def test_output_redirection_custom_stdout(redirection_app) -> None:
"""sys.stdout should not redirect if it's different than self.stdout."""
fd, filename = tempfile.mkstemp(prefix="cmd2_test", suffix=".txt")
os.close(fd)
redirection_app.stdout = io.StringIO()
try:
# Verify that we only see output written to self.stdout
run_cmd(redirection_app, f"print_output > {filename}")
with open(filename) as f:
lines = f.read().splitlines()
assert "print" not in lines
assert lines[0] == "poutput"
# Verify that appending to a file also works
run_cmd(redirection_app, f"print_output >> {filename}")
with open(filename) as f:
lines = f.read().splitlines()
assert "print" not in lines
assert lines[0] == "poutput"
assert lines[1] == "poutput"
finally:
os.remove(filename)
def test_output_redirection_to_nonexistent_directory(redirection_app) -> None:
filename = "~/fakedir/this_does_not_exist.txt"
_out, err = run_cmd(redirection_app, f"print_output > {filename}")
assert "Failed to redirect" in err[0]
_out, err = run_cmd(redirection_app, f"print_output >> {filename}")
assert "Failed to redirect" in err[0]
def test_output_redirection_to_too_long_filename(redirection_app) -> None:
filename = (
"~/sdkfhksdjfhkjdshfkjsdhfkjsdhfkjdshfkjdshfkjshdfkhdsfkjhewfuihewiufhweiufhiweufhiuewhiuewhfiuwehfia"
"ewhfiuewhfiuewhfiuewhiuewhfiuewhfiuewfhiuwehewiufhewiuhfiweuhfiuwehfiuewfhiuwehiuewfhiuewhiewuhfiueh"
"fiuwefhewiuhewiufhewiufhewiufhewiufhewiufhewiufhewiufhewiuhewiufhewiufhewiuheiufhiuewheiwufhewiufheu"
"fheiufhieuwhfewiuhfeiufhiuewfhiuewheiwuhfiuewhfiuewhfeiuwfhewiufhiuewhiuewhfeiuwhfiuwehfuiwehfiuehie"
"whfieuwfhieufhiuewhfeiuwfhiuefhueiwhfw"
)
_out, err = run_cmd(redirection_app, f"print_output > {filename}")
assert "Failed to redirect" in err[0]
_out, err = run_cmd(redirection_app, f"print_output >> {filename}")
assert "Failed to redirect" in err[0]
def test_feedback_to_output_true(redirection_app) -> None:
redirection_app.feedback_to_output = True
f, filename = tempfile.mkstemp(prefix="cmd2_test", suffix=".txt")
os.close(f)
try:
run_cmd(redirection_app, f"print_feedback > {filename}")
with open(filename) as f:
content = f.read().splitlines()
assert "feedback" in content
finally:
os.remove(filename)
def test_feedback_to_output_false(redirection_app) -> None:
redirection_app.feedback_to_output = False
f, filename = tempfile.mkstemp(prefix="feedback_to_output", suffix=".txt")
os.close(f)
try:
_out, err = run_cmd(redirection_app, f"print_feedback > {filename}")
with open(filename) as f:
content = f.read().splitlines()
assert not content
assert "feedback" in err
finally:
os.remove(filename)
def test_disallow_redirection(redirection_app) -> None:
# Set allow_redirection to False
redirection_app.allow_redirection = False
filename = "test_allow_redirect.txt"
# Verify output wasn't redirected
out, _err = run_cmd(redirection_app, f"print_output > {filename}")
assert "print" in out
assert "poutput" in out
# Verify that no file got created
assert not os.path.exists(filename)
def test_pipe_to_shell(redirection_app) -> None:
out, err = run_cmd(redirection_app, "print_output | sort")
assert "print" in out
assert "poutput" in out
assert not err
def test_pipe_to_shell_custom_stdout(redirection_app) -> None:
"""sys.stdout should not redirect if it's different than self.stdout."""
redirection_app.stdout = io.StringIO()
out, err = run_cmd(redirection_app, "print_output | sort")
assert "print" not in out
assert "poutput" in out
assert not err
def test_pipe_to_shell_and_redirect(redirection_app) -> None:
filename = "out.txt"
out, err = run_cmd(redirection_app, f"print_output | sort > {filename}")
assert not out
assert not err
assert os.path.exists(filename)
os.remove(filename)
def test_pipe_to_shell_error(redirection_app) -> None:
# Try to pipe command output to a shell command that doesn't exist in order to produce an error
out, err = run_cmd(redirection_app, "print_output | foobarbaz.this_does_not_exist")
assert not out
assert "Pipe process exited with code" in err[0]
try:
# try getting the contents of the clipboard
_ = clipboard.get_paste_buffer()
# pyperclip raises at least the following types of exceptions
# FileNotFoundError on Windows Subsystem for Linux (WSL) when Windows paths are removed from $PATH
# ValueError for headless Linux systems without Gtk installed
# AssertionError can be raised by paste_klipper().
# PyperclipException for pyperclip-specific exceptions
except Exception: # noqa: BLE001
can_paste = False
else:
can_paste = True
@pytest.mark.skipif(not can_paste, reason="Pyperclip could not find a copy/paste mechanism for your system")
def test_send_to_paste_buffer(redirection_app) -> None:
# Test writing to the PasteBuffer/Clipboard
run_cmd(redirection_app, "print_output >")
lines = cmd2.cmd2.get_paste_buffer().splitlines()
assert lines[0] == "print"
assert lines[1] == "poutput"
# Test appending to the PasteBuffer/Clipboard
run_cmd(redirection_app, "print_output >>")
lines = cmd2.cmd2.get_paste_buffer().splitlines()
assert lines[0] == "print"
assert lines[1] == "poutput"
assert lines[2] == "print"
assert lines[3] == "poutput"
@pytest.mark.skipif(not can_paste, reason="Pyperclip could not find a copy/paste mechanism for your system")
def test_send_to_paste_buffer_custom_stdout(redirection_app) -> None:
"""sys.stdout should not redirect if it's different than self.stdout."""
redirection_app.stdout = io.StringIO()
# Verify that we only see output written to self.stdout
run_cmd(redirection_app, "print_output >")
lines = cmd2.cmd2.get_paste_buffer().splitlines()
assert "print" not in lines
assert lines[0] == "poutput"
# Test appending to the PasteBuffer/Clipboard
run_cmd(redirection_app, "print_output >>")
lines = cmd2.cmd2.get_paste_buffer().splitlines()
assert "print" not in lines
assert lines[0] == "poutput"
assert lines[1] == "poutput"
def test_get_paste_buffer_exception(redirection_app, mocker, capsys) -> None:
# Force get_paste_buffer to throw an exception
pastemock = mocker.patch("pyperclip.paste")
pastemock.side_effect = ValueError("foo")
# Redirect command output to the clipboard
redirection_app.onecmd_plus_hooks("print_output > ")
# Make sure we got the exception output
out, err = capsys.readouterr()
assert out == ""
# this just checks that cmd2 is surfacing whatever error gets raised by pyperclip.paste
assert "ValueError" in err
assert "foo" in err
def test_allow_clipboard_initializer(redirection_app) -> None:
assert redirection_app.allow_clipboard is True
noclipcmd = cmd2.Cmd(allow_clipboard=False)
assert noclipcmd.allow_clipboard is False
# if clipboard access is not allowed, cmd2 should check that first
# before it tries to do anything with pyperclip, that's why we can
# safely run this test without skipping it if pyperclip doesn't
# work in the test environment, like we do for test_send_to_paste_buffer()
def test_allow_clipboard(base_app) -> None:
base_app.allow_clipboard = False
out, err = run_cmd(base_app, "help >")
assert not out
assert "Clipboard access not allowed" in err
def test_base_timing(base_app) -> None:
base_app.feedback_to_output = False
out, err = run_cmd(base_app, "set timing True")
expected = normalize(
"""timing - was: False
now: True
"""
)
assert out == expected
if sys.platform == "win32":
assert err[0].startswith("Elapsed: 0:00:00")
else:
assert err[0].startswith("Elapsed: 0:00:00.0")
def test_base_debug(base_app) -> None:
# Purposely set the editor to None
base_app.editor = None
# Make sure we get an exception, but cmd2 handles it
out, err = run_cmd(base_app, "edit")
assert "ValueError: Please use 'set editor'" in err[0]
assert "To enable full traceback" in err[3]
# Set debug true
out, err = run_cmd(base_app, "set debug True")
expected = normalize(
"""
debug - was: False
now: True
"""
)
assert out == expected
# Verify that we now see the exception traceback
out, err = run_cmd(base_app, "edit")
assert "Traceback (most recent call last)" in err[0]
def test_debug_not_settable(base_app) -> None:
# Set debug to False and make it unsettable
base_app.debug = False
base_app.remove_settable("debug")
# Cause an exception by setting editor to None and running edit
base_app.editor = None
_out, err = run_cmd(base_app, "edit")
# Since debug is unsettable, the user will not be given the option to enable a full traceback
assert err == ["ValueError: Please use 'set editor' to specify your text editing program of", "choice."]
def test_blank_exception(mocker, base_app):
mocker.patch("cmd2.Cmd.do_help", side_effect=Exception)
_out, err = run_cmd(base_app, "help")
# When an exception has no message, the first error line is just its type.
assert err[0] == "Exception"
def test_remove_settable_keyerror(base_app) -> None:
with pytest.raises(KeyError):
base_app.remove_settable("fake")
def test_edit_file(base_app, request, monkeypatch) -> None:
# Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
base_app.editor = "fooedit"
# Mock out the subprocess.Popen call so we don't actually open an editor
m = mock.MagicMock(name="Popen")
monkeypatch.setattr("subprocess.Popen", m)
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "script.txt")
run_cmd(base_app, f"edit {filename}")
# We think we have an editor, so should expect a Popen call
m.assert_called_once()
@pytest.mark.parametrize("file_name", odd_file_names)
def test_edit_file_with_odd_file_names(base_app, file_name, monkeypatch) -> None:
"""Test editor and file names with various patterns"""
# Mock out the do_shell call to see what args are passed to it
shell_mock = mock.MagicMock(name="do_shell")
monkeypatch.setattr("cmd2.Cmd.do_shell", shell_mock)
base_app.editor = "fooedit"
file_name = su.quote("nothingweird.py")
run_cmd(base_app, f"edit {su.quote(file_name)}")
shell_mock.assert_called_once_with(f'"fooedit" {su.quote(file_name)}')
def test_edit_file_with_spaces(base_app, request, monkeypatch) -> None:
# Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
base_app.editor = "fooedit"
# Mock out the subprocess.Popen call so we don't actually open an editor
m = mock.MagicMock(name="Popen")
monkeypatch.setattr("subprocess.Popen", m)
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, "my commands.txt")
run_cmd(base_app, f'edit "{filename}"')
# We think we have an editor, so should expect a Popen call
m.assert_called_once()
def test_edit_blank(base_app, monkeypatch) -> None:
# Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
base_app.editor = "fooedit"
# Mock out the subprocess.Popen call so we don't actually open an editor
m = mock.MagicMock(name="Popen")
monkeypatch.setattr("subprocess.Popen", m)
run_cmd(base_app, "edit")
# We have an editor, so should expect a Popen call
m.assert_called_once()