Debian Codegraph @

testing/test_channel.py

raw symbols ◀ ▶ SCIP
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """
2 mostly functional tests of gateways.
3 """
4
5 from __future__ import annotations
6
7 import time
8
9 import pytest
10
11 from execnet.gateway import Gateway
12 from execnet.gateway_base import Channel
13
14 needs_early_gc = pytest.mark.skipif("not hasattr(sys, 'getrefcount')")
15 needs_osdup = pytest.mark.skipif("not hasattr(os, 'dup')")
16 flakytest = pytest.mark.xfail(reason="flaky test")
17 TESTTIMEOUT = 10.0 # seconds
18
19
20 class TestChannelBasicBehaviour:
21 def test_serialize_error(self, gw: Gateway) -> None:
22 ch = gw.remote_exec("channel.send(ValueError(42))")
23 excinfo = pytest.raises(ch.RemoteError, ch.receive)
24 assert "can't serialize" in str(excinfo.value)
25
26 def test_channel_close_and_then_receive_error(self, gw: Gateway) -> None:
27 channel = gw.remote_exec("raise ValueError")
28 pytest.raises(channel.RemoteError, channel.receive)
29
30 def test_channel_finish_and_then_EOFError(self, gw: Gateway) -> None:
31 channel = gw.remote_exec("channel.send(42)")
32 x = channel.receive()
33 assert x == 42
34 pytest.raises(EOFError, channel.receive)
35 pytest.raises(EOFError, channel.receive)
36 pytest.raises(EOFError, channel.receive)
37
38 def test_waitclose_timeouterror(self, gw: Gateway) -> None:
39 channel = gw.remote_exec("channel.receive()")
40 pytest.raises(channel.TimeoutError, channel.waitclose, 0.02)
41 channel.send(1)
42 channel.waitclose(timeout=TESTTIMEOUT)
43
44 def test_channel_receive_timeout(self, gw: Gateway) -> None:
45 channel = gw.remote_exec("channel.send(channel.receive())")
46 with pytest.raises(channel.TimeoutError):
47 channel.receive(timeout=0.2)
48 channel.send(1)
49 channel.receive(timeout=TESTTIMEOUT)
50
51 def test_channel_receive_internal_timeout(
52 self, gw: Gateway, monkeypatch: pytest.MonkeyPatch
53 ) -> None:
54 channel = gw.remote_exec(
55 """
56 import time
57 time.sleep(0.5)
58 channel.send(1)
59 """
60 )
61 monkeypatch.setattr(channel.__class__, "_INTERNALWAKEUP", 0.2)
62 channel.receive()
63
64 def test_channel_close_and_then_receive_error_multiple(self, gw: Gateway) -> None:
65 channel = gw.remote_exec("channel.send(42) ; raise ValueError")
66 x = channel.receive()
67 assert x == 42
68 pytest.raises(channel.RemoteError, channel.receive)
69
70 def test_channel__local_close(self, gw: Gateway) -> None:
71 channel = gw._channelfactory.new()
72 gw._channelfactory._local_close(channel.id)
73 channel.waitclose(0.1)
74
75 def test_channel__local_close_error(self, gw: Gateway) -> None:
76 channel = gw._channelfactory.new()
77 gw._channelfactory._local_close(channel.id, channel.RemoteError("error"))
78 pytest.raises(channel.RemoteError, channel.waitclose, 0.01)
79
80 def test_channel_error_reporting(self, gw: Gateway) -> None:
81 channel = gw.remote_exec("def foo():\n return foobar()\nfoo()\n")
82 excinfo = pytest.raises(channel.RemoteError, channel.receive)
83 msg = str(excinfo.value)
84 assert msg.startswith("Traceback (most recent call last):")
85 assert "NameError" in msg
86 assert "foobar" in msg
87
88 def test_channel_syntax_error(self, gw: Gateway) -> None:
89 # missing colon
90 channel = gw.remote_exec("def foo()\n return 1\nfoo()\n")
91 excinfo = pytest.raises(channel.RemoteError, channel.receive)
92 msg = str(excinfo.value)
93 assert msg.startswith("Traceback (most recent call last):")
94 assert "SyntaxError" in msg
95
96 def test_channel_iter(self, gw: Gateway) -> None:
97 channel = gw.remote_exec(
98 """
99 for x in range(3):
100 channel.send(x)
101 """
102 )
103 l = list(channel)
104 assert l == [0, 1, 2]
105
106 def test_channel_pass_in_structure(self, gw: Gateway) -> None:
107 channel = gw.remote_exec(
108 """
109 ch1, ch2 = channel.receive()
110 data = ch1.receive()
111 ch2.send(data+1)
112 """
113 )
114 newchan1 = gw.newchannel()
115 newchan2 = gw.newchannel()
116 channel.send((newchan1, newchan2))
117 newchan1.send(1)
118 data = newchan2.receive()
119 assert data == 2
120
121 def test_channel_multipass(self, gw: Gateway) -> None:
122 channel = gw.remote_exec(
123 """
124 channel.send(channel)
125 xchan = channel.receive()
126 assert xchan == channel
127 """
128 )
129 newchan = channel.receive()
130 assert newchan == channel
131 channel.send(newchan)
132 channel.waitclose()
133
134 @flakytest
135 def test_channel_passing_over_channel(self, gw: Gateway) -> None:
136 channel = gw.remote_exec(
137 """
138 c = channel.gateway.newchannel()
139 channel.send(c)
140 c.send(42)
141 """
142 )
143 c = channel.receive()
144 assert isinstance(c, Channel)
145 x = c.receive()
146 assert x == 42
147
148 # check that the both sides previous channels are really gone
149 channel.waitclose(TESTTIMEOUT)
150 # assert c.id not in gw._channelfactory
151 newchan = gw.remote_exec(
152 """
153 assert %d not in channel.gateway._channelfactory._channels
154 """
155 % channel.id
156 )
157 newchan.waitclose(TESTTIMEOUT)
158 assert channel.id not in gw._channelfactory._channels
159
160 def test_channel_receiver_callback(self, gw: Gateway) -> None:
161 l: list[int] = []
162 # channel = gw.newchannel(receiver=l.append)
163 channel = gw.remote_exec(
164 source="""
165 channel.send(42)
166 channel.send(13)
167 channel.send(channel.gateway.newchannel())
168 """
169 )
170 channel.setcallback(callback=l.append)
171 pytest.raises(IOError, channel.receive)
172 channel.waitclose(TESTTIMEOUT)
173 assert len(l) == 3
174 assert l[:2] == [42, 13]
175 assert isinstance(l[2], channel.__class__)
176
177 def test_channel_callback_after_receive(self, gw: Gateway) -> None:
178 l: list[int] = []
179 channel = gw.remote_exec(
180 source="""
181 channel.send(42)
182 channel.send(13)
183 channel.send(channel.gateway.newchannel())
184 """
185 )
186 x = channel.receive()
187 assert x == 42
188 channel.setcallback(callback=l.append)
189 pytest.raises(IOError, channel.receive)
190 channel.waitclose(TESTTIMEOUT)
191 assert len(l) == 2
192 assert l[0] == 13
193 assert isinstance(l[1], channel.__class__)
194
195 def test_waiting_for_callbacks(self, gw: Gateway) -> None:
196 l = []
197
198 def callback(msg) -> None:
199 import time
200
201 time.sleep(0.2)
202 l.append(msg)
203
204 channel = gw.remote_exec(
205 source="""
206 channel.send(42)
207 """
208 )
209 channel.setcallback(callback)
210 channel.waitclose(TESTTIMEOUT)
211 assert l == [42]
212
213 def test_channel_callback_stays_active(self, gw: Gateway) -> None:
214 self.check_channel_callback_stays_active(gw, earlyfree=True)
215
216 def check_channel_callback_stays_active(
217 self, gw: Gateway, earlyfree: bool = True
218 ) -> Channel | None:
219 if gw.spec.execmodel == "gevent":
220 pytest.xfail("investigate gevent failure")
221 # with 'earlyfree==True', this tests the "sendonly" channel state.
222 l: list[int] = []
223 channel = gw.remote_exec(
224 source="""
225 import _thread
226 import time
227 def producer(subchannel):
228 for i in range(5):
229 time.sleep(0.15)
230 subchannel.send(i*100)
231 channel2 = channel.receive()
232 _thread.start_new_thread(producer, (channel2,))
233 del channel2
234 """
235 )
236 subchannel = gw.newchannel()
237 subchannel.setcallback(l.append)
238 channel.send(subchannel)
239 subchan = None if earlyfree else subchannel
240 counter = 100
241 while len(l) < 5:
242 if subchan and subchan.isclosed():
243 break
244 counter -= 1
245 print(counter)
246 if not counter:
247 pytest.fail("timed out waiting for the answer[%d]" % len(l))
248 time.sleep(0.04) # busy-wait
249 assert l == [0, 100, 200, 300, 400]
250 return subchan
251
252 @needs_early_gc
253 def test_channel_callback_remote_freed(self, gw: Gateway) -> None:
254 channel = self.check_channel_callback_stays_active(gw, earlyfree=False)
255 assert channel is not None
256 # freed automatically at the end of producer()
257 channel.waitclose(TESTTIMEOUT)
258
259 def test_channel_endmarker_callback(self, gw: Gateway) -> None:
260 l: list[int | Channel] = []
261 channel = gw.remote_exec(
262 source="""
263 channel.send(42)
264 channel.send(13)
265 channel.send(channel.gateway.newchannel())
266 """
267 )
268 channel.setcallback(l.append, 999)
269 pytest.raises(IOError, channel.receive)
270 channel.waitclose(TESTTIMEOUT)
271 assert len(l) == 4
272 assert l[:2] == [42, 13]
273 assert isinstance(l[2], channel.__class__)
274 assert l[3] == 999
275
276 def test_channel_endmarker_callback_error(self, gw: Gateway) -> None:
277 q = gw.execmodel.queue.Queue()
278 channel = gw.remote_exec(
279 source="""
280 raise ValueError()
281 """
282 )
283 channel.setcallback(q.put, endmarker=999)
284 val = q.get(TESTTIMEOUT)
285 assert val == 999
286 err = channel._getremoteerror()
287 assert err
288 assert str(err).find("ValueError") != -1
289
290 def test_channel_callback_error(self, gw: Gateway) -> None:
291 channel = gw.remote_exec(
292 """
293 def f(item):
294 raise ValueError(42)
295 ch = channel.gateway.newchannel()
296 ch.setcallback(f)
297 channel.send(ch)
298 channel.receive()
299 assert ch.isclosed()
300 """
301 )
302 subchan = channel.receive()
303 assert isinstance(subchan, Channel)
304 subchan.send(1)
305 with pytest.raises(subchan.RemoteError) as excinfo:
306 subchan.waitclose(TESTTIMEOUT)
307 assert "42" in excinfo.value.formatted
308 channel.send(1)
309 channel.waitclose()
310
311
312 class TestChannelFile:
313 def test_channel_file_write(self, gw: Gateway) -> None:
314 channel = gw.remote_exec(
315 """
316 f = channel.makefile()
317 f.write("hello world\\n")
318 f.close()
319 channel.send(42)
320 """
321 )
322 first = channel.receive()
323 assert isinstance(first, str)
324 assert first.strip() == "hello world"
325 second = channel.receive()
326 assert second == 42
327
328 def test_channel_file_write_error(self, gw: Gateway) -> None:
329 channel = gw.remote_exec("pass")
330 f = channel.makefile()
331 assert not f.isatty()
332 channel.waitclose(TESTTIMEOUT)
333 with pytest.raises(IOError):
334 f.write(b"hello")
335
336 def test_channel_file_proxyclose(self, gw: Gateway) -> None:
337 channel = gw.remote_exec(
338 """
339 f = channel.makefile(proxyclose=True)
340 f.write("hello world")
341 f.close()
342 channel.send(42)
343 """
344 )
345 first = channel.receive()
346 assert isinstance(first, str)
347 assert first.strip() == "hello world"
348 pytest.raises(channel.RemoteError, channel.receive)
349
350 def test_channel_file_read(self, gw: Gateway) -> None:
351 channel = gw.remote_exec(
352 """
353 f = channel.makefile(mode='r')
354 s = f.read(2)
355 channel.send(s)
356 s = f.read(5)
357 channel.send(s)
358 """
359 )
360 channel.send("xyabcde")
361 s1 = channel.receive()
362 s2 = channel.receive()
363 assert s1 == "xy"
364 assert s2 == "abcde"
365
366 def test_channel_file_read_empty(self, gw: Gateway) -> None:
367 channel = gw.remote_exec("pass")
368 f = channel.makefile(mode="r")
369 s = f.read(3)
370 assert s == ""
371 s = f.read(5)
372 assert s == ""
373
374 def test_channel_file_readline_remote(self, gw: Gateway) -> None:
375 channel = gw.remote_exec(
376 """
377 channel.send('123\\n45')
378 """
379 )
380 channel.waitclose(TESTTIMEOUT)
381 f = channel.makefile(mode="r")
382 s = f.readline()
383 assert s == "123\n"
384 s = f.readline()
385 assert s == "45"
386
387 def test_channel_makefile_incompatmode(self, gw: Gateway) -> None:
388 channel = gw.newchannel()
389 with pytest.raises(ValueError):
390 channel.makefile("rw") # type: ignore[call-overload]