Debian Codegraph @

tests/test_multikernelmanager.py

raw
1 """Tests for the notebook kernel and session manager."""
2
3 import asyncio
4 import concurrent.futures
5 import os
6 import sys
7 import sysconfig
8 import uuid
9 from asyncio import ensure_future
10 from subprocess import PIPE
11 from unittest import TestCase
12
13 import pytest
14 import zmq
15 from jupyter_core import paths
16 from tornado.testing import AsyncTestCase, gen_test
17 from traitlets.config.loader import Config
18
19 from jupyter_client import AsyncKernelManager, KernelManager
20 from jupyter_client.localinterfaces import localhost
21 from jupyter_client.multikernelmanager import AsyncMultiKernelManager, MultiKernelManager
22
23 from .utils import (
24 AsyncKMSubclass,
25 AsyncMKMSubclass,
26 SyncKMSubclass,
27 SyncMKMSubclass,
28 install_kernel,
29 skip_win32,
30 )
31
32 TIMEOUT = 90
33
34 is_freethreaded = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
35
36
37 async def now(awaitable):
38 """Use this function ensure that this awaitable
39 happens before other awaitables defined after it.
40 """
41 (out,) = await asyncio.gather(awaitable)
42 return out
43
44
45 class TestKernelManager(TestCase):
46 def tearDown(self):
47 zmq.Context.instance().destroy(linger=0)
48 return super().tearDown()
49
50 # static so picklable for multiprocessing on Windows
51
52 @staticmethod
53 def _get_tcp_km():
54 c = Config()
55 km = MultiKernelManager(config=c)
56 return km
57
58 @staticmethod
59 def _get_tcp_km_sub():
60 c = Config()
61 km = SyncMKMSubclass(config=c)
62 return km
63
64 # static so picklable for multiprocessing on Windows
65 @staticmethod
66 def _get_ipc_km():
67 c = Config()
68 c.KernelManager.transport = "ipc"
69 c.KernelManager.ip = "test"
70 km = MultiKernelManager(config=c)
71 return km
72
73 # static so picklable for multiprocessing on Windows
74 @staticmethod
75 def _run_lifecycle(km, test_kid=None):
76 if test_kid:
77 kid = km.start_kernel(stdout=PIPE, stderr=PIPE, kernel_id=test_kid)
78 assert kid == test_kid
79 else:
80 kid = km.start_kernel(stdout=PIPE, stderr=PIPE)
81 assert km.is_alive(kid)
82 assert km.get_kernel(kid).ready.done()
83 assert kid in km
84 assert kid in km.list_kernel_ids()
85 assert len(km) == 1, f"{len(km)} != {1}"
86 km.restart_kernel(kid, now=True)
87 assert km.is_alive(kid)
88 assert kid in km.list_kernel_ids()
89 km.interrupt_kernel(kid)
90 k = km.get_kernel(kid)
91 kc = k.client()
92 assert isinstance(k, KernelManager)
93 km.shutdown_kernel(kid, now=True)
94 assert kid not in km, f"{kid} not in {km}"
95 kc.stop_channels()
96 km.context.destroy(linger=0)
97
98 def _run_cinfo(self, km, transport, ip):
99 kid = km.start_kernel(stdout=PIPE, stderr=PIPE)
100 km.get_kernel(kid)
101 cinfo = km.get_connection_info(kid)
102 self.assertEqual(transport, cinfo["transport"])
103 self.assertEqual(ip, cinfo["ip"])
104 self.assertTrue("stdin_port" in cinfo)
105 self.assertTrue("iopub_port" in cinfo)
106 stream = km.connect_iopub(kid)
107 stream.close()
108 self.assertTrue("shell_port" in cinfo)
109 stream = km.connect_shell(kid)
110 stream.close()
111 self.assertTrue("hb_port" in cinfo)
112 stream = km.connect_hb(kid)
113 stream.close()
114 km.shutdown_kernel(kid, now=True)
115 km.context.destroy(linger=0)
116
117 # static so picklable for multiprocessing on Windows
118 @classmethod
119 def test_tcp_lifecycle(cls):
120 km = cls._get_tcp_km()
121 cls._run_lifecycle(km)
122
123 def test_tcp_lifecycle_with_kernel_id(self):
124 km = self._get_tcp_km()
125 self._run_lifecycle(km, test_kid=str(uuid.uuid4()))
126
127 def test_shutdown_all(self):
128 km = self._get_tcp_km()
129 kid = km.start_kernel(stdout=PIPE, stderr=PIPE)
130 self.assertIn(kid, km)
131 km.shutdown_all()
132 self.assertNotIn(kid, km)
133 # shutdown again is okay, because we have no kernels
134 km.shutdown_all()
135 km.context.destroy(linger=0)
136
137 def test_tcp_cinfo(self):
138 km = self._get_tcp_km()
139 self._run_cinfo(km, "tcp", localhost())
140
141 @skip_win32
142 def test_ipc_lifecycle(self):
143 km = self._get_ipc_km()
144 self._run_lifecycle(km)
145
146 @skip_win32
147 def test_ipc_cinfo(self):
148 km = self._get_ipc_km()
149 self._run_cinfo(km, "ipc", "test")
150
151 def test_start_sequence_tcp_kernels(self):
152 """Ensure that a sequence of kernel startups doesn't break anything."""
153 self._run_lifecycle(self._get_tcp_km())
154 self._run_lifecycle(self._get_tcp_km())
155 self._run_lifecycle(self._get_tcp_km())
156
157 @skip_win32
158 def test_start_sequence_ipc_kernels(self):
159 """Ensure that a sequence of kernel startups doesn't break anything."""
160 self._run_lifecycle(self._get_ipc_km())
161 self._run_lifecycle(self._get_ipc_km())
162 self._run_lifecycle(self._get_ipc_km())
163
164 def tcp_lifecycle_with_loop(self):
165 # Ensure each thread has an event loop
166 async def _task():
167 return self.test_tcp_lifecycle()
168
169 asyncio.run(_task())
170
171 @pytest.mark.skipif(is_freethreaded, reason="Fail on free-threaded python")
172 def test_start_parallel_thread_kernels(self):
173 self.test_tcp_lifecycle()
174
175 with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
176 future1 = thread_executor.submit(self.tcp_lifecycle_with_loop)
177 future2 = thread_executor.submit(self.tcp_lifecycle_with_loop)
178 future1.result()
179 future2.result()
180
181 @pytest.mark.skipif(
182 sys.platform == "linux",
183 reason="Kernel refuses to start in process pool",
184 )
185 def test_start_parallel_process_kernels(self):
186 self.test_tcp_lifecycle()
187
188 with concurrent.futures.ThreadPoolExecutor(max_workers=1) as thread_executor:
189 future1 = thread_executor.submit(self.tcp_lifecycle_with_loop)
190 with concurrent.futures.ProcessPoolExecutor(max_workers=1) as process_executor:
191 # Windows tests needs this target to be picklable:
192 future2 = process_executor.submit(self.test_tcp_lifecycle)
193 future2.result()
194 future1.result()
195
196 def test_subclass_callables(self):
197 km = self._get_tcp_km_sub()
198
199 km.reset_counts()
200 kid = km.start_kernel(stdout=PIPE, stderr=PIPE)
201 assert km.call_count("start_kernel") == 1
202 assert isinstance(km.get_kernel(kid), SyncKMSubclass)
203 assert km.get_kernel(kid).call_count("start_kernel") == 1
204 assert km.get_kernel(kid).call_count("_async_launch_kernel") == 1
205
206 assert km.is_alive(kid)
207 assert kid in km
208 assert kid in km.list_kernel_ids()
209 assert len(km) == 1, f"{len(km)} != {1}"
210
211 km.get_kernel(kid).reset_counts()
212 km.reset_counts()
213 km.restart_kernel(kid, now=True)
214 assert km.call_count("restart_kernel") == 1
215 assert km.call_count("get_kernel") == 1
216 assert km.get_kernel(kid).call_count("restart_kernel") == 1
217 assert km.get_kernel(kid).call_count("_async_shutdown_kernel") == 1
218 assert km.get_kernel(kid).call_count("_async_interrupt_kernel") == 1
219 assert km.get_kernel(kid).call_count("_async_kill_kernel") == 1
220 assert km.get_kernel(kid).call_count("_async_cleanup_resources") == 1
221 assert km.get_kernel(kid).call_count("_async_launch_kernel") == 1
222
223 assert km.is_alive(kid)
224 assert kid in km.list_kernel_ids()
225
226 km.get_kernel(kid).reset_counts()
227 km.reset_counts()
228 km.interrupt_kernel(kid)
229 assert km.call_count("interrupt_kernel") == 1
230 assert km.call_count("get_kernel") == 1
231 assert km.get_kernel(kid).call_count("interrupt_kernel") == 1
232
233 km.get_kernel(kid).reset_counts()
234 km.reset_counts()
235 k = km.get_kernel(kid)
236 assert isinstance(k, SyncKMSubclass)
237 assert km.call_count("get_kernel") == 1
238
239 km.get_kernel(kid).reset_counts()
240 km.reset_counts()
241 km.shutdown_all(now=True)
242 assert km.call_count("remove_kernel") == 1
243 assert km.call_count("request_shutdown") == 0
244 assert km.call_count("finish_shutdown") == 0
245 assert km.call_count("cleanup_resources") == 0
246
247 assert kid not in km, f"{kid} not in {km}"
248
249 def test_stream_on_recv(self):
250 mkm = self._get_tcp_km()
251 kid = mkm.start_kernel(stdout=PIPE, stderr=PIPE)
252 stream = mkm.connect_iopub(kid)
253
254 km = mkm.get_kernel(kid)
255 client = km.client()
256 session = km.session
257 called = False
258
259 def record_activity(msg_list):
260 nonlocal called
261 """Record an IOPub message arriving from a kernel"""
262 _idents, fed_msg_list = session.feed_identities(msg_list)
263 msg = session.deserialize(fed_msg_list, content=False)
264
265 msg_type = msg["header"]["msg_type"]
266 stream.send(msg)
267 called = True
268
269 stream.on_recv(record_activity)
270 while True:
271 client.kernel_info()
272 import time
273
274 time.sleep(0.1)
275 if called:
276 break
277 stream.close()
278 client.stop_channels()
279 km.shutdown_kernel(now=True)
280
281
282 class TestAsyncKernelManager(AsyncTestCase):
283 def tearDown(self):
284 zmq.Context.instance().destroy(linger=0)
285 return super().tearDown()
286
287 # static so picklable for multiprocessing on Windows
288 @staticmethod
289 def _get_tcp_km():
290 c = Config()
291 km = AsyncMultiKernelManager(config=c)
292 return km
293
294 @staticmethod
295 def _get_tcp_km_sub():
296 c = Config()
297 km = AsyncMKMSubclass(config=c)
298 return km
299
300 # static so picklable for multiprocessing on Windows
301 @staticmethod
302 def _get_ipc_km():
303 c = Config()
304 c.KernelManager.transport = "ipc"
305 c.KernelManager.ip = "test"
306 km = AsyncMultiKernelManager(config=c)
307 return km
308
309 @staticmethod
310 def _get_pending_kernels_km():
311 c = Config()
312 c.AsyncMultiKernelManager.use_pending_kernels = True
313 km = AsyncMultiKernelManager(config=c)
314 return km
315
316 # static so picklable for multiprocessing on Windows
317 @staticmethod
318 async def _run_lifecycle(km, test_kid=None):
319 if test_kid:
320 kid = await km.start_kernel(stdout=PIPE, stderr=PIPE, kernel_id=test_kid)
321 assert kid == test_kid
322 else:
323 kid = await km.start_kernel(stdout=PIPE, stderr=PIPE)
324 assert await km.is_alive(kid)
325 assert kid in km
326 assert kid in km.list_kernel_ids()
327 assert len(km) == 1, f"{len(km)} != {1}"
328 # Ensure we can interrupt during a restart.
329 fut = km.restart_kernel(kid, now=True)
330 await km.interrupt_kernel(kid)
331 assert await km.is_alive(kid)
332 await fut
333 assert kid in km.list_kernel_ids()
334 k = km.get_kernel(kid)
335 assert isinstance(k, AsyncKernelManager)
336 await km.shutdown_kernel(kid, now=True)
337 assert kid not in km, f"{kid} not in {km}"
338 await km.shutdown_all()
339 km.context.destroy(linger=100)
340
341 async def _run_cinfo(self, km, transport, ip):
342 kid = await km.start_kernel(stdout=PIPE, stderr=PIPE)
343 km.get_kernel(kid)
344 cinfo = km.get_connection_info(kid)
345 self.assertEqual(transport, cinfo["transport"])
346 self.assertEqual(ip, cinfo["ip"])
347 self.assertTrue("stdin_port" in cinfo)
348 self.assertTrue("iopub_port" in cinfo)
349 stream = km.connect_iopub(kid)
350 stream.close()
351 self.assertTrue("shell_port" in cinfo)
352 stream = km.connect_shell(kid)
353 stream.close()
354 self.assertTrue("hb_port" in cinfo)
355 stream = km.connect_hb(kid)
356 stream.close()
357 await km.shutdown_kernel(kid, now=True)
358 self.assertNotIn(kid, km)
359 km.context.destroy(linger=0)
360
361 @gen_test
362 async def test_tcp_lifecycle(self):
363 await self.raw_tcp_lifecycle()
364
365 @gen_test
366 async def test_tcp_lifecycle_with_kernel_id(self):
367 await self.raw_tcp_lifecycle(test_kid=str(uuid.uuid4()))
368
369 @gen_test
370 async def test_shutdown_all(self):
371 km = self._get_tcp_km()
372 kid = await km.start_kernel(stdout=PIPE, stderr=PIPE)
373 self.assertIn(kid, km)
374 await km.shutdown_all()
375 self.assertNotIn(kid, km)
376 # shutdown again is okay, because we have no kernels
377 await km.shutdown_all()
378
379 @gen_test(timeout=20)
380 async def test_use_after_shutdown_all(self):
381 km = self._get_tcp_km()
382 kid = await km.start_kernel(stdout=PIPE, stderr=PIPE)
383 self.assertIn(kid, km)
384 await km.shutdown_all()
385 self.assertNotIn(kid, km)
386
387 # Start another kernel
388 kid = await km.start_kernel(stdout=PIPE, stderr=PIPE)
389 self.assertIn(kid, km)
390 await km.shutdown_all()
391 self.assertNotIn(kid, km)
392 # shutdown again is okay, because we have no kernels
393 await km.shutdown_all()
394
395 @gen_test(timeout=20)
396 async def test_shutdown_all_while_starting(self):
397 km = self._get_tcp_km()
398 kid_future = asyncio.ensure_future(km.start_kernel(stdout=PIPE, stderr=PIPE))
399 # This is relying on the ordering of the asyncio queue, not sure if guaranteed or not:
400 kid, _ = await asyncio.gather(kid_future, km.shutdown_all())
401 self.assertNotIn(kid, km)
402
403 # Start another kernel
404 kid = await ensure_future(km.start_kernel(stdout=PIPE, stderr=PIPE))
405 self.assertIn(kid, km)
406 self.assertEqual(len(km), 1)
407 await km.shutdown_all()
408 self.assertNotIn(kid, km)
409 # shutdown again is okay, because we have no kernels
410 await km.shutdown_all()
411 km.context.destroy(linger=0)
412
413 @gen_test
414 async def test_use_pending_kernels(self):
415 km = self._get_pending_kernels_km()
416 kid = await ensure_future(km.start_kernel(stdout=PIPE, stderr=PIPE))
417 kernel = km.get_kernel(kid)
418 assert not kernel.ready.done()
419 assert kid in km
420 assert kid in km.list_kernel_ids()
421 assert len(km) == 1, f"{len(km)} != {1}"
422 # Wait for the kernel to start.
423 await kernel.ready
424 await km.restart_kernel(kid, now=True)
425 out = await km.is_alive(kid)
426 assert out
427 assert kid in km.list_kernel_ids()
428 await km.interrupt_kernel(kid)
429 k = km.get_kernel(kid)
430 assert isinstance(k, AsyncKernelManager)
431 await ensure_future(km.shutdown_kernel(kid, now=True))
432 km.context.destroy(linger=0)
433 # Wait for the kernel to shutdown
434 await kernel.ready
435 assert kid not in km, f"{kid} not in {km}"
436
437 @gen_test
438 async def test_use_pending_kernels_early_restart(self):
439 km = self._get_pending_kernels_km()
440 kid = await ensure_future(km.start_kernel(stdout=PIPE, stderr=PIPE))
441 kernel = km.get_kernel(kid)
442 assert not kernel.ready.done()
443 with pytest.raises(RuntimeError):
444 await km.restart_kernel(kid, now=True)
445 await kernel.ready
446 await ensure_future(km.shutdown_kernel(kid, now=True))
447 # Wait for the kernel to shutdown
448 await kernel.ready
449 assert kid not in km, f"{kid} not in {km}"
450 km.context.destroy(linger=0)
451
452 @gen_test
453 async def test_use_pending_kernels_early_shutdown(self):
454 km = self._get_pending_kernels_km()
455 kid = await ensure_future(km.start_kernel(stdout=PIPE, stderr=PIPE))
456 kernel = km.get_kernel(kid)
457 assert not kernel.ready.done()
458 # Try shutting down while the kernel is pending
459 await ensure_future(km.shutdown_kernel(kid, now=True))
460 # Wait for the kernel to shutdown
461 await kernel.ready
462 assert kid not in km, f"{kid} not in {km}"
463 km.context.destroy(linger=0)
464
465 @gen_test
466 async def test_use_pending_kernels_early_interrupt(self):
467 km = self._get_pending_kernels_km()
468 kid = await ensure_future(km.start_kernel(stdout=PIPE, stderr=PIPE))
469 kernel = km.get_kernel(kid)
470 assert not kernel.ready.done()
471 with pytest.raises(RuntimeError):
472 await km.interrupt_kernel(kid)
473 # Now wait for the kernel to be ready.
474 await kernel.ready
475 await ensure_future(km.shutdown_kernel(kid, now=True))
476 # Wait for the kernel to shutdown
477 await kernel.ready
478 assert kid not in km, f"{kid} not in {km}"
479 km.context.destroy(linger=0)
480
481 @gen_test
482 async def test_tcp_cinfo(self):
483 km = self._get_tcp_km()
484 await self._run_cinfo(km, "tcp", localhost())
485 km.context.destroy(linger=0)
486
487 @skip_win32
488 @gen_test
489 async def test_ipc_lifecycle(self):
490 km = self._get_ipc_km()
491 await self._run_lifecycle(km)
492 km.context.destroy(linger=0)
493
494 @skip_win32
495 @gen_test
496 async def test_ipc_cinfo(self):
497 km = self._get_ipc_km()
498 await self._run_cinfo(km, "ipc", "test")
499 km.context.destroy(linger=0)
500
501 @gen_test
502 async def test_start_sequence_tcp_kernels(self):
503 """Ensure that a sequence of kernel startups doesn't break anything."""
504 await self._run_lifecycle(self._get_tcp_km())
505 await self._run_lifecycle(self._get_tcp_km())
506 await self._run_lifecycle(self._get_tcp_km())
507
508 @skip_win32
509 @gen_test
510 async def test_start_sequence_ipc_kernels(self):
511 """Ensure that a sequence of kernel startups doesn't break anything."""
512 await self._run_lifecycle(self._get_ipc_km())
513 await self._run_lifecycle(self._get_ipc_km())
514 await self._run_lifecycle(self._get_ipc_km())
515
516 def tcp_lifecycle_with_loop(self):
517 # Ensure each thread has an event loop
518 loop = asyncio.new_event_loop()
519 asyncio.set_event_loop(loop)
520 loop.run_until_complete(self.raw_tcp_lifecycle())
521 loop.close()
522
523 # static so picklable for multiprocessing on Windows
524 @classmethod
525 async def raw_tcp_lifecycle(cls, test_kid=None):
526 # Since @gen_test creates an event loop, we need a raw form of
527 # test_tcp_lifecycle that assumes the loop already exists.
528 km = cls._get_tcp_km()
529 await cls._run_lifecycle(km, test_kid=test_kid)
530
531 # static so picklable for multiprocessing on Windows
532 @classmethod
533 def raw_tcp_lifecycle_sync(cls, test_kid=None):
534 loop = asyncio.new_event_loop()
535 asyncio.set_event_loop(loop)
536 loop.run_until_complete(cls.raw_tcp_lifecycle(test_kid=test_kid))
537 loop.close()
538
539 @gen_test
540 async def test_start_parallel_thread_kernels(self):
541 await self.raw_tcp_lifecycle()
542
543 with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
544 future1 = thread_executor.submit(self.tcp_lifecycle_with_loop)
545 future2 = thread_executor.submit(self.tcp_lifecycle_with_loop)
546 future1.result()
547 future2.result()
548
549 @gen_test
550 async def test_start_parallel_process_kernels(self):
551 await self.raw_tcp_lifecycle()
552
553 with concurrent.futures.ThreadPoolExecutor(max_workers=1) as thread_executor:
554 future1 = thread_executor.submit(self.tcp_lifecycle_with_loop)
555 with concurrent.futures.ProcessPoolExecutor(max_workers=1) as process_executor:
556 # Windows tests needs this target to be picklable:
557 future2 = process_executor.submit(self.raw_tcp_lifecycle_sync)
558 future2.result()
559 future1.result()
560
561 @gen_test
562 async def test_subclass_callables(self):
563 mkm = self._get_tcp_km_sub()
564
565 mkm.reset_counts()
566 kid = await mkm.start_kernel(stdout=PIPE, stderr=PIPE)
567 assert mkm.call_count("start_kernel") == 1
568 assert isinstance(mkm.get_kernel(kid), AsyncKMSubclass)
569 assert mkm.get_kernel(kid).call_count("start_kernel") == 1
570 assert mkm.get_kernel(kid).call_count("_async_launch_kernel") == 1
571
572 assert await mkm.is_alive(kid)
573 assert kid in mkm
574 assert kid in mkm.list_kernel_ids()
575 assert len(mkm) == 1, f"{len(mkm)} != {1}"
576
577 mkm.get_kernel(kid).reset_counts()
578 mkm.reset_counts()
579 await mkm.restart_kernel(kid, now=True)
580 assert mkm.call_count("restart_kernel") == 1
581 assert mkm.call_count("get_kernel") == 1
582 assert mkm.get_kernel(kid).call_count("restart_kernel") == 1
583 assert mkm.get_kernel(kid).call_count("_async_interrupt_kernel") == 1
584 assert mkm.get_kernel(kid).call_count("_async_kill_kernel") == 1
585 assert mkm.get_kernel(kid).call_count("_async_cleanup_resources") == 1
586 assert mkm.get_kernel(kid).call_count("_async_launch_kernel") == 1
587
588 assert await mkm.is_alive(kid)
589 assert kid in mkm.list_kernel_ids()
590
591 mkm.get_kernel(kid).reset_counts()
592 mkm.reset_counts()
593 await mkm.interrupt_kernel(kid)
594 assert mkm.call_count("interrupt_kernel") == 1
595 assert mkm.call_count("get_kernel") == 1
596 assert mkm.get_kernel(kid).call_count("interrupt_kernel") == 1
597
598 mkm.get_kernel(kid).reset_counts()
599 mkm.reset_counts()
600 k = mkm.get_kernel(kid)
601 assert isinstance(k, AsyncKMSubclass)
602 assert mkm.call_count("get_kernel") == 1
603
604 mkm.get_kernel(kid).reset_counts()
605 mkm.reset_counts()
606 await mkm.shutdown_all(now=True)
607 mkm.context.destroy(linger=0)
608 assert mkm.call_count("remove_kernel") == 1
609 assert mkm.call_count("_async_request_shutdown") == 0
610 assert mkm.call_count("_async_finish_shutdown") == 0
611 assert mkm.call_count("_async_cleanup_resources") == 0
612
613 assert kid not in mkm, f"{kid} not in {mkm}"
614
615 @gen_test
616 async def test_bad_kernelspec(self):
617 km = self._get_tcp_km()
618 install_kernel(
619 os.path.join(paths.jupyter_data_dir(), "kernels"),
620 argv=["non_existent_executable"],
621 name="bad",
622 )
623 with pytest.raises(FileNotFoundError):
624 await ensure_future(km.start_kernel(kernel_name="bad", stdout=PIPE, stderr=PIPE))
625 km.context.destroy(linger=0)
626
627 @gen_test
628 async def test_bad_kernelspec_pending(self):
629 km = self._get_pending_kernels_km()
630 install_kernel(
631 os.path.join(paths.jupyter_data_dir(), "kernels"),
632 argv=["non_existent_executable"],
633 name="bad",
634 )
635 kernel_id = await ensure_future(
636 km.start_kernel(kernel_name="bad", stdout=PIPE, stderr=PIPE)
637 )
638 with pytest.raises(FileNotFoundError):
639 await km.get_kernel(kernel_id).ready
640 assert kernel_id in km.list_kernel_ids()
641 await ensure_future(km.shutdown_kernel(kernel_id))
642 assert kernel_id not in km.list_kernel_ids()
643 km.context.destroy(linger=0)
644
645 @gen_test(timeout=TIMEOUT)
646 async def test_stream_on_recv(self):
647 mkm = self._get_tcp_km()
648 kid = await mkm.start_kernel(stdout=PIPE, stderr=PIPE)
649 stream = mkm.connect_iopub(kid)
650
651 km = mkm.get_kernel(kid)
652 client = km.client()
653 session = km.session
654 called = False
655
656 def record_activity(msg_list):
657 nonlocal called
658 """Record an IOPub message arriving from a kernel"""
659 _idents, fed_msg_list = session.feed_identities(msg_list)
660 msg = session.deserialize(fed_msg_list, content=False)
661
662 msg_type = msg["header"]["msg_type"]
663 stream.send(msg)
664 called = True
665
666 stream.on_recv(record_activity)
667 while True:
668 await client.kernel_info(reply=True)
669 if called:
670 break
671 await asyncio.sleep(0.1)
672
673 client.stop_channels()
674 stream.close()
675 await km.shutdown_kernel(now=True)
676 km.context.destroy(linger=0)