gh-110147: test_msvcrt: run console I/O tests in new processes (#110268)

This commit is contained in:
AN Long 2023-10-06 01:52:26 +08:00 committed by GitHub
parent a13620685f
commit 1f3af03f83
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 107 deletions

View file

@ -1,17 +1,17 @@
import os
import subprocess
import sys
import unittest
from textwrap import dedent
from test.support import os_helper
from test.support import os_helper, requires_resource
from test.support.os_helper import TESTFN, TESTFN_ASCII
if sys.platform != "win32":
raise unittest.SkipTest("windows related tests")
import _winapi
import msvcrt;
from _testconsole import write_input, flush_console_input_buffer
import msvcrt
class TestFileOperations(unittest.TestCase):
@ -61,34 +61,45 @@ c_encoded = b'\x57\x5b' # utf-16-le (which windows internally used) encoded char
class TestConsoleIO(unittest.TestCase):
# CREATE_NEW_CONSOLE creates a "popup" window.
@requires_resource('gui')
def run_in_separated_process(self, code):
# Run test in a seprated process to avoid stdin conflicts.
# See: gh-110147
cmd = [sys.executable, '-c', code]
subprocess.run(cmd, check=True, capture_output=True,
creationflags=subprocess.CREATE_NEW_CONSOLE)
def test_kbhit(self):
h = msvcrt.get_osfhandle(sys.stdin.fileno())
flush_console_input_buffer(h)
self.assertEqual(msvcrt.kbhit(), 0)
code = dedent('''
import msvcrt
assert msvcrt.kbhit() == 0
''')
self.run_in_separated_process(code)
def test_getch(self):
msvcrt.ungetch(b'c')
self.assertEqual(msvcrt.getch(), b'c')
def test_getwch(self):
with open('CONIN$', 'rb', buffering=0) as stdin:
h = msvcrt.get_osfhandle(stdin.fileno())
flush_console_input_buffer(h)
def check_getwch(self, funcname):
code = dedent(f'''
import msvcrt
from _testconsole import write_input
with open("CONIN$", "rb", buffering=0) as stdin:
write_input(stdin, {ascii(c_encoded)})
assert msvcrt.{funcname}() == "{c}"
''')
self.run_in_separated_process(code)
write_input(stdin, c_encoded)
self.assertEqual(msvcrt.getwch(), c)
def test_getwch(self):
self.check_getwch('getwch')
def test_getche(self):
msvcrt.ungetch(b'c')
self.assertEqual(msvcrt.getche(), b'c')
def test_getwche(self):
with open('CONIN$', 'rb', buffering=0) as stdin:
h = msvcrt.get_osfhandle(stdin.fileno())
flush_console_input_buffer(h)
write_input(stdin, c_encoded)
self.assertEqual(msvcrt.getwche(), c)
self.check_getwch('getwche')
def test_putch(self):
msvcrt.putch(b'c')