Debian Codegraph @

Lib/test/test_pyrepl/test_windows_console.py

raw
1 import sys
2 import unittest
3
4 if sys.platform != "win32":
5 raise unittest.SkipTest("test only relevant on win32")
6
7
8 import itertools
9 from functools import partial
10 from typing import Iterable
11 from unittest import TestCase
12 from unittest.mock import MagicMock, call
13
14 from .support import handle_all_events, code_to_events
15
16 try:
17 from _pyrepl.console import Event, Console
18 from _pyrepl.windows_console import (
19 WindowsConsole,
20 MOVE_LEFT,
21 MOVE_RIGHT,
22 MOVE_UP,
23 MOVE_DOWN,
24 ERASE_IN_LINE,
25 )
26 import _pyrepl.windows_console as wc
27 except ImportError:
28 pass
29
30
31 class WindowsConsoleTests(TestCase):
32 def console(self, events, **kwargs) -> Console:
33 console = WindowsConsole()
34 console.get_event = MagicMock(side_effect=events)
35 console._scroll = MagicMock()
36 console._hide_cursor = MagicMock()
37 console._show_cursor = MagicMock()
38 console._getscrollbacksize = MagicMock(42)
39 console.out = MagicMock()
40
41 height = kwargs.get("height", 25)
42 width = kwargs.get("width", 80)
43 console.getheightwidth = MagicMock(side_effect=lambda: (height, width))
44
45 console.prepare()
46 for key, val in kwargs.items():
47 setattr(console, key, val)
48 return console
49
50 def handle_events(self, events: Iterable[Event], **kwargs):
51 return handle_all_events(events, partial(self.console, **kwargs))
52
53 def handle_events_narrow(self, events):
54 return self.handle_events(events, width=5)
55
56 def handle_events_short(self, events):
57 return self.handle_events(events, height=1)
58
59 def handle_events_height_3(self, events):
60 return self.handle_events(events, height=3)
61
62 def test_no_newline(self):
63 code = "1"
64 events = code_to_events(code)
65 _, con = self.handle_events(events)
66 self.assertNotIn(call(b'\n'), con.out.write.mock_calls)
67 con.restore()
68
69 def test_newline(self):
70 code = "\n"
71 events = code_to_events(code)
72 _, con = self.handle_events(events)
73 con.out.write.assert_any_call(b"\n")
74 con.restore()
75
76 def test_simple_addition(self):
77 code = "12+34"
78 events = code_to_events(code)
79 _, con = self.handle_events(events)
80 con.out.write.assert_any_call(b"1")
81 con.out.write.assert_any_call(b"2")
82 con.out.write.assert_any_call(b"+")
83 con.out.write.assert_any_call(b"3")
84 con.out.write.assert_any_call(b"4")
85 con.restore()
86
87 def test_wrap(self):
88 code = "12+34"
89 events = code_to_events(code)
90 _, con = self.handle_events_narrow(events)
91 con.out.write.assert_any_call(b"1")
92 con.out.write.assert_any_call(b"2")
93 con.out.write.assert_any_call(b"+")
94 con.out.write.assert_any_call(b"3")
95 con.out.write.assert_any_call(b"\\")
96 con.out.write.assert_any_call(b"\n")
97 con.out.write.assert_any_call(b"4")
98 con.restore()
99
100 def test_resize_wider(self):
101 code = "1234567890"
102 events = code_to_events(code)
103 reader, console = self.handle_events_narrow(events)
104
105 console.height = 20
106 console.width = 80
107 console.getheightwidth = MagicMock(lambda _: (20, 80))
108
109 def same_reader(_):
110 return reader
111
112 def same_console(events):
113 console.get_event = MagicMock(side_effect=events)
114 return console
115
116 _, con = handle_all_events(
117 [Event(evt="resize", data=None)],
118 prepare_reader=same_reader,
119 prepare_console=same_console,
120 )
121
122 con.out.write.assert_any_call(self.move_right(2))
123 con.out.write.assert_any_call(self.move_up(2))
124 con.out.write.assert_any_call(b"567890")
125
126 con.restore()
127
128 def test_resize_narrower(self):
129 code = "1234567890"
130 events = code_to_events(code)
131 reader, console = self.handle_events(events)
132
133 console.height = 20
134 console.width = 4
135 console.getheightwidth = MagicMock(lambda _: (20, 4))
136
137 def same_reader(_):
138 return reader
139
140 def same_console(events):
141 console.get_event = MagicMock(side_effect=events)
142 return console
143
144 _, con = handle_all_events(
145 [Event(evt="resize", data=None)],
146 prepare_reader=same_reader,
147 prepare_console=same_console,
148 )
149
150 con.out.write.assert_any_call(b"456\\")
151 con.out.write.assert_any_call(b"789\\")
152
153 con.restore()
154
155 def test_cursor_left(self):
156 code = "1"
157 events = itertools.chain(
158 code_to_events(code),
159 [Event(evt="key", data="left", raw=bytearray(b"\x1bOD"))],
160 )
161 _, con = self.handle_events(events)
162 con.out.write.assert_any_call(self.move_left())
163 con.restore()
164
165 def test_cursor_left_right(self):
166 code = "1"
167 events = itertools.chain(
168 code_to_events(code),
169 [
170 Event(evt="key", data="left", raw=bytearray(b"\x1bOD")),
171 Event(evt="key", data="right", raw=bytearray(b"\x1bOC")),
172 ],
173 )
174 _, con = self.handle_events(events)
175 con.out.write.assert_any_call(self.move_left())
176 con.out.write.assert_any_call(self.move_right())
177 con.restore()
178
179 def test_cursor_up(self):
180 code = "1\n2+3"
181 events = itertools.chain(
182 code_to_events(code),
183 [Event(evt="key", data="up", raw=bytearray(b"\x1bOA"))],
184 )
185 _, con = self.handle_events(events)
186 con.out.write.assert_any_call(self.move_up())
187 con.restore()
188
189 def test_cursor_up_down(self):
190 code = "1\n2+3"
191 events = itertools.chain(
192 code_to_events(code),
193 [
194 Event(evt="key", data="up", raw=bytearray(b"\x1bOA")),
195 Event(evt="key", data="down", raw=bytearray(b"\x1bOB")),
196 ],
197 )
198 _, con = self.handle_events(events)
199 con.out.write.assert_any_call(self.move_up())
200 con.out.write.assert_any_call(self.move_down())
201 con.restore()
202
203 def test_cursor_back_write(self):
204 events = itertools.chain(
205 code_to_events("1"),
206 [Event(evt="key", data="left", raw=bytearray(b"\x1bOD"))],
207 code_to_events("2"),
208 )
209 _, con = self.handle_events(events)
210 con.out.write.assert_any_call(b"1")
211 con.out.write.assert_any_call(self.move_left())
212 con.out.write.assert_any_call(b"21")
213 con.restore()
214
215 def test_multiline_function_move_up_short_terminal(self):
216 # fmt: off
217 code = (
218 "def f():\n"
219 " foo"
220 )
221 # fmt: on
222
223 events = itertools.chain(
224 code_to_events(code),
225 [
226 Event(evt="key", data="up", raw=bytearray(b"\x1bOA")),
227 Event(evt="scroll", data=None),
228 ],
229 )
230 _, con = self.handle_events_short(events)
231 con.out.write.assert_any_call(self.move_left(5))
232 con.out.write.assert_any_call(self.move_up())
233 con.restore()
234
235 def test_multiline_function_move_up_down_short_terminal(self):
236 # fmt: off
237 code = (
238 "def f():\n"
239 " foo"
240 )
241 # fmt: on
242
243 events = itertools.chain(
244 code_to_events(code),
245 [
246 Event(evt="key", data="up", raw=bytearray(b"\x1bOA")),
247 Event(evt="scroll", data=None),
248 Event(evt="key", data="down", raw=bytearray(b"\x1bOB")),
249 Event(evt="scroll", data=None),
250 ],
251 )
252 _, con = self.handle_events_short(events)
253 con.out.write.assert_any_call(self.move_left(8))
254 con.out.write.assert_any_call(self.erase_in_line())
255 con.restore()
256
257 def test_resize_bigger_on_multiline_function(self):
258 # fmt: off
259 code = (
260 "def f():\n"
261 " foo"
262 )
263 # fmt: on
264
265 events = itertools.chain(code_to_events(code))
266 reader, console = self.handle_events_short(events)
267
268 console.height = 2
269 console.getheightwidth = MagicMock(lambda _: (2, 80))
270
271 def same_reader(_):
272 return reader
273
274 def same_console(events):
275 console.get_event = MagicMock(side_effect=events)
276 return console
277
278 _, con = handle_all_events(
279 [Event(evt="resize", data=None)],
280 prepare_reader=same_reader,
281 prepare_console=same_console,
282 )
283 con.out.write.assert_has_calls(
284 [
285 call(self.move_left(5)),
286 call(self.move_up()),
287 call(b"def f():"),
288 call(self.move_left(3)),
289 call(self.move_down()),
290 ]
291 )
292 console.restore()
293 con.restore()
294
295 def test_resize_smaller_on_multiline_function(self):
296 # fmt: off
297 code = (
298 "def f():\n"
299 " foo"
300 )
301 # fmt: on
302
303 events = itertools.chain(code_to_events(code))
304 reader, console = self.handle_events_height_3(events)
305
306 console.height = 1
307 console.getheightwidth = MagicMock(lambda _: (1, 80))
308
309 def same_reader(_):
310 return reader
311
312 def same_console(events):
313 console.get_event = MagicMock(side_effect=events)
314 return console
315
316 _, con = handle_all_events(
317 [Event(evt="resize", data=None)],
318 prepare_reader=same_reader,
319 prepare_console=same_console,
320 )
321 con.out.write.assert_has_calls(
322 [
323 call(self.move_left(5)),
324 call(self.move_up()),
325 call(self.erase_in_line()),
326 call(b" foo"),
327 ]
328 )
329 console.restore()
330 con.restore()
331
332 def move_up(self, lines=1):
333 return MOVE_UP.format(lines).encode("utf8")
334
335 def move_down(self, lines=1):
336 return MOVE_DOWN.format(lines).encode("utf8")
337
338 def move_left(self, cols=1):
339 return MOVE_LEFT.format(cols).encode("utf8")
340
341 def move_right(self, cols=1):
342 return MOVE_RIGHT.format(cols).encode("utf8")
343
344 def erase_in_line(self):
345 return ERASE_IN_LINE.encode("utf8")
346
347 def test_multiline_ctrl_z(self):
348 # see gh-126332
349 code = "abcdefghi"
350
351 events = itertools.chain(
352 code_to_events(code),
353 [
354 Event(evt="key", data='\x1a', raw=bytearray(b'\x1a')),
355 Event(evt="key", data='\x1a', raw=bytearray(b'\x1a')),
356 ],
357 )
358 reader, con = self.handle_events_narrow(events)
359 self.assertEqual(reader.cxy, (2, 3))
360 con.restore()
361
362
363 class WindowsConsoleGetEventTests(TestCase):
364 # Virtual-Key Codes: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
365 VK_BACK = 0x08
366 VK_RETURN = 0x0D
367 VK_LEFT = 0x25
368 VK_7 = 0x37
369 VK_M = 0x4D
370 # Used for miscellaneous characters; it can vary by keyboard.
371 # For the US standard keyboard, the '" key.
372 # For the German keyboard, the Ä key.
373 VK_OEM_7 = 0xDE
374
375 # State of control keys: https://learn.microsoft.com/en-us/windows/console/key-event-record-str
376 RIGHT_ALT_PRESSED = 0x0001
377 RIGHT_CTRL_PRESSED = 0x0004
378 LEFT_ALT_PRESSED = 0x0002
379 LEFT_CTRL_PRESSED = 0x0008
380 ENHANCED_KEY = 0x0100
381 SHIFT_PRESSED = 0x0010
382
383
384 def get_event(self, input_records, **kwargs) -> Console:
385 self.console = WindowsConsole(encoding='utf-8')
386 self.mock = MagicMock(side_effect=input_records)
387 self.console._read_input = self.mock
388 self.console._WindowsConsole__vt_support = kwargs.get("vt_support",
389 False)
390 event = self.console.get_event(block=False)
391 return event
392
393 def get_input_record(self, unicode_char, vcode=0, control=0):
394 return wc.INPUT_RECORD(
395 wc.KEY_EVENT,
396 wc.ConsoleEvent(KeyEvent=
397 wc.KeyEvent(
398 bKeyDown=True,
399 wRepeatCount=1,
400 wVirtualKeyCode=vcode,
401 wVirtualScanCode=0, # not used
402 uChar=wc.Char(unicode_char),
403 dwControlKeyState=control
404 )))
405
406 def test_EmptyBuffer(self):
407 self.assertEqual(self.get_event([None]), None)
408 self.assertEqual(self.mock.call_count, 1)
409
410 def test_WINDOW_BUFFER_SIZE_EVENT(self):
411 ir = wc.INPUT_RECORD(
412 wc.WINDOW_BUFFER_SIZE_EVENT,
413 wc.ConsoleEvent(WindowsBufferSizeEvent=
414 wc.WindowsBufferSizeEvent(
415 wc._COORD(0, 0))))
416 self.assertEqual(self.get_event([ir]), Event("resize", ""))
417 self.assertEqual(self.mock.call_count, 1)
418
419 def test_KEY_EVENT_up_ignored(self):
420 ir = wc.INPUT_RECORD(
421 wc.KEY_EVENT,
422 wc.ConsoleEvent(KeyEvent=
423 wc.KeyEvent(bKeyDown=False)))
424 self.assertEqual(self.get_event([ir]), None)
425 self.assertEqual(self.mock.call_count, 1)
426
427 def test_unhandled_events(self):
428 for event in (wc.FOCUS_EVENT, wc.MENU_EVENT, wc.MOUSE_EVENT):
429 ir = wc.INPUT_RECORD(
430 event,
431 # fake data, nothing is read except bKeyDown
432 wc.ConsoleEvent(KeyEvent=
433 wc.KeyEvent(bKeyDown=False)))
434 self.assertEqual(self.get_event([ir]), None)
435 self.assertEqual(self.mock.call_count, 1)
436
437 def test_enter(self):
438 ir = self.get_input_record("\r", self.VK_RETURN)
439 self.assertEqual(self.get_event([ir]), Event("key", "\n"))
440 self.assertEqual(self.mock.call_count, 1)
441
442 def test_backspace(self):
443 ir = self.get_input_record("\x08", self.VK_BACK)
444 self.assertEqual(
445 self.get_event([ir]), Event("key", "backspace"))
446 self.assertEqual(self.mock.call_count, 1)
447
448 def test_m(self):
449 ir = self.get_input_record("m", self.VK_M)
450 self.assertEqual(self.get_event([ir]), Event("key", "m"))
451 self.assertEqual(self.mock.call_count, 1)
452
453 def test_M(self):
454 ir = self.get_input_record("M", self.VK_M, self.SHIFT_PRESSED)
455 self.assertEqual(self.get_event([ir]), Event("key", "M"))
456 self.assertEqual(self.mock.call_count, 1)
457
458 def test_left(self):
459 # VK_LEFT is sent as ENHANCED_KEY
460 ir = self.get_input_record("\x00", self.VK_LEFT, self.ENHANCED_KEY)
461 self.assertEqual(self.get_event([ir]), Event("key", "left"))
462 self.assertEqual(self.mock.call_count, 1)
463
464 def test_left_RIGHT_CTRL_PRESSED(self):
465 ir = self.get_input_record(
466 "\x00", self.VK_LEFT, self.RIGHT_CTRL_PRESSED | self.ENHANCED_KEY)
467 self.assertEqual(
468 self.get_event([ir]), Event("key", "ctrl left"))
469 self.assertEqual(self.mock.call_count, 1)
470
471 def test_left_LEFT_CTRL_PRESSED(self):
472 ir = self.get_input_record(
473 "\x00", self.VK_LEFT, self.LEFT_CTRL_PRESSED | self.ENHANCED_KEY)
474 self.assertEqual(
475 self.get_event([ir]), Event("key", "ctrl left"))
476 self.assertEqual(self.mock.call_count, 1)
477
478 def test_left_RIGHT_ALT_PRESSED(self):
479 ir = self.get_input_record(
480 "\x00", self.VK_LEFT, self.RIGHT_ALT_PRESSED | self.ENHANCED_KEY)
481 self.assertEqual(self.get_event([ir]), Event(evt="key", data="\033"))
482 self.assertEqual(
483 self.console.get_event(), Event("key", "left"))
484 # self.mock is not called again, since the second time we read from the
485 # command queue
486 self.assertEqual(self.mock.call_count, 1)
487
488 def test_left_LEFT_ALT_PRESSED(self):
489 ir = self.get_input_record(
490 "\x00", self.VK_LEFT, self.LEFT_ALT_PRESSED | self.ENHANCED_KEY)
491 self.assertEqual(self.get_event([ir]), Event(evt="key", data="\033"))
492 self.assertEqual(
493 self.console.get_event(), Event("key", "left"))
494 self.assertEqual(self.mock.call_count, 1)
495
496 def test_m_LEFT_ALT_PRESSED_and_LEFT_CTRL_PRESSED(self):
497 # For the shift keys, Windows does not send anything when
498 # ALT and CTRL are both pressed, so let's test with VK_M.
499 # get_event() receives this input, but does not
500 # generate an event.
501 # This is for e.g. an English keyboard layout, for a
502 # German layout this returns `µ`, see test_AltGr_m.
503 ir = self.get_input_record(
504 "\x00", self.VK_M, self.LEFT_ALT_PRESSED | self.LEFT_CTRL_PRESSED)
505 self.assertEqual(self.get_event([ir]), None)
506 self.assertEqual(self.mock.call_count, 1)
507
508 def test_m_LEFT_ALT_PRESSED(self):
509 ir = self.get_input_record(
510 "m", vcode=self.VK_M, control=self.LEFT_ALT_PRESSED)
511 self.assertEqual(self.get_event([ir]), Event(evt="key", data="\033"))
512 self.assertEqual(self.console.get_event(), Event("key", "m"))
513 self.assertEqual(self.mock.call_count, 1)
514
515 def test_m_RIGHT_ALT_PRESSED(self):
516 ir = self.get_input_record(
517 "m", vcode=self.VK_M, control=self.RIGHT_ALT_PRESSED)
518 self.assertEqual(self.get_event([ir]), Event(evt="key", data="\033"))
519 self.assertEqual(self.console.get_event(), Event("key", "m"))
520 self.assertEqual(self.mock.call_count, 1)
521
522 def test_AltGr_7(self):
523 # E.g. on a German keyboard layout, '{' is entered via
524 # AltGr + 7, where AltGr is the right Alt key on the keyboard.
525 # In this case, Windows automatically sets
526 # RIGHT_ALT_PRESSED = 0x0001 + LEFT_CTRL_PRESSED = 0x0008
527 # This can also be entered like
528 # LeftAlt + LeftCtrl + 7 or
529 # LeftAlt + RightCtrl + 7
530 # See https://learn.microsoft.com/en-us/windows/console/key-event-record-str
531 # https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-vkkeyscanw
532 ir = self.get_input_record(
533 "{", vcode=self.VK_7,
534 control=self.RIGHT_ALT_PRESSED | self.LEFT_CTRL_PRESSED)
535 self.assertEqual(self.get_event([ir]), Event("key", "{"))
536 self.assertEqual(self.mock.call_count, 1)
537
538 def test_AltGr_m(self):
539 # E.g. on a German keyboard layout, this yields 'µ'
540 # Let's use LEFT_ALT_PRESSED and RIGHT_CTRL_PRESSED this
541 # time, to cover that, too. See above in test_AltGr_7.
542 ir = self.get_input_record(
543 "µ", vcode=self.VK_M, control=self.LEFT_ALT_PRESSED | self.RIGHT_CTRL_PRESSED)
544 self.assertEqual(self.get_event([ir]), Event("key", "µ"))
545 self.assertEqual(self.mock.call_count, 1)
546
547 def test_umlaut_a_german(self):
548 ir = self.get_input_record("ä", self.VK_OEM_7)
549 self.assertEqual(self.get_event([ir]), Event("key", "ä"))
550 self.assertEqual(self.mock.call_count, 1)
551
552 # virtual terminal tests
553 # Note: wVirtualKeyCode, wVirtualScanCode and dwControlKeyState
554 # are always zero in this case.
555 # "\r" and backspace are handled specially, everything else
556 # is handled in "elif self.__vt_support:" in WindowsConsole.get_event().
557 # Hence, only one regular key ("m") and a terminal sequence
558 # are sufficient to test here, the real tests happen in test_eventqueue
559 # and test_keymap.
560
561 def test_enter_vt(self):
562 ir = self.get_input_record("\r")
563 self.assertEqual(self.get_event([ir], vt_support=True),
564 Event("key", "\n"))
565 self.assertEqual(self.mock.call_count, 1)
566
567 def test_backspace_vt(self):
568 ir = self.get_input_record("\x7f")
569 self.assertEqual(self.get_event([ir], vt_support=True),
570 Event("key", "backspace", b"\x7f"))
571 self.assertEqual(self.mock.call_count, 1)
572
573 def test_up_vt(self):
574 irs = [self.get_input_record(x) for x in "\x1b[A"]
575 self.assertEqual(self.get_event(irs, vt_support=True),
576 Event(evt='key', data='up', raw=bytearray(b'\x1b[A')))
577 self.assertEqual(self.mock.call_count, 3)
578
579 # All tests above assume that there is always keyboard data to read,
580 # because for simplicity we just use
581 # self.console.wait = MagicMock(return_value=True)
582 def test_wait_empty(self):
583 console = WindowsConsole(encoding='utf-8')
584 console.wait_for_event = MagicMock(return_value=True)
585 self.assertTrue(console.event_queue.empty())
586 timeout = 2.0
587 self.assertTrue(console.wait(timeout))
588 self.assertEqual(console.wait_for_event.call_count, 1)
589 self.assertEqual(console.wait_for_event.mock_calls[0], call(timeout))
590
591 timeout = 1.1
592 console.wait_for_event = MagicMock(return_value=False)
593 self.assertFalse(console.wait(timeout))
594 self.assertEqual(console.wait_for_event.call_count, 1)
595 self.assertEqual(console.wait_for_event.mock_calls[0], call(timeout))
596
597 def test_wait_not_empty(self):
598 console = WindowsConsole(encoding='utf-8')
599 console.wait_for_event = MagicMock(return_value=True)
600 console.event_queue.push(b"a")
601 self.assertFalse(console.event_queue.empty())
602 self.assertTrue(console.wait(0.0))
603 self.assertEqual(console.wait_for_event.call_count, 0)
604
605
606 if __name__ == "__main__":
607 unittest.main()