Debian Codegraph @

testing/test_multi.py

raw symbols SCIP
1 """
2 tests for multi channels and gateway Groups
3 """
4
5 from __future__ import annotations
6
7 import gc
8 from time import sleep
9 from typing import Callable
10
11 import pytest
12
13 import execnet
14 from execnet import XSpec
15 from execnet.gateway import Gateway
16 from execnet.gateway_base import Channel
17 from execnet.gateway_base import ExecModel
18 from execnet.multi import Group
19 from execnet.multi import safe_terminate
20
21
22 class TestMultiChannelAndGateway:
23 def test_multichannel_container_basics(
24 self, gw: Gateway, execmodel: ExecModel
25 ) -> None:
26 mch = execnet.MultiChannel([Channel(gw, i) for i in range(3)])
27 assert len(mch) == 3
28 channels = list(mch)
29 assert len(channels) == 3
30 # ordering
31 for i in range(3):
32 assert channels[i].id == i
33 assert channels[i] == mch[i]
34 assert channels[0] in mch
35 assert channels[1] in mch
36 assert channels[2] in mch
37
38 def test_multichannel_receive_each(self) -> None:
39 class pseudochannel:
40 def receive(self) -> object:
41 return 12
42
43 pc1 = pseudochannel()
44 pc2 = pseudochannel()
45 multichannel = execnet.MultiChannel([pc1, pc2]) # type: ignore[list-item]
46 l = multichannel.receive_each(withchannel=True)
47 assert len(l) == 2
48 assert l == [(pc1, 12), (pc2, 12)] # type: ignore[comparison-overlap]
49 l2 = multichannel.receive_each(withchannel=False)
50 assert l2 == [12, 12]
51
52 def test_multichannel_send_each(self) -> None:
53 gm = execnet.Group(["popen"] * 2)
54 mc = gm.remote_exec(
55 """
56 import os
57 channel.send(channel.receive() + 1)
58 """
59 )
60 mc.send_each(41)
61 l = mc.receive_each()
62 assert l == [42, 42]
63
64 def test_Group_execmodel_setting(self) -> None:
65 gm = execnet.Group()
66 gm.set_execmodel("thread")
67 assert gm.execmodel.backend == "thread"
68 assert gm.remote_execmodel.backend == "thread"
69 gm._gateways.append(1) # type: ignore[arg-type]
70 try:
71 with pytest.raises(ValueError):
72 gm.set_execmodel("eventlet")
73 assert gm.execmodel.backend == "thread"
74 finally:
75 gm._gateways.pop()
76
77 def test_multichannel_receive_queue_for_two_subprocesses(self) -> None:
78 gm = execnet.Group(["popen"] * 2)
79 mc = gm.remote_exec(
80 """
81 import os
82 channel.send(os.getpid())
83 """
84 )
85 queue = mc.make_receive_queue()
86 ch, item = queue.get(timeout=10)
87 ch2, item2 = queue.get(timeout=10)
88 assert ch != ch2
89 assert ch.gateway != ch2.gateway
90 assert item != item2
91 mc.waitclose()
92
93 def test_multichannel_waitclose(self) -> None:
94 l = []
95
96 class pseudochannel:
97 def waitclose(self) -> None:
98 l.append(0)
99
100 multichannel = execnet.MultiChannel([pseudochannel(), pseudochannel()]) # type: ignore[list-item]
101 multichannel.waitclose()
102 assert len(l) == 2
103
104
105 class TestGroup:
106 def test_basic_group(self, monkeypatch: pytest.MonkeyPatch) -> None:
107 import atexit
108
109 atexitlist: list[Callable[[], object]] = []
110 monkeypatch.setattr(atexit, "register", atexitlist.append)
111 group = Group()
112 assert atexitlist == [group._cleanup_atexit]
113 exitlist = []
114 joinlist = []
115
116 class PseudoIO:
117 def wait(self) -> None:
118 pass
119
120 class PseudoSpec:
121 via = None
122
123 class PseudoGW:
124 id = "9999"
125 _io = PseudoIO()
126 spec = PseudoSpec()
127
128 def exit(self) -> None:
129 exitlist.append(self)
130 group._unregister(self) # type: ignore[arg-type]
131
132 def join(self) -> None:
133 joinlist.append(self)
134
135 gw = PseudoGW()
136 group._register(gw) # type: ignore[arg-type]
137 assert len(exitlist) == 0
138 assert len(joinlist) == 0
139 group._cleanup_atexit()
140 assert len(exitlist) == 1
141 assert exitlist == [gw]
142 assert len(joinlist) == 1
143 assert joinlist == [gw]
144 group._cleanup_atexit()
145 assert len(exitlist) == 1
146 assert len(joinlist) == 1
147
148 def test_group_default_spec(self) -> None:
149 group = Group()
150 group.defaultspec = "not-existing-type"
151 pytest.raises(ValueError, group.makegateway)
152
153 def test_group_PopenGateway(self) -> None:
154 group = Group()
155 gw = group.makegateway("popen")
156 assert list(group) == [gw]
157 assert group[0] == gw
158 assert len(group) == 1
159 group._cleanup_atexit()
160 assert not group._gateways
161
162 def test_group_ordering_and_termination(self) -> None:
163 group = Group()
164 group.makegateway("popen//id=3")
165 group.makegateway("popen//id=2")
166 group.makegateway("popen//id=5")
167 gwlist = list(group)
168 assert len(gwlist) == 3
169 idlist = [x.id for x in gwlist]
170 assert idlist == list("325")
171 print(group)
172 group.terminate()
173 print(group)
174 assert not group
175 assert repr(group) == "<Group []>"
176
177 def test_group_id_allocation(self) -> None:
178 group = Group()
179 specs = [XSpec("popen"), XSpec("popen//id=hello")]
180 group.allocate_id(specs[0])
181 group.allocate_id(specs[1])
182 gw = group.makegateway(specs[1])
183 assert gw.id == "hello"
184 gw = group.makegateway(specs[0])
185 assert gw.id == "gw0"
186 # pytest.raises(ValueError,
187 # group.allocate_id, XSpec("popen//id=hello"))
188 group.terminate()
189
190 def test_gateway_and_id(self) -> None:
191 group = Group()
192 gw = group.makegateway("popen//id=hello")
193 assert group["hello"] == gw
194 with pytest.raises((TypeError, AttributeError)):
195 del group["hello"] # type: ignore[attr-defined]
196 with pytest.raises((TypeError, AttributeError)):
197 group["hello"] = 5 # type: ignore[index]
198 assert "hello" in group
199 assert gw in group
200 assert len(group) == 1
201 gw.exit()
202 assert "hello" not in group
203 with pytest.raises(KeyError):
204 _ = group["hello"]
205
206 def test_default_group(self) -> None:
207 oldlist = list(execnet.default_group)
208 gw = execnet.makegateway("popen")
209 try:
210 newlist = list(execnet.default_group)
211 assert len(newlist) == len(oldlist) + 1
212 assert gw in newlist
213 assert gw not in oldlist
214 finally:
215 gw.exit()
216
217 def test_remote_exec_args(self) -> None:
218 group = Group()
219 group.makegateway("popen")
220
221 def fun(channel, arg) -> None:
222 channel.send(arg)
223
224 mch = group.remote_exec(fun, arg=1)
225 result = mch.receive_each()
226 assert result == [1]
227
228 def test_terminate_with_proxying(self) -> None:
229 group = Group()
230 group.makegateway("popen//id=master")
231 group.makegateway("popen//via=master//id=worker")
232 group.terminate(1.0)
233
234
235 @pytest.mark.xfail(reason="active_count() has been broken for some time")
236 def test_safe_terminate(execmodel: ExecModel) -> None:
237 if execmodel.backend not in ("thread", "main_thread_only"):
238 pytest.xfail(
239 "execution model %r does not support task count" % execmodel.backend
240 )
241 import threading
242
243 active = threading.active_count()
244 l = []
245
246 def term() -> None:
247 sleep(3)
248
249 def kill() -> None:
250 l.append(1)
251
252 safe_terminate(execmodel, 1, [(term, kill)] * 10)
253 assert len(l) == 10
254 sleep(0.1)
255 gc.collect()
256 assert execmodel.active_count() == active # type: ignore[attr-defined]
257
258
259 @pytest.mark.xfail(reason="active_count() has been broken for some time")
260 def test_safe_terminate2(execmodel: ExecModel) -> None:
261 if execmodel.backend not in ("thread", "main_thread_only"):
262 pytest.xfail(
263 "execution model %r does not support task count" % execmodel.backend
264 )
265 import threading
266
267 active = threading.active_count()
268 l = []
269
270 def term() -> None:
271 return
272
273 def kill() -> None:
274 l.append(1)
275
276 safe_terminate(execmodel, 3, [(term, kill)] * 10)
277 assert len(l) == 0
278 sleep(0.1)
279 gc.collect()
280 assert threading.active_count() == active