Debian Codegraph @

Lib/test/test_cmd.py

raw
1 """
2 Test script for the 'cmd' module
3 Original by Michael Schneider
4 """
5
6
7 import cmd
8 import sys
9 import doctest
10 import unittest
11 import io
12 import textwrap
13 from test import support
14 from test.support.import_helper import ensure_lazy_imports, import_module
15 from test.support.pty_helper import run_pty
16
17 class LazyImportTest(unittest.TestCase):
18 @support.cpython_only
19 def test_lazy_import(self):
20 ensure_lazy_imports("cmd", {"inspect", "string"})
21
22
23 class samplecmdclass(cmd.Cmd):
24 """
25 Instance the sampleclass:
26 >>> mycmd = samplecmdclass()
27
28 Test for the function parseline():
29 >>> mycmd.parseline("")
30 (None, None, '')
31 >>> mycmd.parseline("?")
32 ('help', '', 'help ')
33 >>> mycmd.parseline("?help")
34 ('help', 'help', 'help help')
35 >>> mycmd.parseline("!")
36 ('shell', '', 'shell ')
37 >>> mycmd.parseline("!command")
38 ('shell', 'command', 'shell command')
39 >>> mycmd.parseline("func")
40 ('func', '', 'func')
41 >>> mycmd.parseline("func arg1")
42 ('func', 'arg1', 'func arg1')
43
44
45 Test for the function onecmd():
46 >>> mycmd.onecmd("")
47 >>> mycmd.onecmd("add 4 5")
48 9
49 >>> mycmd.onecmd("")
50 9
51 >>> mycmd.onecmd("test")
52 *** Unknown syntax: test
53
54 Test for the function emptyline():
55 >>> mycmd.emptyline()
56 *** Unknown syntax: test
57
58 Test for the function default():
59 >>> mycmd.default("default")
60 *** Unknown syntax: default
61
62 Test for the function completedefault():
63 >>> mycmd.completedefault()
64 This is the completedefault method
65 >>> mycmd.completenames("a")
66 ['add']
67
68 Test for the function completenames():
69 >>> mycmd.completenames("12")
70 []
71 >>> mycmd.completenames("help")
72 ['help']
73
74 Test for the function complete_help():
75 >>> mycmd.complete_help("a")
76 ['add']
77 >>> mycmd.complete_help("he")
78 ['help']
79 >>> mycmd.complete_help("12")
80 []
81 >>> sorted(mycmd.complete_help(""))
82 ['add', 'exit', 'help', 'life', 'meaning', 'shell']
83
84 Test for the function do_help():
85 >>> mycmd.do_help("testet")
86 *** No help on testet
87 >>> mycmd.do_help("add")
88 help text for add
89 >>> mycmd.onecmd("help add")
90 help text for add
91 >>> mycmd.onecmd("help meaning") # doctest: +NORMALIZE_WHITESPACE
92 Try and be nice to people, avoid eating fat, read a good book every
93 now and then, get some walking in, and try to live together in peace
94 and harmony with people of all creeds and nations.
95 >>> mycmd.do_help("")
96 <BLANKLINE>
97 Documented commands (type help <topic>):
98 ========================================
99 add help
100 <BLANKLINE>
101 Miscellaneous help topics:
102 ==========================
103 life meaning
104 <BLANKLINE>
105 Undocumented commands:
106 ======================
107 exit shell
108 <BLANKLINE>
109
110 Test for the function print_topics():
111 >>> mycmd.print_topics("header", ["command1", "command2"], 2 ,10)
112 header
113 ======
114 command1
115 command2
116 <BLANKLINE>
117
118 Test for the function columnize():
119 >>> mycmd.columnize([str(i) for i in range(20)])
120 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
121 >>> mycmd.columnize([str(i) for i in range(20)], 10)
122 0 7 14
123 1 8 15
124 2 9 16
125 3 10 17
126 4 11 18
127 5 12 19
128 6 13
129
130 This is an interactive test, put some commands in the cmdqueue attribute
131 and let it execute
132 This test includes the preloop(), postloop(), default(), emptyline(),
133 parseline(), do_help() functions
134 >>> mycmd.use_rawinput=0
135
136 >>> mycmd.cmdqueue=["add", "add 4 5", "", "help", "help add", "exit"]
137 >>> mycmd.cmdloop() # doctest: +REPORT_NDIFF
138 Hello from preloop
139 *** invalid number of arguments
140 9
141 9
142 <BLANKLINE>
143 Documented commands (type help <topic>):
144 ========================================
145 add help
146 <BLANKLINE>
147 Miscellaneous help topics:
148 ==========================
149 life meaning
150 <BLANKLINE>
151 Undocumented commands:
152 ======================
153 exit shell
154 <BLANKLINE>
155 help text for add
156 Hello from postloop
157 """
158
159 def preloop(self):
160 print("Hello from preloop")
161
162 def postloop(self):
163 print("Hello from postloop")
164
165 def completedefault(self, *ignored):
166 print("This is the completedefault method")
167
168 def complete_command(self):
169 print("complete command")
170
171 def do_shell(self, s):
172 pass
173
174 def do_add(self, s):
175 l = s.split()
176 if len(l) != 2:
177 print("*** invalid number of arguments")
178 return
179 try:
180 l = [int(i) for i in l]
181 except ValueError:
182 print("*** arguments should be numbers")
183 return
184 print(l[0]+l[1])
185
186 def help_add(self):
187 print("help text for add")
188 return
189
190 def help_meaning(self):
191 print("Try and be nice to people, avoid eating fat, read a "
192 "good book every now and then, get some walking in, "
193 "and try to live together in peace and harmony with "
194 "people of all creeds and nations.")
195 return
196
197 def help_life(self):
198 print("Always look on the bright side of life")
199 return
200
201 def do_exit(self, arg):
202 return True
203
204
205 class TestAlternateInput(unittest.TestCase):
206
207 class simplecmd(cmd.Cmd):
208
209 def do_print(self, args):
210 print(args, file=self.stdout)
211
212 def do_EOF(self, args):
213 return True
214
215
216 class simplecmd2(simplecmd):
217
218 def do_EOF(self, args):
219 print('*** Unknown syntax: EOF', file=self.stdout)
220 return True
221
222
223 def test_file_with_missing_final_nl(self):
224 input = io.StringIO("print test\nprint test2")
225 output = io.StringIO()
226 cmd = self.simplecmd(stdin=input, stdout=output)
227 cmd.use_rawinput = False
228 cmd.cmdloop()
229 self.assertMultiLineEqual(output.getvalue(),
230 ("(Cmd) test\n"
231 "(Cmd) test2\n"
232 "(Cmd) "))
233
234
235 def test_input_reset_at_EOF(self):
236 input = io.StringIO("print test\nprint test2")
237 output = io.StringIO()
238 cmd = self.simplecmd2(stdin=input, stdout=output)
239 cmd.use_rawinput = False
240 cmd.cmdloop()
241 self.assertMultiLineEqual(output.getvalue(),
242 ("(Cmd) test\n"
243 "(Cmd) test2\n"
244 "(Cmd) *** Unknown syntax: EOF\n"))
245 input = io.StringIO("print \n\n")
246 output = io.StringIO()
247 cmd.stdin = input
248 cmd.stdout = output
249 cmd.cmdloop()
250 self.assertMultiLineEqual(output.getvalue(),
251 ("(Cmd) \n"
252 "(Cmd) \n"
253 "(Cmd) *** Unknown syntax: EOF\n"))
254
255
256 class CmdPrintExceptionClass(cmd.Cmd):
257 """
258 GH-80731
259 cmd.Cmd should print the correct exception in default()
260 >>> mycmd = CmdPrintExceptionClass()
261 >>> try:
262 ... raise ValueError("test")
263 ... except ValueError:
264 ... mycmd.onecmd("not important")
265 (<class 'ValueError'>, ValueError('test'))
266 """
267
268 def default(self, line):
269 print(sys.exc_info()[:2])
270
271
272 @support.requires_subprocess()
273 class CmdTestReadline(unittest.TestCase):
274 def setUpClass():
275 # Ensure that the readline module is loaded
276 # If this fails, the test is skipped because SkipTest will be raised
277 readline = import_module('readline')
278
279 def test_basic_completion(self):
280 script = textwrap.dedent("""
281 import cmd
282 class simplecmd(cmd.Cmd):
283 def do_tab_completion_test(self, args):
284 print('tab completion success')
285 return True
286
287 simplecmd().cmdloop()
288 """)
289
290 # 't' and complete 'ab_completion_test' to 'tab_completion_test'
291 input = b"t\t\n"
292
293 output = run_pty(script, input)
294
295 self.assertIn(b'ab_completion_test', output)
296 self.assertIn(b'tab completion success', output)
297
298 def test_bang_completion_without_do_shell(self):
299 script = textwrap.dedent("""
300 import cmd
301 class simplecmd(cmd.Cmd):
302 def completedefault(self, text, line, begidx, endidx):
303 return ["hello"]
304
305 def default(self, line):
306 if line.replace(" ", "") == "!hello":
307 print('tab completion success')
308 else:
309 print('tab completion failure')
310 return True
311
312 simplecmd().cmdloop()
313 """)
314
315 # '! h' or '!h' and complete 'ello' to 'hello'
316 for input in [b"! h\t\n", b"!h\t\n"]:
317 with self.subTest(input=input):
318 output = run_pty(script, input)
319 self.assertIn(b'hello', output)
320 self.assertIn(b'tab completion success', output)
321
322 def load_tests(loader, tests, pattern):
323 tests.addTest(doctest.DocTestSuite())
324 return tests
325
326
327 if __name__ == "__main__":
328 if "-i" in sys.argv:
329 samplecmdclass().cmdloop()
330 else:
331 unittest.main()