blob: 59dbef903800530e2b91f904a951174b249cda4d [file] [log] [blame]
Ronald Oussoren2efd9242009-09-20 14:53:22 +00001"""
2Very minimal unittests for parts of the readline module.
Ronald Oussoren2efd9242009-09-20 14:53:22 +00003"""
Martin Panter37126862016-05-15 03:05:36 +00004from contextlib import ExitStack
Martin Panterf0dbf7a2016-05-15 01:26:25 +00005from errno import EIO
Victor Stinnerc495e792018-01-16 17:34:34 +01006import locale
Victor Stinnera3c80ce2014-07-24 12:23:56 +02007import os
Martin Panterf0dbf7a2016-05-15 01:26:25 +00008import selectors
9import subprocess
10import sys
Benjamin Peterson33f8f152014-11-26 13:58:16 -060011import tempfile
Ronald Oussoren2efd9242009-09-20 14:53:22 +000012import unittest
Hai Shi847f94f2020-06-26 01:17:57 +080013from test.support import verbose
14from test.support.import_helper import import_module
15from test.support.os_helper import unlink, temp_dir, TESTFN
Berker Peksagce643912015-05-06 06:33:17 +030016from test.support.script_helper import assert_python_ok
Ronald Oussoren2efd9242009-09-20 14:53:22 +000017
Mark Dickinson2d7062e2009-10-26 12:01:06 +000018# Skip tests if there is no readline module
19readline = import_module('readline')
Ronald Oussoren2efd9242009-09-20 14:53:22 +000020
Victor Stinner1881bef2017-07-07 16:06:58 +020021if hasattr(readline, "_READLINE_LIBRARY_VERSION"):
22 is_editline = ("EditLine wrapper" in readline._READLINE_LIBRARY_VERSION)
23else:
24 is_editline = (readline.__doc__ and "libedit" in readline.__doc__)
25
26
27def setUpModule():
28 if verbose:
29 # Python implementations other than CPython may not have
30 # these private attributes
31 if hasattr(readline, "_READLINE_VERSION"):
32 print(f"readline version: {readline._READLINE_VERSION:#x}")
33 print(f"readline runtime version: {readline._READLINE_RUNTIME_VERSION:#x}")
34 if hasattr(readline, "_READLINE_LIBRARY_VERSION"):
35 print(f"readline library version: {readline._READLINE_LIBRARY_VERSION!r}")
36 print(f"use libedit emulation? {is_editline}")
37
Martin Panter056f76d2016-06-14 05:45:31 +000038
Martin Panterf00c49d2016-06-14 01:16:16 +000039@unittest.skipUnless(hasattr(readline, "clear_history"),
40 "The history update test cannot be run because the "
41 "clear_history method is not available.")
Ronald Oussoren2efd9242009-09-20 14:53:22 +000042class TestHistoryManipulation (unittest.TestCase):
Victor Stinnera3c80ce2014-07-24 12:23:56 +020043 """
44 These tests were added to check that the libedit emulation on OSX and the
45 "real" readline have the same interface for history manipulation. That's
46 why the tests cover only a small subset of the interface.
47 """
R David Murrayf8b9dfd2011-03-14 17:10:22 -040048
Ronald Oussoren2efd9242009-09-20 14:53:22 +000049 def testHistoryUpdates(self):
Georg Brandl7b250a52012-08-11 11:02:14 +020050 readline.clear_history()
Ronald Oussoren2efd9242009-09-20 14:53:22 +000051
52 readline.add_history("first line")
53 readline.add_history("second line")
54
55 self.assertEqual(readline.get_history_item(0), None)
56 self.assertEqual(readline.get_history_item(1), "first line")
57 self.assertEqual(readline.get_history_item(2), "second line")
58
59 readline.replace_history_item(0, "replaced line")
60 self.assertEqual(readline.get_history_item(0), None)
61 self.assertEqual(readline.get_history_item(1), "replaced line")
62 self.assertEqual(readline.get_history_item(2), "second line")
63
64 self.assertEqual(readline.get_current_history_length(), 2)
65
66 readline.remove_history_item(0)
67 self.assertEqual(readline.get_history_item(0), None)
68 self.assertEqual(readline.get_history_item(1), "second line")
69
70 self.assertEqual(readline.get_current_history_length(), 1)
71
Ned Deily8007cbc2014-11-26 13:02:33 -080072 @unittest.skipUnless(hasattr(readline, "append_history_file"),
Benjamin Petersond1e22ba2014-11-26 14:35:12 -060073 "append_history not available")
Benjamin Peterson33f8f152014-11-26 13:58:16 -060074 def test_write_read_append(self):
75 hfile = tempfile.NamedTemporaryFile(delete=False)
76 hfile.close()
77 hfilename = hfile.name
78 self.addCleanup(unlink, hfilename)
79
80 # test write-clear-read == nop
81 readline.clear_history()
82 readline.add_history("first line")
83 readline.add_history("second line")
84 readline.write_history_file(hfilename)
85
86 readline.clear_history()
87 self.assertEqual(readline.get_current_history_length(), 0)
88
89 readline.read_history_file(hfilename)
90 self.assertEqual(readline.get_current_history_length(), 2)
91 self.assertEqual(readline.get_history_item(1), "first line")
92 self.assertEqual(readline.get_history_item(2), "second line")
93
94 # test append
95 readline.append_history_file(1, hfilename)
96 readline.clear_history()
97 readline.read_history_file(hfilename)
98 self.assertEqual(readline.get_current_history_length(), 3)
99 self.assertEqual(readline.get_history_item(1), "first line")
100 self.assertEqual(readline.get_history_item(2), "second line")
101 self.assertEqual(readline.get_history_item(3), "second line")
102
103 # test 'no such file' behaviour
104 os.unlink(hfilename)
Gregory P. Smithfd053fd2021-02-12 12:04:46 -0800105 try:
Benjamin Peterson33f8f152014-11-26 13:58:16 -0600106 readline.append_history_file(1, hfilename)
Gregory P. Smithfd053fd2021-02-12 12:04:46 -0800107 except FileNotFoundError:
108 pass # Some implementations return this error (libreadline).
109 else:
110 os.unlink(hfilename) # Some create it anyways (libedit).
111 # If the file wasn't created, unlink will fail.
112 # We're just testing that one of the two expected behaviors happens
113 # instead of an incorrect error.
Benjamin Peterson33f8f152014-11-26 13:58:16 -0600114
115 # write_history_file can create the target
116 readline.write_history_file(hfilename)
117
Martin Panterf00c49d2016-06-14 01:16:16 +0000118 def test_nonascii_history(self):
119 readline.clear_history()
120 try:
121 readline.add_history("entrée 1")
122 except UnicodeEncodeError as err:
123 self.skipTest("Locale cannot encode test data: " + format(err))
124 readline.add_history("entrée 2")
125 readline.replace_history_item(1, "entrée 22")
126 readline.write_history_file(TESTFN)
127 self.addCleanup(os.remove, TESTFN)
128 readline.clear_history()
129 readline.read_history_file(TESTFN)
Martin Panter056f76d2016-06-14 05:45:31 +0000130 if is_editline:
131 # An add_history() call seems to be required for get_history_
132 # item() to register items from the file
133 readline.add_history("dummy")
Martin Panterf00c49d2016-06-14 01:16:16 +0000134 self.assertEqual(readline.get_history_item(1), "entrée 1")
135 self.assertEqual(readline.get_history_item(2), "entrée 22")
136
Ronald Oussoren2efd9242009-09-20 14:53:22 +0000137
Victor Stinnera3c80ce2014-07-24 12:23:56 +0200138class TestReadline(unittest.TestCase):
Antoine Pitrou7e8b8672014-11-04 14:52:10 +0100139
Martin Panterc427b8d2016-08-27 03:23:11 +0000140 @unittest.skipIf(readline._READLINE_VERSION < 0x0601 and not is_editline,
Antoine Pitrou7e8b8672014-11-04 14:52:10 +0100141 "not supported in this library version")
Victor Stinnera3c80ce2014-07-24 12:23:56 +0200142 def test_init(self):
143 # Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not
144 # written into stdout when the readline module is imported and stdout
145 # is redirected to a pipe.
146 rc, stdout, stderr = assert_python_ok('-c', 'import readline',
147 TERM='xterm-256color')
148 self.assertEqual(stdout, b'')
149
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000150 auto_history_script = """\
151import readline
152readline.set_auto_history({})
153input()
154print("History length:", readline.get_current_history_length())
155"""
156
157 def test_auto_history_enabled(self):
158 output = run_pty(self.auto_history_script.format(True))
Miss Islington (bot)fc6ad052021-08-19 01:52:16 -0700159 # bpo-44949: Sometimes, the newline character is not written at the
160 # end, so don't expect it in the output.
161 self.assertIn(b"History length: 1", output)
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000162
163 def test_auto_history_disabled(self):
164 output = run_pty(self.auto_history_script.format(False))
Miss Islington (bot)fc6ad052021-08-19 01:52:16 -0700165 # bpo-44949: Sometimes, the newline character is not written at the
166 # end, so don't expect it in the output.
167 self.assertIn(b"History length: 0", output)
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000168
Martin Panterf00c49d2016-06-14 01:16:16 +0000169 def test_nonascii(self):
Victor Stinnerc495e792018-01-16 17:34:34 +0100170 loc = locale.setlocale(locale.LC_CTYPE, None)
171 if loc in ('C', 'POSIX'):
172 # bpo-29240: On FreeBSD, if the LC_CTYPE locale is C or POSIX,
173 # writing and reading non-ASCII bytes into/from a TTY works, but
174 # readline or ncurses ignores non-ASCII bytes on read.
175 self.skipTest(f"the LC_CTYPE locale is {loc!r}")
176
Martin Panterf00c49d2016-06-14 01:16:16 +0000177 try:
178 readline.add_history("\xEB\xEF")
179 except UnicodeEncodeError as err:
180 self.skipTest("Locale cannot encode test data: " + format(err))
181
182 script = r"""import readline
183
Martin Panter6afbc652016-06-14 08:45:43 +0000184is_editline = readline.__doc__ and "libedit" in readline.__doc__
185inserted = "[\xEFnserted]"
186macro = "|t\xEB[after]"
187set_pre_input_hook = getattr(readline, "set_pre_input_hook", None)
188if is_editline or not set_pre_input_hook:
Martin Panter056f76d2016-06-14 05:45:31 +0000189 # The insert_line() call via pre_input_hook() does nothing with Editline,
190 # so include the extra text that would have been inserted here
Martin Panter6afbc652016-06-14 08:45:43 +0000191 macro = inserted + macro
192
193if is_editline:
194 readline.parse_and_bind(r'bind ^B ed-prev-char')
195 readline.parse_and_bind(r'bind "\t" rl_complete')
196 readline.parse_and_bind(r'bind -s ^A "{}"'.format(macro))
Martin Panterf00c49d2016-06-14 01:16:16 +0000197else:
198 readline.parse_and_bind(r'Control-b: backward-char')
199 readline.parse_and_bind(r'"\t": complete')
200 readline.parse_and_bind(r'set disable-completion off')
201 readline.parse_and_bind(r'set show-all-if-ambiguous off')
202 readline.parse_and_bind(r'set show-all-if-unmodified off')
Martin Panter6afbc652016-06-14 08:45:43 +0000203 readline.parse_and_bind(r'Control-a: "{}"'.format(macro))
Martin Panterf00c49d2016-06-14 01:16:16 +0000204
205def pre_input_hook():
Martin Panter6afbc652016-06-14 08:45:43 +0000206 readline.insert_text(inserted)
Martin Panterf00c49d2016-06-14 01:16:16 +0000207 readline.redisplay()
Martin Panter6afbc652016-06-14 08:45:43 +0000208if set_pre_input_hook:
209 set_pre_input_hook(pre_input_hook)
Martin Panterf00c49d2016-06-14 01:16:16 +0000210
211def completer(text, state):
212 if text == "t\xEB":
213 if state == 0:
214 print("text", ascii(text))
215 print("line", ascii(readline.get_line_buffer()))
216 print("indexes", readline.get_begidx(), readline.get_endidx())
217 return "t\xEBnt"
218 if state == 1:
219 return "t\xEBxt"
220 if text == "t\xEBx" and state == 0:
221 return "t\xEBxt"
222 return None
223readline.set_completer(completer)
224
225def display(substitution, matches, longest_match_length):
226 print("substitution", ascii(substitution))
227 print("matches", ascii(matches))
228readline.set_completion_display_matches_hook(display)
229
230print("result", ascii(input()))
231print("history", ascii(readline.get_history_item(1)))
232"""
233
234 input = b"\x01" # Ctrl-A, expands to "|t\xEB[after]"
235 input += b"\x02" * len("[after]") # Move cursor back
236 input += b"\t\t" # Display possible completions
237 input += b"x\t" # Complete "t\xEBx" -> "t\xEBxt"
238 input += b"\r"
239 output = run_pty(script, input)
240 self.assertIn(b"text 't\\xeb'\r\n", output)
241 self.assertIn(b"line '[\\xefnserted]|t\\xeb[after]'\r\n", output)
Gregory P. Smithfd053fd2021-02-12 12:04:46 -0800242 if sys.platform == "darwin" or not is_editline:
243 self.assertIn(b"indexes 11 13\r\n", output)
244 # Non-macOS libedit does not handle non-ASCII bytes
245 # the same way and generates character indices
246 # rather than byte indices via get_begidx() and
247 # get_endidx(). Ex: libedit2 3.1-20191231-2 on Debian
248 # winds up with "indexes 10 12". Stemming from the
249 # start and end values calls back into readline.c's
250 # rl_attempted_completion_function = flex_complete with:
251 # (11, 13) instead of libreadline's (12, 15).
252
Martin Pantera8cadb22016-06-14 11:29:31 +0000253 if not is_editline and hasattr(readline, "set_pre_input_hook"):
Martin Panter056f76d2016-06-14 05:45:31 +0000254 self.assertIn(b"substitution 't\\xeb'\r\n", output)
255 self.assertIn(b"matches ['t\\xebnt', 't\\xebxt']\r\n", output)
Martin Panterf00c49d2016-06-14 01:16:16 +0000256 expected = br"'[\xefnserted]|t\xebxt[after]'"
257 self.assertIn(b"result " + expected + b"\r\n", output)
Miss Islington (bot)ececa532021-09-15 05:38:49 -0700258 # bpo-45195: Sometimes, the newline character is not written at the
259 # end, so don't expect it in the output.
260 self.assertIn(b"history " + expected, output)
Martin Panterf00c49d2016-06-14 01:16:16 +0000261
Nir Sofferaa6a4d62017-07-08 17:34:27 +0300262 # We have 2 reasons to skip this test:
263 # - readline: history size was added in 6.0
264 # See https://cnswww.cns.cwru.edu/php/chet/readline/CHANGES
265 # - editline: history size is broken on OS X 10.11.6.
266 # Newer versions were not tested yet.
267 @unittest.skipIf(readline._READLINE_VERSION < 0x600,
268 "this readline version does not support history-size")
Nir Sofferfae8f4a2017-07-07 09:10:46 +0300269 @unittest.skipIf(is_editline,
270 "editline history size configuration is broken")
271 def test_history_size(self):
272 history_size = 10
273 with temp_dir() as test_dir:
274 inputrc = os.path.join(test_dir, "inputrc")
275 with open(inputrc, "wb") as f:
276 f.write(b"set history-size %d\n" % history_size)
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000277
Nir Sofferfae8f4a2017-07-07 09:10:46 +0300278 history_file = os.path.join(test_dir, "history")
279 with open(history_file, "wb") as f:
280 # history_size * 2 items crashes readline
281 data = b"".join(b"item %d\n" % i
282 for i in range(history_size * 2))
283 f.write(data)
284
285 script = """
286import os
287import readline
288
289history_file = os.environ["HISTORY_FILE"]
290readline.read_history_file(history_file)
291input()
292readline.write_history_file(history_file)
293"""
294
295 env = dict(os.environ)
296 env["INPUTRC"] = inputrc
297 env["HISTORY_FILE"] = history_file
298
299 run_pty(script, input=b"last input\r", env=env)
300
301 with open(history_file, "rb") as f:
302 lines = f.readlines()
303 self.assertEqual(len(lines), history_size)
304 self.assertEqual(lines[-1].strip(), b"last input")
305
306
307def run_pty(script, input=b"dummy input\r", env=None):
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000308 pty = import_module('pty')
309 output = bytearray()
310 [master, slave] = pty.openpty()
311 args = (sys.executable, '-c', script)
Nir Sofferfae8f4a2017-07-07 09:10:46 +0300312 proc = subprocess.Popen(args, stdin=slave, stdout=slave, stderr=slave, env=env)
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000313 os.close(slave)
Martin Panter37126862016-05-15 03:05:36 +0000314 with ExitStack() as cleanup:
315 cleanup.enter_context(proc)
Martin Panter79f561d2016-05-15 15:04:58 +0000316 def terminate(proc):
317 try:
318 proc.terminate()
319 except ProcessLookupError:
320 # Workaround for Open/Net BSD bug (Issue 16762)
321 pass
322 cleanup.callback(terminate, proc)
Martin Panter37126862016-05-15 03:05:36 +0000323 cleanup.callback(os.close, master)
Martin Panter79f561d2016-05-15 15:04:58 +0000324 # Avoid using DefaultSelector and PollSelector. Kqueue() does not
325 # work with pseudo-terminals on OS X < 10.9 (Issue 20365) and Open
326 # BSD (Issue 20667). Poll() does not work with OS X 10.6 or 10.4
327 # either (Issue 20472). Hopefully the file descriptor is low enough
328 # to use with select().
329 sel = cleanup.enter_context(selectors.SelectSelector())
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000330 sel.register(master, selectors.EVENT_READ | selectors.EVENT_WRITE)
331 os.set_blocking(master, False)
332 while True:
333 for [_, events] in sel.select():
334 if events & selectors.EVENT_READ:
335 try:
336 chunk = os.read(master, 0x10000)
337 except OSError as err:
Martin Panterf00c49d2016-06-14 01:16:16 +0000338 # Linux raises EIO when slave is closed (Issue 5380)
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000339 if err.errno != EIO:
340 raise
341 chunk = b""
342 if not chunk:
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000343 return output
344 output.extend(chunk)
345 if events & selectors.EVENT_WRITE:
Martin Panterf00c49d2016-06-14 01:16:16 +0000346 try:
347 input = input[os.write(master, input):]
348 except OSError as err:
349 # Apparently EIO means the slave was closed
350 if err.errno != EIO:
351 raise
352 input = b"" # Stop writing
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000353 if not input:
354 sel.modify(master, selectors.EVENT_READ)
355
Victor Stinnera3c80ce2014-07-24 12:23:56 +0200356
Ronald Oussoren2efd9242009-09-20 14:53:22 +0000357if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500358 unittest.main()