test_cmd.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. """
  2. Test script for the 'cmd' module
  3. Original by Michael Schneider
  4. """
  5. import cmd
  6. import sys
  7. import doctest
  8. import unittest
  9. import io
  10. from test import support
  11. class samplecmdclass(cmd.Cmd):
  12. """
  13. Instance the sampleclass:
  14. >>> mycmd = samplecmdclass()
  15. Test for the function parseline():
  16. >>> mycmd.parseline("")
  17. (None, None, '')
  18. >>> mycmd.parseline("?")
  19. ('help', '', 'help ')
  20. >>> mycmd.parseline("?help")
  21. ('help', 'help', 'help help')
  22. >>> mycmd.parseline("!")
  23. ('shell', '', 'shell ')
  24. >>> mycmd.parseline("!command")
  25. ('shell', 'command', 'shell command')
  26. >>> mycmd.parseline("func")
  27. ('func', '', 'func')
  28. >>> mycmd.parseline("func arg1")
  29. ('func', 'arg1', 'func arg1')
  30. Test for the function onecmd():
  31. >>> mycmd.onecmd("")
  32. >>> mycmd.onecmd("add 4 5")
  33. 9
  34. >>> mycmd.onecmd("")
  35. 9
  36. >>> mycmd.onecmd("test")
  37. *** Unknown syntax: test
  38. Test for the function emptyline():
  39. >>> mycmd.emptyline()
  40. *** Unknown syntax: test
  41. Test for the function default():
  42. >>> mycmd.default("default")
  43. *** Unknown syntax: default
  44. Test for the function completedefault():
  45. >>> mycmd.completedefault()
  46. This is the completedefault method
  47. >>> mycmd.completenames("a")
  48. ['add']
  49. Test for the function completenames():
  50. >>> mycmd.completenames("12")
  51. []
  52. >>> mycmd.completenames("help")
  53. ['help']
  54. Test for the function complete_help():
  55. >>> mycmd.complete_help("a")
  56. ['add']
  57. >>> mycmd.complete_help("he")
  58. ['help']
  59. >>> mycmd.complete_help("12")
  60. []
  61. >>> sorted(mycmd.complete_help(""))
  62. ['add', 'exit', 'help', 'life', 'meaning', 'shell']
  63. Test for the function do_help():
  64. >>> mycmd.do_help("testet")
  65. *** No help on testet
  66. >>> mycmd.do_help("add")
  67. help text for add
  68. >>> mycmd.onecmd("help add")
  69. help text for add
  70. >>> mycmd.onecmd("help meaning") # doctest: +NORMALIZE_WHITESPACE
  71. Try and be nice to people, avoid eating fat, read a good book every
  72. now and then, get some walking in, and try to live together in peace
  73. and harmony with people of all creeds and nations.
  74. >>> mycmd.do_help("")
  75. <BLANKLINE>
  76. Documented commands (type help <topic>):
  77. ========================================
  78. add help
  79. <BLANKLINE>
  80. Miscellaneous help topics:
  81. ==========================
  82. life meaning
  83. <BLANKLINE>
  84. Undocumented commands:
  85. ======================
  86. exit shell
  87. <BLANKLINE>
  88. Test for the function print_topics():
  89. >>> mycmd.print_topics("header", ["command1", "command2"], 2 ,10)
  90. header
  91. ======
  92. command1
  93. command2
  94. <BLANKLINE>
  95. Test for the function columnize():
  96. >>> mycmd.columnize([str(i) for i in range(20)])
  97. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
  98. >>> mycmd.columnize([str(i) for i in range(20)], 10)
  99. 0 7 14
  100. 1 8 15
  101. 2 9 16
  102. 3 10 17
  103. 4 11 18
  104. 5 12 19
  105. 6 13
  106. This is an interactive test, put some commands in the cmdqueue attribute
  107. and let it execute
  108. This test includes the preloop(), postloop(), default(), emptyline(),
  109. parseline(), do_help() functions
  110. >>> mycmd.use_rawinput=0
  111. >>> mycmd.cmdqueue=["add", "add 4 5", "", "help", "help add", "exit"]
  112. >>> mycmd.cmdloop() # doctest: +REPORT_NDIFF
  113. Hello from preloop
  114. *** invalid number of arguments
  115. 9
  116. 9
  117. <BLANKLINE>
  118. Documented commands (type help <topic>):
  119. ========================================
  120. add help
  121. <BLANKLINE>
  122. Miscellaneous help topics:
  123. ==========================
  124. life meaning
  125. <BLANKLINE>
  126. Undocumented commands:
  127. ======================
  128. exit shell
  129. <BLANKLINE>
  130. help text for add
  131. Hello from postloop
  132. """
  133. def preloop(self):
  134. print("Hello from preloop")
  135. def postloop(self):
  136. print("Hello from postloop")
  137. def completedefault(self, *ignored):
  138. print("This is the completedefault method")
  139. def complete_command(self):
  140. print("complete command")
  141. def do_shell(self, s):
  142. pass
  143. def do_add(self, s):
  144. l = s.split()
  145. if len(l) != 2:
  146. print("*** invalid number of arguments")
  147. return
  148. try:
  149. l = [int(i) for i in l]
  150. except ValueError:
  151. print("*** arguments should be numbers")
  152. return
  153. print(l[0]+l[1])
  154. def help_add(self):
  155. print("help text for add")
  156. return
  157. def help_meaning(self):
  158. print("Try and be nice to people, avoid eating fat, read a "
  159. "good book every now and then, get some walking in, "
  160. "and try to live together in peace and harmony with "
  161. "people of all creeds and nations.")
  162. return
  163. def help_life(self):
  164. print("Always look on the bright side of life")
  165. return
  166. def do_exit(self, arg):
  167. return True
  168. class TestAlternateInput(unittest.TestCase):
  169. class simplecmd(cmd.Cmd):
  170. def do_print(self, args):
  171. print(args, file=self.stdout)
  172. def do_EOF(self, args):
  173. return True
  174. class simplecmd2(simplecmd):
  175. def do_EOF(self, args):
  176. print('*** Unknown syntax: EOF', file=self.stdout)
  177. return True
  178. def test_file_with_missing_final_nl(self):
  179. input = io.StringIO("print test\nprint test2")
  180. output = io.StringIO()
  181. cmd = self.simplecmd(stdin=input, stdout=output)
  182. cmd.use_rawinput = False
  183. cmd.cmdloop()
  184. self.assertMultiLineEqual(output.getvalue(),
  185. ("(Cmd) test\n"
  186. "(Cmd) test2\n"
  187. "(Cmd) "))
  188. def test_input_reset_at_EOF(self):
  189. input = io.StringIO("print test\nprint test2")
  190. output = io.StringIO()
  191. cmd = self.simplecmd2(stdin=input, stdout=output)
  192. cmd.use_rawinput = False
  193. cmd.cmdloop()
  194. self.assertMultiLineEqual(output.getvalue(),
  195. ("(Cmd) test\n"
  196. "(Cmd) test2\n"
  197. "(Cmd) *** Unknown syntax: EOF\n"))
  198. input = io.StringIO("print \n\n")
  199. output = io.StringIO()
  200. cmd.stdin = input
  201. cmd.stdout = output
  202. cmd.cmdloop()
  203. self.assertMultiLineEqual(output.getvalue(),
  204. ("(Cmd) \n"
  205. "(Cmd) \n"
  206. "(Cmd) *** Unknown syntax: EOF\n"))
  207. def load_tests(loader, tests, pattern):
  208. tests.addTest(doctest.DocTestSuite())
  209. return tests
  210. def test_coverage(coverdir):
  211. trace = support.import_module('trace')
  212. tracer=trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
  213. trace=0, count=1)
  214. tracer.run('import importlib; importlib.reload(cmd); test_main()')
  215. r=tracer.results()
  216. print("Writing coverage results...")
  217. r.write_results(show_missing=True, summary=True, coverdir=coverdir)
  218. if __name__ == "__main__":
  219. if "-c" in sys.argv:
  220. test_coverage('/tmp/cmd.cover')
  221. elif "-i" in sys.argv:
  222. samplecmdclass().cmdloop()
  223. else:
  224. unittest.main()