Debian Codegraph @

tests/test_io.py

raw
1 """Test IO capturing functionality"""
2
3 import io
4 import os
5 import subprocess
6 import sys
7 import threading
8 import time
9 import warnings
10 from concurrent.futures import Future, ThreadPoolExecutor
11 from unittest import mock
12
13 import pytest
14 import zmq
15 from jupyter_client.session import Session
16
17 from ipykernel.iostream import MASTER, BackgroundSocket, IOPubThread, OutStream
18
19
20 @pytest.fixture()
21 def ctx():
22 ctx = zmq.Context()
23 yield ctx
24 ctx.destroy()
25
26
27 @pytest.fixture()
28 def iopub_thread(ctx):
29 session = Session()
30 with ctx.socket(zmq.PUB) as pub:
31 thread = IOPubThread(pub, session=session)
32 thread.start()
33
34 yield thread
35 thread.stop()
36 thread.close()
37
38
39 def test_io_api(iopub_thread):
40 """Test that wrapped stdout has the same API as a normal TextIO object"""
41 session = Session()
42 stream = OutStream(session, iopub_thread, "stdout")
43
44 assert stream.errors is None
45 assert not stream.isatty()
46 with pytest.raises(io.UnsupportedOperation):
47 stream.detach()
48 with pytest.raises(io.UnsupportedOperation):
49 next(stream)
50 with pytest.raises(io.UnsupportedOperation):
51 stream.read()
52 with pytest.raises(io.UnsupportedOperation):
53 stream.readline()
54 with pytest.raises(io.UnsupportedOperation):
55 stream.seek(0)
56 with pytest.raises(io.UnsupportedOperation):
57 stream.tell()
58 with pytest.raises(TypeError):
59 stream.write(b"") # type:ignore
60
61
62 def test_io_isatty(iopub_thread):
63 session = Session()
64 stream = OutStream(session, iopub_thread, "stdout", isatty=True)
65 assert stream.isatty()
66
67
68 def test_io_thread(iopub_thread):
69 thread = iopub_thread
70 thread._setup_pipe_in()
71 msg = [thread._pipe_uuid, b"a"]
72 thread._handle_pipe_msg(msg)
73 ctx1, pipe = thread._setup_pipe_out()
74 pipe.close()
75 thread._pipe_in.close()
76 thread._check_mp_mode = lambda: MASTER
77 thread._really_send([b"hi"])
78 ctx1.destroy()
79 thread.close()
80 thread.close()
81 thread._really_send(None)
82
83
84 def test_background_socket(iopub_thread):
85 sock = BackgroundSocket(iopub_thread)
86 assert sock.__class__ == BackgroundSocket
87 with warnings.catch_warnings():
88 warnings.simplefilter("ignore", DeprecationWarning)
89 sock.linger = 101
90 assert iopub_thread.socket.linger == 101
91 assert sock.io_thread == iopub_thread
92 sock.send(b"hi")
93
94
95 def test_outstream(iopub_thread):
96 session = Session()
97 pub = iopub_thread.socket
98 with warnings.catch_warnings():
99 warnings.simplefilter("ignore", DeprecationWarning)
100 stream = OutStream(session, pub, "stdout")
101 stream.close()
102 stream = OutStream(session, iopub_thread, "stdout", pipe=object())
103 stream.close()
104
105 stream = OutStream(session, iopub_thread, "stdout", watchfd=False)
106 stream.close()
107
108 stream = OutStream(session, iopub_thread, "stdout", isatty=True, echo=io.StringIO())
109
110 with stream:
111 with pytest.raises(io.UnsupportedOperation):
112 stream.fileno()
113 stream._watch_pipe_fd()
114 stream.flush()
115 stream.write("hi")
116 stream.writelines(["ab", "cd"])
117 assert stream.writable()
118
119
120 async def test_event_pipe_gc(iopub_thread):
121 session = Session(key=b"abc")
122 stream = OutStream(
123 session,
124 iopub_thread,
125 "stdout",
126 isatty=True,
127 watchfd=False,
128 )
129 assert iopub_thread._event_pipes == {}
130 with stream, mock.patch.object(sys, "stdout", stream), ThreadPoolExecutor(1) as pool:
131 pool.submit(print, "x").result()
132 pool_thread = pool.submit(threading.current_thread).result()
133 assert list(iopub_thread._event_pipes) == [pool_thread]
134
135 # run gc once in the iopub thread
136 f: Future = Future()
137
138 async def run_gc():
139 try:
140 await iopub_thread._event_pipe_gc()
141 except Exception as e:
142 f.set_exception(e)
143 else:
144 f.set_result(None)
145
146 iopub_thread.io_loop.add_callback(run_gc)
147 # wait for call to finish in iopub thread
148 f.result()
149 assert iopub_thread._event_pipes == {}
150
151
152 def subprocess_test_echo_watch():
153 # handshake Pub subscription
154 session = Session(key=b"abc")
155
156 # use PUSH socket to avoid subscription issues
157 with zmq.Context() as ctx, ctx.socket(zmq.PUSH) as pub:
158 pub.connect(os.environ["IOPUB_URL"])
159 iopub_thread = IOPubThread(pub, session=session)
160 iopub_thread.start()
161 stdout_fd = sys.stdout.fileno()
162 sys.stdout.flush()
163 stream = OutStream(
164 session,
165 iopub_thread,
166 "stdout",
167 isatty=True,
168 echo=sys.stdout,
169 watchfd="force",
170 )
171 save_stdout = sys.stdout
172 with stream, mock.patch.object(sys, "stdout", stream):
173 # write to low-level FD
174 os.write(stdout_fd, b"fd\n")
175 # print (writes to stream)
176 print("print\n", end="")
177 sys.stdout.flush()
178 # write to unwrapped __stdout__ (should also go to original FD)
179 sys.__stdout__.write("__stdout__\n")
180 sys.__stdout__.flush()
181 # write to original sys.stdout (should be the same as __stdout__)
182 save_stdout.write("stdout\n")
183 save_stdout.flush()
184 # is there another way to flush on the FD?
185 fd_file = os.fdopen(stdout_fd, "w")
186 fd_file.flush()
187 # we don't have a sync flush on _reading_ from the watched pipe
188 time.sleep(1)
189 stream.flush()
190 iopub_thread.stop()
191 iopub_thread.close()
192
193
194 @pytest.mark.skipif(sys.platform.startswith("win"), reason="Windows")
195 def test_echo_watch(ctx):
196 """Test echo on underlying FD while capturing the same FD
197
198 Test runs in a subprocess to avoid messing with pytest output capturing.
199 """
200 s = ctx.socket(zmq.PULL)
201 port = s.bind_to_random_port("tcp://127.0.0.1")
202 url = f"tcp://127.0.0.1:{port}"
203 session = Session(key=b"abc")
204 stdout_chunks = []
205 with s:
206 env = dict(os.environ)
207 env["IOPUB_URL"] = url
208 env["PYTHONUNBUFFERED"] = "1"
209 env.pop("PYTEST_CURRENT_TEST", None)
210 p = subprocess.run(
211 [
212 sys.executable,
213 "-c",
214 f"import {__name__}; {__name__}.subprocess_test_echo_watch()",
215 ],
216 env=env,
217 capture_output=True,
218 check=True,
219 text=True,
220 timeout=10,
221 )
222 print(f"{p.stdout=}")
223 print(f"{p.stderr}=", file=sys.stderr)
224 assert p.returncode == 0
225 while s.poll(timeout=100):
226 _ident, msg = session.recv(s)
227 assert msg is not None # for type narrowing
228 if msg["header"]["msg_type"] == "stream" and msg["content"]["name"] == "stdout":
229 stdout_chunks.append(msg["content"]["text"])
230
231 # check outputs
232 # use sets of lines to ignore ordering issues with
233 # async flush and watchfd thread
234
235 # Check the stream output forwarded over zmq
236 zmq_stdout = "".join(stdout_chunks)
237 assert set(zmq_stdout.strip().splitlines()) == {
238 "fd",
239 "print",
240 "stdout",
241 "__stdout__",
242 }
243
244 # Check what was written to the process stdout (kernel terminal)
245 # just check that each output source went to the terminal
246 assert set(p.stdout.strip().splitlines()) == {
247 "fd",
248 "print",
249 "stdout",
250 "__stdout__",
251 }