Debian Codegraph @

tests/test_stream.py

raw symbols SCIP
1 import os
2 import io
3 import gc
4 import sys
5 import pytest
6 import asyncio
7 from unittest.mock import Mock
8
9 from aioconsole.stream import create_standard_streams, ainput, aprint
10 from aioconsole.stream import is_pipe_transport_compatible, get_standard_streams
11
12
13 @pytest.mark.skipif(sys.platform == "win32", reason="Not supported on windows")
14 @pytest.mark.asyncio
15 async def test_create_standard_stream_with_pipe(is_uvloop):
16 r1, w1 = os.pipe()
17 r2, w2 = os.pipe()
18 stdin = open(r1)
19 stdout = open(w1, "w")
20 stderr = open(w2, "w")
21
22 assert is_pipe_transport_compatible(stdin)
23 assert is_pipe_transport_compatible(stdout)
24 assert is_pipe_transport_compatible(stderr)
25
26 reader, writer1, writer2 = await create_standard_streams(stdin, stdout, stderr)
27
28 writer1.write("a\n")
29 await writer1.drain()
30 data = await reader.readline()
31 assert data == b"a\n"
32
33 writer2.write("b\n")
34 await writer2.drain()
35 assert os.read(r2, 2) == b"b\n"
36
37 # Mock stdout.close() to check if it has been called
38 stdout_actual_close = stdout.close
39 stdout.close = Mock()
40
41 # Close the transport and delete the object
42 writer1.transport.close()
43 del reader, writer1, writer2
44 gc.collect() # Force garbage collection - necessary for pypy
45
46 # Check that the transport has been closed but not stdout
47 assert not stdout.close.called
48
49 # Weirdly enough, uvloop DID close the file descriptor.
50 # Probably because it used the file descriptor directly instead
51 # of the pipe object. However, this should not be an issue since
52 # file descriptors 0, 1, 2 do not seem to be affected by this.
53 if not is_uvloop:
54 stdout_actual_close()
55
56
57 @pytest.mark.asyncio
58 async def test_create_standard_stream_with_non_pipe(monkeypatch):
59 stdin = io.StringIO("a\nb\nc\nd\n")
60 stdout = io.StringIO()
61 stderr = io.StringIO()
62 reader, writer1, writer2 = await create_standard_streams(stdin, stdout, stderr)
63
64 writer1.write("a\n")
65 await writer1.drain()
66 data = await reader.readline()
67 assert data == b"a\n"
68 assert stdout.getvalue() == "a\n"
69
70 writer2.write("b\n")
71 await writer2.drain()
72 data = await reader.readline()
73 assert data == b"b\n"
74 assert stderr.getvalue() == "b\n"
75
76 # Multiple writes
77 writer2.write("c\n")
78 writer2.write("d\n")
79 await asyncio.sleep(0.1)
80 writer2.write("e\n")
81 writer2.close()
82 assert writer2.is_closing()
83 await writer2.wait_closed()
84 assert stderr.getvalue() == "b\nc\nd\ne\n"
85 with pytest.raises(RuntimeError):
86 writer2.write("f\n")
87
88 data = await reader.read(2)
89 assert data == b"c\n"
90
91 assert reader.at_eof() is False
92
93 async for data in reader:
94 assert data == b"d\n"
95
96 assert reader.at_eof() is True
97
98 # Check exception handling in the daemon thread
99
100 class KeyboardInterruptLike(BaseException):
101 pass
102
103 def raise_keyboard_interrupt(*args):
104 raise KeyboardInterruptLike
105
106 def raise_os_error(*args):
107 raise OSError
108
109 monkeypatch.setattr(stdin, "readline", raise_os_error)
110 with pytest.raises(OSError):
111 data = await reader.readline()
112
113 monkeypatch.setattr(stdin, "read", raise_keyboard_interrupt)
114 with pytest.raises(KeyboardInterruptLike):
115 data = await reader.read()
116
117
118 def mock_stdio(monkeypatch, input_text="", disable_stdin=False):
119 monkeypatch.setattr("sys.stdin", None if disable_stdin else io.StringIO(input_text))
120 monkeypatch.setattr("sys.stdout", io.StringIO())
121 monkeypatch.setattr("sys.stderr", io.StringIO())
122
123
124 @pytest.mark.asyncio
125 async def test_ainput_with_standard_stream(monkeypatch):
126 mock_stdio(monkeypatch, "a\nb\n")
127 assert (await ainput()) == "a"
128 assert (await ainput(">>> ")) == "b"
129 assert sys.stdout.getvalue() == ">>> "
130 assert sys.stderr.getvalue() == ""
131
132
133 @pytest.mark.asyncio
134 async def test_aprint_with_standard_stream(monkeypatch):
135 mock_stdio(monkeypatch)
136 await aprint("ab", "cd")
137 assert sys.stdout.getvalue() == "ab cd\n"
138 await aprint("a" * 1024 * 64)
139 assert sys.stdout.getvalue() == "ab cd\n" + "a" * 1024 * 64 + "\n"
140 assert sys.stderr.getvalue() == ""
141
142
143 @pytest.mark.parametrize("flush", [False, True])
144 @pytest.mark.asyncio
145 async def test_aprint_flush_argument(monkeypatch, flush):
146 mock_stdio(monkeypatch)
147 await aprint("a", flush=flush)
148 if not flush:
149 # Might or might not be there yet, depending on internal logic
150 assert sys.stdout.getvalue() in ("", "a\n")
151 await aprint("", end="", flush=True)
152 assert sys.stdout.getvalue() == "a\n"
153
154
155 @pytest.mark.asyncio
156 async def test_read_from_closed_pipe(is_uvloop):
157 if is_uvloop:
158 pytest.skip("This test is flaky with uvloop for some reason.")
159
160 stdin_r, stdin_w = os.pipe()
161 stdout_r, stdout_w = os.pipe()
162 stderr_r, stderr_w = os.pipe()
163
164 stdin = open(stdin_w, "wb")
165 stdin.write(b"hello\n")
166 stdin.close()
167
168 f_stdin = open(stdin_r, "r")
169 f_stdout = open(stdout_w, "w")
170 f_stderr = open(stderr_w, "w")
171
172 reader, writer1, writer2 = await create_standard_streams(
173 f_stdin, f_stdout, f_stderr
174 )
175
176 result = await ainput(">>> ", streams=(reader, writer1))
177 assert result == "hello"
178
179 writer1.close()
180 await writer1.wait_closed()
181 f_stdout.close()
182
183 writer2.close()
184 await writer2.wait_closed()
185 f_stderr.close()
186
187 assert open(stdout_r).read() == ">>> "
188 assert open(stderr_r).read() == ""
189
190
191 @pytest.mark.skipif(sys.platform == "win32", reason="Not supported on windows")
192 @pytest.mark.asyncio
193 async def test_standard_stream_pipe_buffering(is_uvloop):
194 if is_uvloop:
195 pytest.skip("This test is flaky with uvloop for some reason.")
196 r1, w1 = os.pipe()
197 r2, w2 = os.pipe()
198 stdin = open(r1)
199 stdout = open(w1, "w")
200 stderr = open(w2, "w")
201
202 assert is_pipe_transport_compatible(stdin)
203 assert is_pipe_transport_compatible(stdout)
204 assert is_pipe_transport_compatible(stderr)
205
206 reader, writer1, writer2 = await create_standard_streams(stdin, stdout, stderr)
207
208 blob_size = 4 * 1024 * 1024 # 4 MB
209 writer1.write("a\n" + "b" * blob_size + "\n")
210 task = asyncio.ensure_future(writer1.drain())
211 data = await reader.readline()
212 assert data == b"a\n"
213
214 # Check back pressure
215 await asyncio.sleep(0.1)
216 assert not task.done()
217 assert len(reader._buffer) < blob_size
218
219 data = await reader.readline()
220 assert data == b"b" * blob_size + b"\n"
221 await task
222
223
224 @pytest.mark.asyncio
225 async def test_aprint_with_no_stdin(monkeypatch):
226 mock_stdio(monkeypatch, disable_stdin=True)
227 await aprint("test1")
228 assert sys.stdout.getvalue() == "test1\n"
229 assert sys.stderr.getvalue() == ""
230 with pytest.raises(RuntimeError) as ctx:
231 await ainput("test2")
232 assert str(ctx.value) == "ainput(): lost sys.stdin"
233 assert sys.stdout.getvalue() == "test1\ntest2"
234 assert sys.stderr.getvalue() == ""
235 # Test the methods specifically
236 reader, _ = await get_standard_streams()
237 with pytest.raises(RuntimeError) as ctx:
238 await reader.read(10)
239 assert str(ctx.value) == "ainput(): lost sys.stdin"
240 with pytest.raises(RuntimeError) as ctx:
241 await reader.readline()
242 assert str(ctx.value) == "ainput(): lost sys.stdin"