Skip to content

Commit 16db304

Browse files
committed
Drain both terminals while testing input redirection
1 parent d3049db commit 16db304

1 file changed

Lines changed: 36 additions & 13 deletions

File tree

‎extra_tests/snippets/stdlib_input_readline.py‎

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,41 @@
44
import sys
55

66
if os.name == "posix" and hasattr(os, "openpty"):
7+
import errno
78
import select
89
import subprocess
910
import time
1011

11-
def read_until(fd, marker):
12-
output = bytearray()
12+
def read_until(fd, marker, buffers, closed):
1313
deadline = time.monotonic() + 20
14-
while marker not in output:
14+
while marker not in buffers[fd]:
1515
remaining = deadline - time.monotonic()
16-
assert remaining > 0, (marker, output)
17-
ready, _, _ = select.select([fd], [], [], remaining)
18-
assert ready, (marker, output)
19-
output.extend(os.read(fd, 4096))
20-
return bytes(output)
16+
assert remaining > 0, (marker, buffers)
17+
# Drain both terminals, even while waiting for the other one's
18+
# prompt. On BSD, unread output can block tcsetattr(TCSADRAIN)
19+
# when the first input restores its terminal mode.
20+
ready, _, _ = select.select(
21+
[stream for stream in buffers if stream not in closed],
22+
[],
23+
[],
24+
remaining,
25+
)
26+
assert ready, (marker, buffers)
27+
for stream in ready:
28+
try:
29+
chunk = os.read(stream, 4096)
30+
except OSError as error:
31+
# Linux PTY masters report EIO after their last slave closes.
32+
if error.errno != errno.EIO:
33+
raise
34+
chunk = b""
35+
if chunk:
36+
buffers[stream].extend(chunk)
37+
else:
38+
closed.add(stream)
39+
assert fd not in closed or marker in buffers[fd], (marker, buffers)
40+
end = buffers[fd].index(marker) + len(marker)
41+
del buffers[fd][:end]
2142

2243
def exercise(code, switch_terminal=False, output_terminal=False):
2344
master, slave = os.openpty()
@@ -35,17 +56,19 @@ def exercise(code, switch_terminal=False, output_terminal=False):
3556
)
3657
os.close(slave)
3758
os.close(other_slave)
59+
buffers = {master: bytearray(), other_master: bytearray()}
60+
closed = set()
3861
try:
39-
read_until(master, b"FIRST>")
62+
read_until(master, b"FIRST>", buffers, closed)
4063
os.write(master, b"one\ntwo\n")
4164
if switch_terminal:
42-
read_until(other_master, b"SECOND>")
65+
read_until(other_master, b"SECOND>", buffers, closed)
4366
os.write(other_master, b"fresh\n")
44-
read_until(other_master, b"RESULT=fresh")
67+
read_until(other_master, b"RESULT=fresh", buffers, closed)
4568
elif output_terminal:
46-
read_until(other_master, b"RESULT=two")
69+
read_until(other_master, b"RESULT=two", buffers, closed)
4770
else:
48-
read_until(master, b"RESULT=two")
71+
read_until(master, b"RESULT=two", buffers, closed)
4972
assert process.wait(timeout=20) == 0
5073
finally:
5174
if process.poll() is None:

0 commit comments

Comments
 (0)