Debian Codegraph @

Lib/test/test_readline.py

raw
1 """
2 Very minimal unittests for parts of the readline module.
3 """
4 import codecs
5 import locale
6 import os
7 import sys
8 import tempfile
9 import textwrap
10 import unittest
11 from test.support import verbose
12 from test.support.import_helper import import_module
13 from test.support.os_helper import unlink, temp_dir, TESTFN
14 from test.support.pty_helper import run_pty
15 from test.support.script_helper import assert_python_ok
16 from test.support.threading_helper import requires_working_threading
17
18 # Skip tests if there is no readline module
19 readline = import_module('readline')
20
21 if hasattr(readline, "_READLINE_LIBRARY_VERSION"):
22 is_editline = ("EditLine wrapper" in readline._READLINE_LIBRARY_VERSION)
23 else:
24 is_editline = readline.backend == "editline"
25
26
27 def 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
38
39 @unittest.skipUnless(hasattr(readline, "clear_history"),
40 "The history update test cannot be run because the "
41 "clear_history method is not available.")
42 class TestHistoryManipulation (unittest.TestCase):
43 """
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 """
48
49 def testHistoryUpdates(self):
50 readline.clear_history()
51
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
72 @unittest.skipUnless(hasattr(readline, "append_history_file"),
73 "append_history not available")
74 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)
105 try:
106 readline.append_history_file(1, hfilename)
107 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.
114
115 # write_history_file can create the target
116 readline.write_history_file(hfilename)
117
118 # Negative values should be disallowed
119 with self.assertRaises(ValueError):
120 readline.append_history_file(-42, hfilename)
121
122 # See gh-122431, using the minimum signed integer value caused a segfault
123 with self.assertRaises(ValueError):
124 readline.append_history_file(-2147483648, hfilename)
125
126 def test_nonascii_history(self):
127 readline.clear_history()
128 try:
129 readline.add_history("entrée 1")
130 except UnicodeEncodeError as err:
131 self.skipTest("Locale cannot encode test data: " + format(err))
132 readline.add_history("entrée 2")
133 readline.replace_history_item(1, "entrée 22")
134 readline.write_history_file(TESTFN)
135 self.addCleanup(os.remove, TESTFN)
136 readline.clear_history()
137 readline.read_history_file(TESTFN)
138 if is_editline:
139 # An add_history() call seems to be required for get_history_
140 # item() to register items from the file
141 readline.add_history("dummy")
142 self.assertEqual(readline.get_history_item(1), "entrée 1")
143 self.assertEqual(readline.get_history_item(2), "entrée 22")
144
145 def test_write_read_limited_history(self):
146 previous_length = readline.get_history_length()
147 self.addCleanup(readline.set_history_length, previous_length)
148
149 readline.clear_history()
150 readline.add_history("first line")
151 readline.add_history("second line")
152 readline.add_history("third line")
153
154 readline.set_history_length(2)
155 self.assertEqual(readline.get_history_length(), 2)
156 readline.write_history_file(TESTFN)
157 self.addCleanup(os.remove, TESTFN)
158
159 readline.clear_history()
160 self.assertEqual(readline.get_current_history_length(), 0)
161 self.assertEqual(readline.get_history_length(), 2)
162
163 readline.read_history_file(TESTFN)
164 self.assertEqual(readline.get_history_item(1), "second line")
165 self.assertEqual(readline.get_history_item(2), "third line")
166 self.assertEqual(readline.get_history_item(3), None)
167
168 # Readline seems to report an additional history element.
169 self.assertIn(readline.get_current_history_length(), (2, 3))
170
171
172 class TestReadline(unittest.TestCase):
173
174 @unittest.skipIf(readline._READLINE_VERSION < 0x0601 and not is_editline,
175 "not supported in this library version")
176 def test_init(self):
177 # Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not
178 # written into stdout when the readline module is imported and stdout
179 # is redirected to a pipe.
180 rc, stdout, stderr = assert_python_ok('-c', 'import readline',
181 TERM='xterm-256color')
182 self.assertEqual(stdout, b'')
183
184 def test_backend(self):
185 self.assertIn(readline.backend, ("readline", "editline"))
186
187 auto_history_script = """\
188 import readline
189 readline.set_auto_history({})
190 input()
191 print("History length:", readline.get_current_history_length())
192 """
193
194 def test_auto_history_enabled(self):
195 output = run_pty(self.auto_history_script.format(True))
196 # bpo-44949: Sometimes, the newline character is not written at the
197 # end, so don't expect it in the output.
198 self.assertIn(b"History length: 1", output)
199
200 def test_auto_history_disabled(self):
201 output = run_pty(self.auto_history_script.format(False))
202 # bpo-44949: Sometimes, the newline character is not written at the
203 # end, so don't expect it in the output.
204 self.assertIn(b"History length: 0", output)
205
206 def test_set_complete_delims(self):
207 script = textwrap.dedent("""
208 import readline
209 def complete(text, state):
210 if state == 0 and text == "$":
211 return "$complete"
212 return None
213 if readline.backend == "editline":
214 readline.parse_and_bind(r'bind "\\t" rl_complete')
215 else:
216 readline.parse_and_bind(r'"\\t": complete')
217 readline.set_completer_delims(" \\t\\n")
218 readline.set_completer(complete)
219 print(input())
220 """)
221
222 output = run_pty(script, input=b"$\t\n")
223 self.assertIn(b"$complete", output)
224
225 def test_nonascii(self):
226 loc = locale.setlocale(locale.LC_CTYPE, None)
227 if loc in ('C', 'POSIX'):
228 # bpo-29240: On FreeBSD, if the LC_CTYPE locale is C or POSIX,
229 # writing and reading non-ASCII bytes into/from a TTY works, but
230 # readline or ncurses ignores non-ASCII bytes on read.
231 self.skipTest(f"the LC_CTYPE locale is {loc!r}")
232 if sys.flags.utf8_mode:
233 encoding = locale.getencoding()
234 encoding = codecs.lookup(encoding).name # normalize the name
235 if encoding != "utf-8":
236 # gh-133711: The Python UTF-8 Mode ignores the LC_CTYPE locale
237 # and always use the UTF-8 encoding.
238 self.skipTest(f"the LC_CTYPE encoding is {encoding!r}")
239
240 try:
241 readline.add_history("\xEB\xEF")
242 except UnicodeEncodeError as err:
243 self.skipTest("Locale cannot encode test data: " + format(err))
244
245 script = r"""import readline
246
247 is_editline = readline.backend == "editline"
248 inserted = "[\xEFnserted]"
249 macro = "|t\xEB[after]"
250 set_pre_input_hook = getattr(readline, "set_pre_input_hook", None)
251 if is_editline or not set_pre_input_hook:
252 # The insert_line() call via pre_input_hook() does nothing with Editline,
253 # so include the extra text that would have been inserted here
254 macro = inserted + macro
255
256 if is_editline:
257 readline.parse_and_bind(r'bind ^B ed-prev-char')
258 readline.parse_and_bind(r'bind "\t" rl_complete')
259 readline.parse_and_bind(r'bind -s ^A "{}"'.format(macro))
260 else:
261 readline.parse_and_bind(r'Control-b: backward-char')
262 readline.parse_and_bind(r'"\t": complete')
263 readline.parse_and_bind(r'set disable-completion off')
264 readline.parse_and_bind(r'set show-all-if-ambiguous off')
265 readline.parse_and_bind(r'set show-all-if-unmodified off')
266 readline.parse_and_bind(r'Control-a: "{}"'.format(macro))
267
268 def pre_input_hook():
269 readline.insert_text(inserted)
270 readline.redisplay()
271 if set_pre_input_hook:
272 set_pre_input_hook(pre_input_hook)
273
274 def completer(text, state):
275 if text == "t\xEB":
276 if state == 0:
277 print("text", ascii(text))
278 print("line", ascii(readline.get_line_buffer()))
279 print("indexes", readline.get_begidx(), readline.get_endidx())
280 return "t\xEBnt"
281 if state == 1:
282 return "t\xEBxt"
283 if text == "t\xEBx" and state == 0:
284 return "t\xEBxt"
285 return None
286 readline.set_completer(completer)
287
288 def display(substitution, matches, longest_match_length):
289 print("substitution", ascii(substitution))
290 print("matches", ascii(matches))
291 readline.set_completion_display_matches_hook(display)
292
293 print("result", ascii(input()))
294 print("history", ascii(readline.get_history_item(1)))
295 """
296
297 input = b"\x01" # Ctrl-A, expands to "|t\xEB[after]"
298 input += b"\x02" * len("[after]") # Move cursor back
299 input += b"\t\t" # Display possible completions
300 input += b"x\t" # Complete "t\xEBx" -> "t\xEBxt"
301 input += b"\r"
302 output = run_pty(script, input)
303 self.assertIn(b"text 't\\xeb'\r\n", output)
304 self.assertIn(b"line '[\\xefnserted]|t\\xeb[after]'\r\n", output)
305 if sys.platform == "darwin" or not is_editline:
306 self.assertIn(b"indexes 11 13\r\n", output)
307 # Non-macOS libedit does not handle non-ASCII bytes
308 # the same way and generates character indices
309 # rather than byte indices via get_begidx() and
310 # get_endidx(). Ex: libedit2 3.1-20191231-2 on Debian
311 # winds up with "indexes 10 12". Stemming from the
312 # start and end values calls back into readline.c's
313 # rl_attempted_completion_function = flex_complete with:
314 # (11, 13) instead of libreadline's (12, 15).
315
316 if not is_editline and hasattr(readline, "set_pre_input_hook"):
317 self.assertIn(b"substitution 't\\xeb'\r\n", output)
318 self.assertIn(b"matches ['t\\xebnt', 't\\xebxt']\r\n", output)
319 expected = br"'[\xefnserted]|t\xebxt[after]'"
320 self.assertIn(b"result " + expected + b"\r\n", output)
321 # bpo-45195: Sometimes, the newline character is not written at the
322 # end, so don't expect it in the output.
323 self.assertIn(b"history " + expected, output)
324
325 # We have 2 reasons to skip this test:
326 # - readline: history size was added in 6.0
327 # See https://cnswww.cns.cwru.edu/php/chet/readline/CHANGES
328 # - editline: history size is broken on OS X 10.11.6.
329 # Newer versions were not tested yet.
330 @unittest.skipIf(readline._READLINE_VERSION < 0x600,
331 "this readline version does not support history-size")
332 @unittest.skipIf(is_editline,
333 "editline history size configuration is broken")
334 def test_history_size(self):
335 history_size = 10
336 with temp_dir() as test_dir:
337 inputrc = os.path.join(test_dir, "inputrc")
338 with open(inputrc, "wb") as f:
339 f.write(b"set history-size %d\n" % history_size)
340
341 history_file = os.path.join(test_dir, "history")
342 with open(history_file, "wb") as f:
343 # history_size * 2 items crashes readline
344 data = b"".join(b"item %d\n" % i
345 for i in range(history_size * 2))
346 f.write(data)
347
348 script = """
349 import os
350 import readline
351
352 history_file = os.environ["HISTORY_FILE"]
353 readline.read_history_file(history_file)
354 input()
355 readline.write_history_file(history_file)
356 """
357
358 env = dict(os.environ)
359 env["INPUTRC"] = inputrc
360 env["HISTORY_FILE"] = history_file
361
362 run_pty(script, input=b"last input\r", env=env)
363
364 with open(history_file, "rb") as f:
365 lines = f.readlines()
366 self.assertEqual(len(lines), history_size)
367 self.assertEqual(lines[-1].strip(), b"last input")
368
369 @requires_working_threading()
370 def test_gh123321_threadsafe(self):
371 """gh-123321: readline should be thread-safe and not crash"""
372 script = textwrap.dedent(r"""
373 import threading
374 from test.support.threading_helper import join_thread
375
376 def func():
377 input()
378
379 thread1 = threading.Thread(target=func)
380 thread2 = threading.Thread(target=func)
381 thread1.start()
382 thread2.start()
383 join_thread(thread1)
384 join_thread(thread2)
385 print("done")
386 """)
387
388 output = run_pty(script, input=b"input1\rinput2\r")
389
390 self.assertIn(b"done", output)
391
392
393 def test_write_read_limited_history(self):
394 previous_length = readline.get_history_length()
395 self.addCleanup(readline.set_history_length, previous_length)
396
397 readline.add_history("first line")
398 readline.add_history("second line")
399 readline.add_history("third line")
400
401 readline.set_history_length(2)
402 self.assertEqual(readline.get_history_length(), 2)
403 readline.write_history_file(TESTFN)
404 self.addCleanup(os.remove, TESTFN)
405
406 readline.read_history_file(TESTFN)
407 # Without clear_history() there's no good way to test if
408 # the correct entries are present (we're combining history limiting and
409 # possible deduplication with arbitrary previous content).
410 # So, we've only tested that the read did not fail.
411 # See TestHistoryManipulation for the full test.
412
413
414 if __name__ == "__main__":
415 unittest.main()