Debian Codegraph @

Lib/test/test_pyrepl/test_unix_console.py

raw
1 import errno
2 import itertools
3 import os
4 import signal
5 import subprocess
6 import sys
7 import threading
8 import unittest
9 from functools import partial
10 from test import support
11 from test.support import os_helper
12 from test.support import script_helper, threading_helper
13
14 from unittest import TestCase
15 from unittest.mock import MagicMock, call, patch, ANY, Mock
16
17 from .support import handle_all_events, code_to_events, reader_no_colors
18
19 try:
20 from _pyrepl.console import Event
21 from _pyrepl.unix_console import UnixConsole
22 except ImportError:
23 pass
24
25
26 def unix_console(events, **kwargs):
27 console = UnixConsole()
28 console.get_event = MagicMock(side_effect=events)
29
30 height = kwargs.get("height", 25)
31 width = kwargs.get("width", 80)
32 console.getheightwidth = MagicMock(side_effect=lambda: (height, width))
33
34 console.prepare()
35 for key, val in kwargs.items():
36 setattr(console, key, val)
37 return console
38
39
40 handle_events_unix_console = partial(
41 handle_all_events,
42 prepare_console=partial(unix_console),
43 )
44 handle_events_narrow_unix_console = partial(
45 handle_all_events,
46 prepare_console=partial(unix_console, width=5),
47 )
48 handle_events_short_unix_console = partial(
49 handle_all_events,
50 prepare_console=partial(unix_console, height=1),
51 )
52 handle_events_unix_console_height_3 = partial(
53 handle_all_events, prepare_console=partial(unix_console, height=3)
54 )
55
56
57 TERM_CAPABILITIES = {
58 "bel": b"\x07",
59 "civis": b"\x1b[?25l",
60 "clear": b"\x1b[H\x1b[2J",
61 "cnorm": b"\x1b[?12l\x1b[?25h",
62 "cub": b"\x1b[%p1%dD",
63 "cub1": b"\x08",
64 "cud": b"\x1b[%p1%dB",
65 "cud1": b"\n",
66 "cuf": b"\x1b[%p1%dC",
67 "cuf1": b"\x1b[C",
68 "cup": b"\x1b[%i%p1%d;%p2%dH",
69 "cuu": b"\x1b[%p1%dA",
70 "cuu1": b"\x1b[A",
71 "dch1": b"\x1b[P",
72 "dch": b"\x1b[%p1%dP",
73 "el": b"\x1b[K",
74 "hpa": b"\x1b[%i%p1%dG",
75 "ich": b"\x1b[%p1%d@",
76 "ich1": None,
77 "ind": b"\n",
78 "pad": None,
79 "ri": b"\x1bM",
80 "rmkx": b"\x1b[?1l\x1b>",
81 "smkx": b"\x1b[?1h\x1b=",
82 }
83
84
85 @unittest.skipIf(sys.platform == "win32", "No Unix event queue on Windows")
86 @patch("_pyrepl.curses.tigetstr", lambda s: TERM_CAPABILITIES.get(s))
87 @patch(
88 "_pyrepl.curses.tparm",
89 lambda s, *args: s + b":" + b",".join(str(i).encode() for i in args),
90 )
91 @patch("_pyrepl.curses.setupterm", lambda a, b: None)
92 @patch(
93 "termios.tcgetattr",
94 lambda _: [
95 27394,
96 3,
97 19200,
98 536872399,
99 38400,
100 38400,
101 [
102 b"\x04",
103 b"\xff",
104 b"\xff",
105 b"\x7f",
106 b"\x17",
107 b"\x15",
108 b"\x12",
109 b"\x00",
110 b"\x03",
111 b"\x1c",
112 b"\x1a",
113 b"\x19",
114 b"\x11",
115 b"\x13",
116 b"\x16",
117 b"\x0f",
118 b"\x01",
119 b"\x00",
120 b"\x14",
121 b"\x00",
122 ],
123 ],
124 )
125 @patch("termios.tcsetattr", lambda a, b, c: None)
126 @patch("os.write")
127 class TestConsole(TestCase):
128 def test_no_newline(self, _os_write):
129 code = "1"
130 events = code_to_events(code)
131 _, con = handle_events_unix_console(events)
132 self.assertNotIn(call(ANY, b'\n'), _os_write.mock_calls)
133 con.restore()
134
135 def test_newline(self, _os_write):
136 code = "\n"
137 events = code_to_events(code)
138 _, con = handle_events_unix_console(events)
139 _os_write.assert_any_call(ANY, b"\n")
140 con.restore()
141
142 def test_simple_addition(self, _os_write):
143 code = "12+34"
144 events = code_to_events(code)
145 _, con = handle_events_unix_console(events)
146 _os_write.assert_any_call(ANY, b"1")
147 _os_write.assert_any_call(ANY, b"2")
148 _os_write.assert_any_call(ANY, b"+")
149 _os_write.assert_any_call(ANY, b"3")
150 _os_write.assert_any_call(ANY, b"4")
151 con.restore()
152
153 def test_wrap(self, _os_write):
154 code = "12+34"
155 events = code_to_events(code)
156 _, con = handle_events_narrow_unix_console(events)
157 _os_write.assert_any_call(ANY, b"1")
158 _os_write.assert_any_call(ANY, b"2")
159 _os_write.assert_any_call(ANY, b"+")
160 _os_write.assert_any_call(ANY, b"3")
161 _os_write.assert_any_call(ANY, b"\\")
162 _os_write.assert_any_call(ANY, b"\n")
163 _os_write.assert_any_call(ANY, b"4")
164 con.restore()
165
166 def test_cursor_left(self, _os_write):
167 code = "1"
168 events = itertools.chain(
169 code_to_events(code),
170 [Event(evt="key", data="left", raw=bytearray(b"\x1bOD"))],
171 )
172 _, con = handle_events_unix_console(events)
173 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["cub"] + b":1")
174 con.restore()
175
176 def test_cursor_left_right(self, _os_write):
177 code = "1"
178 events = itertools.chain(
179 code_to_events(code),
180 [
181 Event(evt="key", data="left", raw=bytearray(b"\x1bOD")),
182 Event(evt="key", data="right", raw=bytearray(b"\x1bOC")),
183 ],
184 )
185 _, con = handle_events_unix_console(events)
186 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["cub"] + b":1")
187 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["cuf"] + b":1")
188 con.restore()
189
190 def test_cursor_up(self, _os_write):
191 code = "1\n2+3"
192 events = itertools.chain(
193 code_to_events(code),
194 [Event(evt="key", data="up", raw=bytearray(b"\x1bOA"))],
195 )
196 _, con = handle_events_unix_console(events)
197 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["cuu"] + b":1")
198 con.restore()
199
200 def test_cursor_up_down(self, _os_write):
201 code = "1\n2+3"
202 events = itertools.chain(
203 code_to_events(code),
204 [
205 Event(evt="key", data="up", raw=bytearray(b"\x1bOA")),
206 Event(evt="key", data="down", raw=bytearray(b"\x1bOB")),
207 ],
208 )
209 _, con = handle_events_unix_console(events)
210 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["cuu"] + b":1")
211 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["cud"] + b":1")
212 con.restore()
213
214 def test_cursor_back_write(self, _os_write):
215 events = itertools.chain(
216 code_to_events("1"),
217 [Event(evt="key", data="left", raw=bytearray(b"\x1bOD"))],
218 code_to_events("2"),
219 )
220 _, con = handle_events_unix_console(events)
221 _os_write.assert_any_call(ANY, b"1")
222 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["cub"] + b":1")
223 _os_write.assert_any_call(ANY, b"2")
224 con.restore()
225
226 def test_multiline_function_move_up_short_terminal(self, _os_write):
227 # fmt: off
228 code = (
229 "def f():\n"
230 " foo"
231 )
232 # fmt: on
233
234 events = itertools.chain(
235 code_to_events(code),
236 [
237 Event(evt="key", data="up", raw=bytearray(b"\x1bOA")),
238 Event(evt="scroll", data=None),
239 ],
240 )
241 _, con = handle_events_short_unix_console(events)
242 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["ri"] + b":")
243 con.restore()
244
245 def test_multiline_function_move_up_down_short_terminal(self, _os_write):
246 # fmt: off
247 code = (
248 "def f():\n"
249 " foo"
250 )
251 # fmt: on
252
253 events = itertools.chain(
254 code_to_events(code),
255 [
256 Event(evt="key", data="up", raw=bytearray(b"\x1bOA")),
257 Event(evt="scroll", data=None),
258 Event(evt="key", data="down", raw=bytearray(b"\x1bOB")),
259 Event(evt="scroll", data=None),
260 ],
261 )
262 _, con = handle_events_short_unix_console(events)
263 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["ri"] + b":")
264 _os_write.assert_any_call(ANY, TERM_CAPABILITIES["ind"] + b":")
265 con.restore()
266
267 def test_resize_bigger_on_multiline_function(self, _os_write):
268 # fmt: off
269 code = (
270 "def f():\n"
271 " foo"
272 )
273 # fmt: on
274
275 events = itertools.chain(code_to_events(code))
276 reader, console = handle_events_short_unix_console(
277 events, prepare_reader=reader_no_colors
278 )
279
280 console.height = 2
281 console.getheightwidth = MagicMock(lambda _: (2, 80))
282
283 def same_reader(_):
284 return reader
285
286 def same_console(events):
287 console.get_event = MagicMock(side_effect=events)
288 return console
289
290 _, con = handle_all_events(
291 [Event(evt="resize", data=None)],
292 prepare_reader=same_reader,
293 prepare_console=same_console,
294 )
295 _os_write.assert_has_calls(
296 [
297 call(ANY, TERM_CAPABILITIES["ri"] + b":"),
298 call(ANY, TERM_CAPABILITIES["cup"] + b":0,0"),
299 call(ANY, b"def f():"),
300 ]
301 )
302 console.restore()
303 con.restore()
304
305 def test_resize_smaller_on_multiline_function(self, _os_write):
306 # fmt: off
307 code = (
308 "def f():\n"
309 " foo"
310 )
311 # fmt: on
312
313 events = itertools.chain(code_to_events(code))
314 reader, console = handle_events_unix_console_height_3(events)
315
316 console.height = 1
317 console.getheightwidth = MagicMock(lambda _: (1, 80))
318
319 def same_reader(_):
320 return reader
321
322 def same_console(events):
323 console.get_event = MagicMock(side_effect=events)
324 return console
325
326 _, con = handle_all_events(
327 [Event(evt="resize", data=None)],
328 prepare_reader=same_reader,
329 prepare_console=same_console,
330 )
331 _os_write.assert_has_calls(
332 [
333 call(ANY, TERM_CAPABILITIES["ind"] + b":"),
334 call(ANY, TERM_CAPABILITIES["cup"] + b":0,0"),
335 call(ANY, b" foo"),
336 ]
337 )
338 console.restore()
339 con.restore()
340
341 def test_getheightwidth_with_invalid_environ(self, _os_write):
342 # gh-128636
343 console = UnixConsole()
344 with os_helper.EnvironmentVarGuard() as env:
345 env["LINES"] = ""
346 self.assertIsInstance(console.getheightwidth(), tuple)
347 env["COLUMNS"] = ""
348 self.assertIsInstance(console.getheightwidth(), tuple)
349 os.environ = []
350 self.assertIsInstance(console.getheightwidth(), tuple)
351
352 @unittest.skipUnless(sys.platform == "darwin", "requires macOS")
353 def test_restore_with_invalid_environ_on_macos(self, _os_write):
354 # gh-128636 for macOS
355 console = UnixConsole(term="xterm")
356 with os_helper.EnvironmentVarGuard():
357 os.environ = []
358 console.prepare() # needed to call restore()
359 console.restore() # this should succeed
360
361 @threading_helper.reap_threads
362 @threading_helper.requires_working_threading()
363 def test_restore_in_thread(self, _os_write):
364 # gh-139391: ensure that console.restore() silently suppresses
365 # exceptions when calling signal.signal() from a non-main thread.
366 console = unix_console([])
367 console.old_sigwinch = signal.SIG_DFL
368 thread = threading.Thread(target=console.restore)
369 thread.start()
370 thread.join() # this should not raise
371
372
373 @unittest.skipIf(sys.platform == "win32", "No Unix console on Windows")
374 class TestUnixConsoleEIOHandling(TestCase):
375
376 @patch('_pyrepl.unix_console.tcsetattr')
377 @patch('_pyrepl.unix_console.tcgetattr')
378 def test_eio_error_handling_in_restore(self, mock_tcgetattr, mock_tcsetattr):
379
380 import termios
381 mock_termios = Mock()
382 mock_termios.iflag = 0
383 mock_termios.oflag = 0
384 mock_termios.cflag = 0
385 mock_termios.lflag = 0
386 mock_termios.cc = [0] * 32
387 mock_termios.copy.return_value = mock_termios
388 mock_tcgetattr.return_value = mock_termios
389
390 console = UnixConsole(term="xterm")
391 console.prepare()
392
393 mock_tcsetattr.side_effect = termios.error(errno.EIO, "Input/output error")
394
395 # EIO error should be handled gracefully in restore()
396 console.restore()
397
398 @unittest.skipUnless(sys.platform == "linux", "Only valid on Linux")
399 def test_repl_eio(self):
400 # Use the pty-based approach to simulate EIO error
401 script_path = os.path.join(os.path.dirname(__file__), "eio_test_script.py")
402
403 proc = script_helper.spawn_python(
404 "-S", script_path,
405 stderr=subprocess.PIPE,
406 text=True
407 )
408
409 ready_line = proc.stdout.readline().strip()
410 if ready_line != "READY" or proc.poll() is not None:
411 self.fail("Child process failed to start properly")
412
413 os.kill(proc.pid, signal.SIGUSR1)
414 # sleep for pty to settle
415 _, err = proc.communicate(timeout=support.LONG_TIMEOUT)
416 self.assertEqual(
417 proc.returncode,
418 1,
419 f"Expected EIO/ENXIO error, got return code {proc.returncode}",
420 )
421 self.assertTrue(
422 (
423 "Got EIO:" in err
424 or "Got ENXIO:" in err
425 ),
426 f"Expected EIO/ENXIO error message in stderr: {err}",
427 )