test_manhole.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. # -*- test-case-name: twisted.conch.test.test_manhole -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. # pylint: disable=I0011,W9401,W9402
  5. """
  6. Tests for L{twisted.conch.manhole}.
  7. """
  8. import traceback
  9. from twisted.trial import unittest
  10. from twisted.internet import error, defer
  11. from twisted.test.proto_helpers import StringTransport
  12. from twisted.conch.test.test_recvline import (
  13. _TelnetMixin, _SSHMixin, _StdioMixin, stdio, ssh)
  14. from twisted.conch import manhole
  15. from twisted.conch.insults import insults
  16. def determineDefaultFunctionName():
  17. """
  18. Return the string used by Python as the name for code objects which are
  19. compiled from interactive input or at the top-level of modules.
  20. """
  21. try:
  22. 1 // 0
  23. except:
  24. # The last frame is this function. The second to last frame is this
  25. # function's caller, which is module-scope, which is what we want,
  26. # so -2.
  27. return traceback.extract_stack()[-2][2]
  28. defaultFunctionName = determineDefaultFunctionName()
  29. class ManholeInterpreterTests(unittest.TestCase):
  30. """
  31. Tests for L{manhole.ManholeInterpreter}.
  32. """
  33. def test_resetBuffer(self):
  34. """
  35. L{ManholeInterpreter.resetBuffer} should empty the input buffer.
  36. """
  37. interpreter = manhole.ManholeInterpreter(None)
  38. interpreter.buffer.extend(["1", "2"])
  39. interpreter.resetBuffer()
  40. self.assertFalse(interpreter.buffer)
  41. class ManholeProtocolTests(unittest.TestCase):
  42. """
  43. Tests for L{manhole.Manhole}.
  44. """
  45. def test_interruptResetsInterpreterBuffer(self):
  46. """
  47. L{manhole.Manhole.handle_INT} should cause the interpreter input buffer
  48. to be reset.
  49. """
  50. transport = StringTransport()
  51. terminal = insults.ServerProtocol(manhole.Manhole)
  52. terminal.makeConnection(transport)
  53. protocol = terminal.terminalProtocol
  54. interpreter = protocol.interpreter
  55. interpreter.buffer.extend(["1", "2"])
  56. protocol.handle_INT()
  57. self.assertFalse(interpreter.buffer)
  58. class WriterTests(unittest.TestCase):
  59. def test_Integer(self):
  60. """
  61. Colorize an integer.
  62. """
  63. manhole.lastColorizedLine("1")
  64. def test_DoubleQuoteString(self):
  65. """
  66. Colorize an integer in double quotes.
  67. """
  68. manhole.lastColorizedLine('"1"')
  69. def test_SingleQuoteString(self):
  70. """
  71. Colorize an integer in single quotes.
  72. """
  73. manhole.lastColorizedLine("'1'")
  74. def test_TripleSingleQuotedString(self):
  75. """
  76. Colorize an integer in triple quotes.
  77. """
  78. manhole.lastColorizedLine("'''1'''")
  79. def test_TripleDoubleQuotedString(self):
  80. """
  81. Colorize an integer in triple and double quotes.
  82. """
  83. manhole.lastColorizedLine('"""1"""')
  84. def test_FunctionDefinition(self):
  85. """
  86. Colorize a function definition.
  87. """
  88. manhole.lastColorizedLine("def foo():")
  89. def test_ClassDefinition(self):
  90. """
  91. Colorize a class definition.
  92. """
  93. manhole.lastColorizedLine("class foo:")
  94. class ManholeLoopbackMixin:
  95. serverProtocol = manhole.ColoredManhole
  96. def wfd(self, d):
  97. return defer.waitForDeferred(d)
  98. def test_SimpleExpression(self):
  99. """
  100. Evaluate simple expression.
  101. """
  102. done = self.recvlineClient.expect(b"done")
  103. self._testwrite(
  104. b"1 + 1\n"
  105. b"done")
  106. def finished(ign):
  107. self._assertBuffer(
  108. [b">>> 1 + 1",
  109. b"2",
  110. b">>> done"])
  111. return done.addCallback(finished)
  112. def test_TripleQuoteLineContinuation(self):
  113. """
  114. Evaluate line continuation in triple quotes.
  115. """
  116. done = self.recvlineClient.expect(b"done")
  117. self._testwrite(
  118. b"'''\n'''\n"
  119. b"done")
  120. def finished(ign):
  121. self._assertBuffer(
  122. [b">>> '''",
  123. b"... '''",
  124. b"'\\n'",
  125. b">>> done"])
  126. return done.addCallback(finished)
  127. def test_FunctionDefinition(self):
  128. """
  129. Evaluate function definition.
  130. """
  131. done = self.recvlineClient.expect(b"done")
  132. self._testwrite(
  133. b"def foo(bar):\n"
  134. b"\tprint(bar)\n\n"
  135. b"foo(42)\n"
  136. b"done")
  137. def finished(ign):
  138. self._assertBuffer(
  139. [b">>> def foo(bar):",
  140. b"... print(bar)",
  141. b"... ",
  142. b">>> foo(42)",
  143. b"42",
  144. b">>> done"])
  145. return done.addCallback(finished)
  146. def test_ClassDefinition(self):
  147. """
  148. Evaluate class definition.
  149. """
  150. done = self.recvlineClient.expect(b"done")
  151. self._testwrite(
  152. b"class Foo:\n"
  153. b"\tdef bar(self):\n"
  154. b"\t\tprint('Hello, world!')\n\n"
  155. b"Foo().bar()\n"
  156. b"done")
  157. def finished(ign):
  158. self._assertBuffer(
  159. [b">>> class Foo:",
  160. b"... def bar(self):",
  161. b"... print('Hello, world!')",
  162. b"... ",
  163. b">>> Foo().bar()",
  164. b"Hello, world!",
  165. b">>> done"])
  166. return done.addCallback(finished)
  167. def test_Exception(self):
  168. """
  169. Evaluate raising an exception.
  170. """
  171. done = self.recvlineClient.expect(b"done")
  172. self._testwrite(
  173. b"raise Exception('foo bar baz')\n"
  174. b"done")
  175. def finished(ign):
  176. self._assertBuffer(
  177. [b">>> raise Exception('foo bar baz')",
  178. b"Traceback (most recent call last):",
  179. b' File "<console>", line 1, in ' +
  180. defaultFunctionName.encode("utf-8"),
  181. b"Exception: foo bar baz",
  182. b">>> done"])
  183. return done.addCallback(finished)
  184. def test_ControlC(self):
  185. """
  186. Evaluate interrupting with CTRL-C.
  187. """
  188. done = self.recvlineClient.expect(b"done")
  189. self._testwrite(
  190. b"cancelled line" + manhole.CTRL_C +
  191. b"done")
  192. def finished(ign):
  193. self._assertBuffer(
  194. [b">>> cancelled line",
  195. b"KeyboardInterrupt",
  196. b">>> done"])
  197. return done.addCallback(finished)
  198. def test_interruptDuringContinuation(self):
  199. """
  200. Sending ^C to Manhole while in a state where more input is required to
  201. complete a statement should discard the entire ongoing statement and
  202. reset the input prompt to the non-continuation prompt.
  203. """
  204. continuing = self.recvlineClient.expect(b"things")
  205. self._testwrite(b"(\nthings")
  206. def gotContinuation(ignored):
  207. self._assertBuffer(
  208. [b">>> (",
  209. b"... things"])
  210. interrupted = self.recvlineClient.expect(b">>> ")
  211. self._testwrite(manhole.CTRL_C)
  212. return interrupted
  213. continuing.addCallback(gotContinuation)
  214. def gotInterruption(ignored):
  215. self._assertBuffer(
  216. [b">>> (",
  217. b"... things",
  218. b"KeyboardInterrupt",
  219. b">>> "])
  220. continuing.addCallback(gotInterruption)
  221. return continuing
  222. def test_ControlBackslash(self):
  223. """
  224. Evaluate cancelling with CTRL-\.
  225. """
  226. self._testwrite(b"cancelled line")
  227. partialLine = self.recvlineClient.expect(b"cancelled line")
  228. def gotPartialLine(ign):
  229. self._assertBuffer(
  230. [b">>> cancelled line"])
  231. self._testwrite(manhole.CTRL_BACKSLASH)
  232. d = self.recvlineClient.onDisconnection
  233. return self.assertFailure(d, error.ConnectionDone)
  234. def gotClearedLine(ign):
  235. self._assertBuffer(
  236. [b""])
  237. return partialLine.addCallback(gotPartialLine).addCallback(
  238. gotClearedLine)
  239. @defer.inlineCallbacks
  240. def test_controlD(self):
  241. """
  242. A CTRL+D in the middle of a line doesn't close a connection,
  243. but at the beginning of a line it does.
  244. """
  245. self._testwrite(b"1 + 1")
  246. yield self.recvlineClient.expect(br"\+ 1")
  247. self._assertBuffer([b">>> 1 + 1"])
  248. self._testwrite(manhole.CTRL_D + b" + 1")
  249. yield self.recvlineClient.expect(br"\+ 1")
  250. self._assertBuffer([b">>> 1 + 1 + 1"])
  251. self._testwrite(b"\n")
  252. yield self.recvlineClient.expect(b"3\n>>> ")
  253. self._testwrite(manhole.CTRL_D)
  254. d = self.recvlineClient.onDisconnection
  255. yield self.assertFailure(d, error.ConnectionDone)
  256. @defer.inlineCallbacks
  257. def test_ControlL(self):
  258. """
  259. CTRL+L is generally used as a redraw-screen command in terminal
  260. applications. Manhole doesn't currently respect this usage of it,
  261. but it should at least do something reasonable in response to this
  262. event (rather than, say, eating your face).
  263. """
  264. # Start off with a newline so that when we clear the display we can
  265. # tell by looking for the missing first empty prompt line.
  266. self._testwrite(b"\n1 + 1")
  267. yield self.recvlineClient.expect(br"\+ 1")
  268. self._assertBuffer([b">>> ", b">>> 1 + 1"])
  269. self._testwrite(manhole.CTRL_L + b" + 1")
  270. yield self.recvlineClient.expect(br"1 \+ 1 \+ 1")
  271. self._assertBuffer([b">>> 1 + 1 + 1"])
  272. def test_controlA(self):
  273. """
  274. CTRL-A can be used as HOME - returning cursor to beginning of
  275. current line buffer.
  276. """
  277. self._testwrite(b'rint "hello"' + b'\x01' + b'p')
  278. d = self.recvlineClient.expect(b'print "hello"')
  279. def cb(ignore):
  280. self._assertBuffer([b'>>> print "hello"'])
  281. return d.addCallback(cb)
  282. def test_controlE(self):
  283. """
  284. CTRL-E can be used as END - setting cursor to end of current
  285. line buffer.
  286. """
  287. self._testwrite(b'rint "hello' + b'\x01' + b'p' + b'\x05' + b'"')
  288. d = self.recvlineClient.expect(b'print "hello"')
  289. def cb(ignore):
  290. self._assertBuffer([b'>>> print "hello"'])
  291. return d.addCallback(cb)
  292. @defer.inlineCallbacks
  293. def test_deferred(self):
  294. """
  295. When a deferred is returned to the manhole REPL, it is displayed with
  296. a sequence number, and when the deferred fires, the result is printed.
  297. """
  298. self._testwrite(
  299. b"from twisted.internet import defer, reactor\n"
  300. b"d = defer.Deferred()\n"
  301. b"d\n")
  302. yield self.recvlineClient.expect(b"<Deferred #0>")
  303. self._testwrite(
  304. b"c = reactor.callLater(0.1, d.callback, 'Hi!')\n")
  305. yield self.recvlineClient.expect(b">>> ")
  306. yield self.recvlineClient.expect(
  307. b"Deferred #0 called back: 'Hi!'\n>>> ")
  308. self._assertBuffer(
  309. [b">>> from twisted.internet import defer, reactor",
  310. b">>> d = defer.Deferred()",
  311. b">>> d",
  312. b"<Deferred #0>",
  313. b">>> c = reactor.callLater(0.1, d.callback, 'Hi!')",
  314. b"Deferred #0 called back: 'Hi!'",
  315. b">>> "])
  316. class ManholeLoopbackTelnetTests(_TelnetMixin, unittest.TestCase,
  317. ManholeLoopbackMixin):
  318. """
  319. Test manhole loopback over Telnet.
  320. """
  321. pass
  322. class ManholeLoopbackSSHTests(_SSHMixin, unittest.TestCase,
  323. ManholeLoopbackMixin):
  324. """
  325. Test manhole loopback over SSH.
  326. """
  327. if ssh is None:
  328. skip = "cryptography requirements missing"
  329. class ManholeLoopbackStdioTests(_StdioMixin, unittest.TestCase,
  330. ManholeLoopbackMixin):
  331. """
  332. Test manhole loopback over standard IO.
  333. """
  334. if stdio is None:
  335. skip = "Terminal requirements missing"
  336. else:
  337. serverProtocol = stdio.ConsoleManhole
  338. class ManholeMainTests(unittest.TestCase):
  339. """
  340. Test the I{main} method from the I{manhole} module.
  341. """
  342. if stdio is None:
  343. skip = "Terminal requirements missing"
  344. def test_mainClassNotFound(self):
  345. """
  346. Will raise an exception when called with an argument which is a
  347. dotted patch which can not be imported..
  348. """
  349. exception = self.assertRaises(
  350. ValueError,
  351. stdio.main, argv=['no-such-class'],
  352. )
  353. self.assertEqual('Empty module name', exception.args[0])