blob: e8fb8d2f9cc603ac450b319b738849daf44b7c74 [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)
258 self.assertIn(b"history " + expected + b"\r\n", output)
259
Nir Sofferaa6a4d62017-07-08 17:34:27 +0300260 # We have 2 reasons to skip this test:
261 # - readline: history size was added in 6.0
262 # See https://cnswww.cns.cwru.edu/php/chet/readline/CHANGES
263 # - editline: history size is broken on OS X 10.11.6.
264 # Newer versions were not tested yet.
265 @unittest.skipIf(readline._READLINE_VERSION < 0x600,
266 "this readline version does not support history-size")
Nir Sofferfae8f4a2017-07-07 09:10:46 +0300267 @unittest.skipIf(is_editline,
268 "editline history size configuration is broken")
269 def test_history_size(self):
270 history_size = 10
271 with temp_dir() as test_dir:
272 inputrc = os.path.join(test_dir, "inputrc")
273 with open(inputrc, "wb") as f:
274 f.write(b"set history-size %d\n" % history_size)
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000275
Nir Sofferfae8f4a2017-07-07 09:10:46 +0300276 history_file = os.path.join(test_dir, "history")
277 with open(history_file, "wb") as f:
278 # history_size * 2 items crashes readline
279 data = b"".join(b"item %d\n" % i
280 for i in range(history_size * 2))
281 f.write(data)
282
283 script = """
284import os
285import readline
286
287history_file = os.environ["HISTORY_FILE"]
288readline.read_history_file(history_file)
289input()
290readline.write_history_file(history_file)
291"""
292
293 env = dict(os.environ)
294 env["INPUTRC"] = inputrc
295 env["HISTORY_FILE"] = history_file
296
297 run_pty(script, input=b"last input\r", env=env)
298
299 with open(history_file, "rb") as f:
300 lines = f.readlines()
301 self.assertEqual(len(lines), history_size)
302 self.assertEqual(lines[-1].strip(), b"last input")
303
304
305def run_pty(script, input=b"dummy input\r", env=None):
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000306 pty = import_module('pty')
307 output = bytearray()
308 [master, slave] = pty.openpty()
309 args = (sys.executable, '-c', script)
Nir Sofferfae8f4a2017-07-07 09:10:46 +0300310 proc = subprocess.Popen(args, stdin=slave, stdout=slave, stderr=slave, env=env)
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000311 os.close(slave)
Martin Panter37126862016-05-15 03:05:36 +0000312 with ExitStack() as cleanup:
313 cleanup.enter_context(proc)
Martin Panter79f561d2016-05-15 15:04:58 +0000314 def terminate(proc):
315 try:
316 proc.terminate()
317 except ProcessLookupError:
318 # Workaround for Open/Net BSD bug (Issue 16762)
319 pass
320 cleanup.callback(terminate, proc)
Martin Panter37126862016-05-15 03:05:36 +0000321 cleanup.callback(os.close, master)
Martin Panter79f561d2016-05-15 15:04:58 +0000322 # Avoid using DefaultSelector and PollSelector. Kqueue() does not
323 # work with pseudo-terminals on OS X < 10.9 (Issue 20365) and Open
324 # BSD (Issue 20667). Poll() does not work with OS X 10.6 or 10.4
325 # either (Issue 20472). Hopefully the file descriptor is low enough
326 # to use with select().
327 sel = cleanup.enter_context(selectors.SelectSelector())
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000328 sel.register(master, selectors.EVENT_READ | selectors.EVENT_WRITE)
329 os.set_blocking(master, False)
330 while True:
331 for [_, events] in sel.select():
332 if events & selectors.EVENT_READ:
333 try:
334 chunk = os.read(master, 0x10000)
335 except OSError as err:
Martin Panterf00c49d2016-06-14 01:16:16 +0000336 # Linux raises EIO when slave is closed (Issue 5380)
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000337 if err.errno != EIO:
338 raise
339 chunk = b""
340 if not chunk:
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000341 return output
342 output.extend(chunk)
343 if events & selectors.EVENT_WRITE:
Martin Panterf00c49d2016-06-14 01:16:16 +0000344 try:
345 input = input[os.write(master, input):]
346 except OSError as err:
347 # Apparently EIO means the slave was closed
348 if err.errno != EIO:
349 raise
350 input = b"" # Stop writing
Martin Panterf0dbf7a2016-05-15 01:26:25 +0000351 if not input:
352 sel.modify(master, selectors.EVENT_READ)
353
Victor Stinnera3c80ce2014-07-24 12:23:56 +0200354
Ronald Oussoren2efd9242009-09-20 14:53:22 +0000355if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500356 unittest.main()