test_readline.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. """
  2. Very minimal unittests for parts of the readline module.
  3. """
  4. from contextlib import ExitStack
  5. from errno import EIO
  6. import locale
  7. import os
  8. import selectors
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import unittest
  13. from test.support import verbose
  14. from test.support.import_helper import import_module
  15. from test.support.os_helper import unlink, temp_dir, TESTFN
  16. from test.support.script_helper import assert_python_ok
  17. # Skip tests if there is no readline module
  18. readline = import_module('readline')
  19. if hasattr(readline, "_READLINE_LIBRARY_VERSION"):
  20. is_editline = ("EditLine wrapper" in readline._READLINE_LIBRARY_VERSION)
  21. else:
  22. is_editline = (readline.__doc__ and "libedit" in readline.__doc__)
  23. def setUpModule():
  24. if verbose:
  25. # Python implementations other than CPython may not have
  26. # these private attributes
  27. if hasattr(readline, "_READLINE_VERSION"):
  28. print(f"readline version: {readline._READLINE_VERSION:#x}")
  29. print(f"readline runtime version: {readline._READLINE_RUNTIME_VERSION:#x}")
  30. if hasattr(readline, "_READLINE_LIBRARY_VERSION"):
  31. print(f"readline library version: {readline._READLINE_LIBRARY_VERSION!r}")
  32. print(f"use libedit emulation? {is_editline}")
  33. @unittest.skipUnless(hasattr(readline, "clear_history"),
  34. "The history update test cannot be run because the "
  35. "clear_history method is not available.")
  36. class TestHistoryManipulation (unittest.TestCase):
  37. """
  38. These tests were added to check that the libedit emulation on OSX and the
  39. "real" readline have the same interface for history manipulation. That's
  40. why the tests cover only a small subset of the interface.
  41. """
  42. def testHistoryUpdates(self):
  43. readline.clear_history()
  44. readline.add_history("first line")
  45. readline.add_history("second line")
  46. self.assertEqual(readline.get_history_item(0), None)
  47. self.assertEqual(readline.get_history_item(1), "first line")
  48. self.assertEqual(readline.get_history_item(2), "second line")
  49. readline.replace_history_item(0, "replaced line")
  50. self.assertEqual(readline.get_history_item(0), None)
  51. self.assertEqual(readline.get_history_item(1), "replaced line")
  52. self.assertEqual(readline.get_history_item(2), "second line")
  53. self.assertEqual(readline.get_current_history_length(), 2)
  54. readline.remove_history_item(0)
  55. self.assertEqual(readline.get_history_item(0), None)
  56. self.assertEqual(readline.get_history_item(1), "second line")
  57. self.assertEqual(readline.get_current_history_length(), 1)
  58. @unittest.skipUnless(hasattr(readline, "append_history_file"),
  59. "append_history not available")
  60. def test_write_read_append(self):
  61. hfile = tempfile.NamedTemporaryFile(delete=False)
  62. hfile.close()
  63. hfilename = hfile.name
  64. self.addCleanup(unlink, hfilename)
  65. # test write-clear-read == nop
  66. readline.clear_history()
  67. readline.add_history("first line")
  68. readline.add_history("second line")
  69. readline.write_history_file(hfilename)
  70. readline.clear_history()
  71. self.assertEqual(readline.get_current_history_length(), 0)
  72. readline.read_history_file(hfilename)
  73. self.assertEqual(readline.get_current_history_length(), 2)
  74. self.assertEqual(readline.get_history_item(1), "first line")
  75. self.assertEqual(readline.get_history_item(2), "second line")
  76. # test append
  77. readline.append_history_file(1, hfilename)
  78. readline.clear_history()
  79. readline.read_history_file(hfilename)
  80. self.assertEqual(readline.get_current_history_length(), 3)
  81. self.assertEqual(readline.get_history_item(1), "first line")
  82. self.assertEqual(readline.get_history_item(2), "second line")
  83. self.assertEqual(readline.get_history_item(3), "second line")
  84. # test 'no such file' behaviour
  85. os.unlink(hfilename)
  86. try:
  87. readline.append_history_file(1, hfilename)
  88. except FileNotFoundError:
  89. pass # Some implementations return this error (libreadline).
  90. else:
  91. os.unlink(hfilename) # Some create it anyways (libedit).
  92. # If the file wasn't created, unlink will fail.
  93. # We're just testing that one of the two expected behaviors happens
  94. # instead of an incorrect error.
  95. # write_history_file can create the target
  96. readline.write_history_file(hfilename)
  97. def test_nonascii_history(self):
  98. readline.clear_history()
  99. try:
  100. readline.add_history("entrée 1")
  101. except UnicodeEncodeError as err:
  102. self.skipTest("Locale cannot encode test data: " + format(err))
  103. readline.add_history("entrée 2")
  104. readline.replace_history_item(1, "entrée 22")
  105. readline.write_history_file(TESTFN)
  106. self.addCleanup(os.remove, TESTFN)
  107. readline.clear_history()
  108. readline.read_history_file(TESTFN)
  109. if is_editline:
  110. # An add_history() call seems to be required for get_history_
  111. # item() to register items from the file
  112. readline.add_history("dummy")
  113. self.assertEqual(readline.get_history_item(1), "entrée 1")
  114. self.assertEqual(readline.get_history_item(2), "entrée 22")
  115. class TestReadline(unittest.TestCase):
  116. @unittest.skipIf(readline._READLINE_VERSION < 0x0601 and not is_editline,
  117. "not supported in this library version")
  118. def test_init(self):
  119. # Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not
  120. # written into stdout when the readline module is imported and stdout
  121. # is redirected to a pipe.
  122. rc, stdout, stderr = assert_python_ok('-c', 'import readline',
  123. TERM='xterm-256color')
  124. self.assertEqual(stdout, b'')
  125. auto_history_script = """\
  126. import readline
  127. readline.set_auto_history({})
  128. input()
  129. print("History length:", readline.get_current_history_length())
  130. """
  131. def test_auto_history_enabled(self):
  132. output = run_pty(self.auto_history_script.format(True))
  133. # bpo-44949: Sometimes, the newline character is not written at the
  134. # end, so don't expect it in the output.
  135. self.assertIn(b"History length: 1", output)
  136. def test_auto_history_disabled(self):
  137. output = run_pty(self.auto_history_script.format(False))
  138. # bpo-44949: Sometimes, the newline character is not written at the
  139. # end, so don't expect it in the output.
  140. self.assertIn(b"History length: 0", output)
  141. def test_nonascii(self):
  142. loc = locale.setlocale(locale.LC_CTYPE, None)
  143. if loc in ('C', 'POSIX'):
  144. # bpo-29240: On FreeBSD, if the LC_CTYPE locale is C or POSIX,
  145. # writing and reading non-ASCII bytes into/from a TTY works, but
  146. # readline or ncurses ignores non-ASCII bytes on read.
  147. self.skipTest(f"the LC_CTYPE locale is {loc!r}")
  148. try:
  149. readline.add_history("\xEB\xEF")
  150. except UnicodeEncodeError as err:
  151. self.skipTest("Locale cannot encode test data: " + format(err))
  152. script = r"""import readline
  153. is_editline = readline.__doc__ and "libedit" in readline.__doc__
  154. inserted = "[\xEFnserted]"
  155. macro = "|t\xEB[after]"
  156. set_pre_input_hook = getattr(readline, "set_pre_input_hook", None)
  157. if is_editline or not set_pre_input_hook:
  158. # The insert_line() call via pre_input_hook() does nothing with Editline,
  159. # so include the extra text that would have been inserted here
  160. macro = inserted + macro
  161. if is_editline:
  162. readline.parse_and_bind(r'bind ^B ed-prev-char')
  163. readline.parse_and_bind(r'bind "\t" rl_complete')
  164. readline.parse_and_bind(r'bind -s ^A "{}"'.format(macro))
  165. else:
  166. readline.parse_and_bind(r'Control-b: backward-char')
  167. readline.parse_and_bind(r'"\t": complete')
  168. readline.parse_and_bind(r'set disable-completion off')
  169. readline.parse_and_bind(r'set show-all-if-ambiguous off')
  170. readline.parse_and_bind(r'set show-all-if-unmodified off')
  171. readline.parse_and_bind(r'Control-a: "{}"'.format(macro))
  172. def pre_input_hook():
  173. readline.insert_text(inserted)
  174. readline.redisplay()
  175. if set_pre_input_hook:
  176. set_pre_input_hook(pre_input_hook)
  177. def completer(text, state):
  178. if text == "t\xEB":
  179. if state == 0:
  180. print("text", ascii(text))
  181. print("line", ascii(readline.get_line_buffer()))
  182. print("indexes", readline.get_begidx(), readline.get_endidx())
  183. return "t\xEBnt"
  184. if state == 1:
  185. return "t\xEBxt"
  186. if text == "t\xEBx" and state == 0:
  187. return "t\xEBxt"
  188. return None
  189. readline.set_completer(completer)
  190. def display(substitution, matches, longest_match_length):
  191. print("substitution", ascii(substitution))
  192. print("matches", ascii(matches))
  193. readline.set_completion_display_matches_hook(display)
  194. print("result", ascii(input()))
  195. print("history", ascii(readline.get_history_item(1)))
  196. """
  197. input = b"\x01" # Ctrl-A, expands to "|t\xEB[after]"
  198. input += b"\x02" * len("[after]") # Move cursor back
  199. input += b"\t\t" # Display possible completions
  200. input += b"x\t" # Complete "t\xEBx" -> "t\xEBxt"
  201. input += b"\r"
  202. output = run_pty(script, input)
  203. self.assertIn(b"text 't\\xeb'\r\n", output)
  204. self.assertIn(b"line '[\\xefnserted]|t\\xeb[after]'\r\n", output)
  205. if sys.platform == "darwin" or not is_editline:
  206. self.assertIn(b"indexes 11 13\r\n", output)
  207. # Non-macOS libedit does not handle non-ASCII bytes
  208. # the same way and generates character indices
  209. # rather than byte indices via get_begidx() and
  210. # get_endidx(). Ex: libedit2 3.1-20191231-2 on Debian
  211. # winds up with "indexes 10 12". Stemming from the
  212. # start and end values calls back into readline.c's
  213. # rl_attempted_completion_function = flex_complete with:
  214. # (11, 13) instead of libreadline's (12, 15).
  215. if not is_editline and hasattr(readline, "set_pre_input_hook"):
  216. self.assertIn(b"substitution 't\\xeb'\r\n", output)
  217. self.assertIn(b"matches ['t\\xebnt', 't\\xebxt']\r\n", output)
  218. expected = br"'[\xefnserted]|t\xebxt[after]'"
  219. self.assertIn(b"result " + expected + b"\r\n", output)
  220. # bpo-45195: Sometimes, the newline character is not written at the
  221. # end, so don't expect it in the output.
  222. self.assertIn(b"history " + expected, output)
  223. # We have 2 reasons to skip this test:
  224. # - readline: history size was added in 6.0
  225. # See https://cnswww.cns.cwru.edu/php/chet/readline/CHANGES
  226. # - editline: history size is broken on OS X 10.11.6.
  227. # Newer versions were not tested yet.
  228. @unittest.skipIf(readline._READLINE_VERSION < 0x600,
  229. "this readline version does not support history-size")
  230. @unittest.skipIf(is_editline,
  231. "editline history size configuration is broken")
  232. def test_history_size(self):
  233. history_size = 10
  234. with temp_dir() as test_dir:
  235. inputrc = os.path.join(test_dir, "inputrc")
  236. with open(inputrc, "wb") as f:
  237. f.write(b"set history-size %d\n" % history_size)
  238. history_file = os.path.join(test_dir, "history")
  239. with open(history_file, "wb") as f:
  240. # history_size * 2 items crashes readline
  241. data = b"".join(b"item %d\n" % i
  242. for i in range(history_size * 2))
  243. f.write(data)
  244. script = """
  245. import os
  246. import readline
  247. history_file = os.environ["HISTORY_FILE"]
  248. readline.read_history_file(history_file)
  249. input()
  250. readline.write_history_file(history_file)
  251. """
  252. env = dict(os.environ)
  253. env["INPUTRC"] = inputrc
  254. env["HISTORY_FILE"] = history_file
  255. run_pty(script, input=b"last input\r", env=env)
  256. with open(history_file, "rb") as f:
  257. lines = f.readlines()
  258. self.assertEqual(len(lines), history_size)
  259. self.assertEqual(lines[-1].strip(), b"last input")
  260. def run_pty(script, input=b"dummy input\r", env=None):
  261. pty = import_module('pty')
  262. output = bytearray()
  263. [master, slave] = pty.openpty()
  264. args = (sys.executable, '-c', script)
  265. proc = subprocess.Popen(args, stdin=slave, stdout=slave, stderr=slave, env=env)
  266. os.close(slave)
  267. with ExitStack() as cleanup:
  268. cleanup.enter_context(proc)
  269. def terminate(proc):
  270. try:
  271. proc.terminate()
  272. except ProcessLookupError:
  273. # Workaround for Open/Net BSD bug (Issue 16762)
  274. pass
  275. cleanup.callback(terminate, proc)
  276. cleanup.callback(os.close, master)
  277. # Avoid using DefaultSelector and PollSelector. Kqueue() does not
  278. # work with pseudo-terminals on OS X < 10.9 (Issue 20365) and Open
  279. # BSD (Issue 20667). Poll() does not work with OS X 10.6 or 10.4
  280. # either (Issue 20472). Hopefully the file descriptor is low enough
  281. # to use with select().
  282. sel = cleanup.enter_context(selectors.SelectSelector())
  283. sel.register(master, selectors.EVENT_READ | selectors.EVENT_WRITE)
  284. os.set_blocking(master, False)
  285. while True:
  286. for [_, events] in sel.select():
  287. if events & selectors.EVENT_READ:
  288. try:
  289. chunk = os.read(master, 0x10000)
  290. except OSError as err:
  291. # Linux raises EIO when slave is closed (Issue 5380)
  292. if err.errno != EIO:
  293. raise
  294. chunk = b""
  295. if not chunk:
  296. return output
  297. output.extend(chunk)
  298. if events & selectors.EVENT_WRITE:
  299. try:
  300. input = input[os.write(master, input):]
  301. except OSError as err:
  302. # Apparently EIO means the slave was closed
  303. if err.errno != EIO:
  304. raise
  305. input = b"" # Stop writing
  306. if not input:
  307. sel.modify(master, selectors.EVENT_READ)
  308. if __name__ == "__main__":
  309. unittest.main()