| 1 |
"""test embed_kernel""" |
| 2 |
|
| 3 |
# Copyright (c) IPython Development Team. |
| 4 |
# Distributed under the terms of the Modified BSD License. |
| 5 |
|
| 6 |
import json |
| 7 |
import os |
| 8 |
import sys |
| 9 |
import threading |
| 10 |
import time |
| 11 |
from contextlib import contextmanager |
| 12 |
from subprocess import PIPE, Popen |
| 13 |
|
| 14 |
import pytest |
| 15 |
from jupyter_client.blocking.client import BlockingKernelClient |
| 16 |
from jupyter_core import paths |
| 17 |
|
| 18 |
from ipykernel.embed import IPKernelApp, embed_kernel # type:ignore[attr-defined] |
| 19 |
|
| 20 |
SETUP_TIMEOUT = 60 |
| 21 |
TIMEOUT = 15 |
| 22 |
|
| 23 |
|
| 24 |
if os.name == "nt": |
| 25 |
pytest.skip("skipping tests on windows", allow_module_level=True) |
| 26 |
|
| 27 |
|
| 28 |
@contextmanager |
| 29 |
def setup_kernel(cmd): |
| 30 |
"""start an embedded kernel in a subprocess, and wait for it to be ready |
| 31 |
|
| 32 |
Returns |
| 33 |
------- |
| 34 |
kernel_manager: connected KernelManager instance |
| 35 |
""" |
| 36 |
|
| 37 |
def connection_file_ready(connection_file): |
| 38 |
"""Check if connection_file is a readable json file.""" |
| 39 |
if not os.path.exists(connection_file): |
| 40 |
return False |
| 41 |
try: |
| 42 |
with open(connection_file) as f: |
| 43 |
json.load(f) |
| 44 |
return True |
| 45 |
except ValueError: |
| 46 |
return False |
| 47 |
|
| 48 |
kernel = Popen([sys.executable, "-c", cmd], stdout=PIPE, stderr=PIPE, encoding="utf-8") |
| 49 |
try: |
| 50 |
connection_file = os.path.join( |
| 51 |
paths.jupyter_runtime_dir(), |
| 52 |
"kernel-%i.json" % kernel.pid, |
| 53 |
) |
| 54 |
# wait for connection file to exist, timeout after 5s |
| 55 |
tic = time.time() |
| 56 |
while ( |
| 57 |
not connection_file_ready(connection_file) |
| 58 |
and kernel.poll() is None |
| 59 |
and time.time() < tic + SETUP_TIMEOUT |
| 60 |
): |
| 61 |
time.sleep(0.1) |
| 62 |
|
| 63 |
# Wait 100ms for the writing to finish |
| 64 |
time.sleep(0.1) |
| 65 |
|
| 66 |
if kernel.poll() is not None: |
| 67 |
_o, e = kernel.communicate() |
| 68 |
raise OSError("Kernel failed to start:\n%s" % e) |
| 69 |
|
| 70 |
if not os.path.exists(connection_file): |
| 71 |
if kernel.poll() is None: |
| 72 |
kernel.terminate() |
| 73 |
raise OSError("Connection file %r never arrived" % connection_file) |
| 74 |
|
| 75 |
client = BlockingKernelClient(connection_file=connection_file) |
| 76 |
client.load_connection_file() |
| 77 |
client.start_channels() |
| 78 |
client.wait_for_ready() |
| 79 |
try: |
| 80 |
yield client |
| 81 |
finally: |
| 82 |
client.stop_channels() |
| 83 |
finally: |
| 84 |
kernel.terminate() |
| 85 |
kernel.wait() |
| 86 |
# Make sure all the fds get closed. |
| 87 |
for attr in ["stdout", "stderr", "stdin"]: |
| 88 |
fid = getattr(kernel, attr) |
| 89 |
if fid: |
| 90 |
fid.close() |
| 91 |
|
| 92 |
|
| 93 |
@pytest.mark.flaky(max_runs=3) |
| 94 |
def test_embed_kernel_basic(): |
| 95 |
"""IPython.embed_kernel() is basically functional""" |
| 96 |
cmd = "\n".join( |
| 97 |
[ |
| 98 |
"from IPython import embed_kernel", |
| 99 |
"def go():", |
| 100 |
" a=5", |
| 101 |
' b="hi there"', |
| 102 |
" embed_kernel()", |
| 103 |
"go()", |
| 104 |
"", |
| 105 |
] |
| 106 |
) |
| 107 |
|
| 108 |
with setup_kernel(cmd) as client: |
| 109 |
# oinfo a (int) |
| 110 |
client.inspect("a") |
| 111 |
msg = client.get_shell_msg(timeout=TIMEOUT) |
| 112 |
content = msg["content"] |
| 113 |
assert content["found"] |
| 114 |
|
| 115 |
client.execute("c=a*2") |
| 116 |
msg = client.get_shell_msg(timeout=TIMEOUT) |
| 117 |
content = msg["content"] |
| 118 |
assert content["status"] == "ok" |
| 119 |
|
| 120 |
# oinfo c (should be 10) |
| 121 |
client.inspect("c") |
| 122 |
msg = client.get_shell_msg(timeout=TIMEOUT) |
| 123 |
content = msg["content"] |
| 124 |
assert content["found"] |
| 125 |
text = content["data"]["text/plain"] |
| 126 |
assert "10" in text |
| 127 |
|
| 128 |
|
| 129 |
@pytest.mark.flaky(max_runs=3) |
| 130 |
def test_embed_kernel_namespace(): |
| 131 |
"""IPython.embed_kernel() inherits calling namespace""" |
| 132 |
cmd = "\n".join( |
| 133 |
[ |
| 134 |
"from IPython import embed_kernel", |
| 135 |
"def go():", |
| 136 |
" a=5", |
| 137 |
' b="hi there"', |
| 138 |
" embed_kernel()", |
| 139 |
"go()", |
| 140 |
"", |
| 141 |
] |
| 142 |
) |
| 143 |
|
| 144 |
with setup_kernel(cmd) as client: |
| 145 |
# oinfo a (int) |
| 146 |
client.inspect("a") |
| 147 |
msg = client.get_shell_msg(timeout=TIMEOUT) |
| 148 |
content = msg["content"] |
| 149 |
assert content["found"] |
| 150 |
text = content["data"]["text/plain"] |
| 151 |
assert "5" in text |
| 152 |
|
| 153 |
# oinfo b (str) |
| 154 |
client.inspect("b") |
| 155 |
msg = client.get_shell_msg(timeout=TIMEOUT) |
| 156 |
content = msg["content"] |
| 157 |
assert content["found"] |
| 158 |
text = content["data"]["text/plain"] |
| 159 |
assert "hi there" in text |
| 160 |
|
| 161 |
# oinfo c (undefined) |
| 162 |
client.inspect("c") |
| 163 |
msg = client.get_shell_msg(timeout=TIMEOUT) |
| 164 |
content = msg["content"] |
| 165 |
assert not content["found"] |
| 166 |
|
| 167 |
|
| 168 |
@pytest.mark.flaky(max_runs=3) |
| 169 |
def test_embed_kernel_reentrant(): |
| 170 |
"""IPython.embed_kernel() can be called multiple times""" |
| 171 |
cmd = "\n".join( |
| 172 |
[ |
| 173 |
"from IPython import embed_kernel", |
| 174 |
"count = 0", |
| 175 |
"def go():", |
| 176 |
" global count", |
| 177 |
" embed_kernel()", |
| 178 |
" count = count + 1", |
| 179 |
"", |
| 180 |
"while True: go()", |
| 181 |
"", |
| 182 |
] |
| 183 |
) |
| 184 |
|
| 185 |
with setup_kernel(cmd) as client: |
| 186 |
for i in range(5): |
| 187 |
client.inspect("count") |
| 188 |
msg = client.get_shell_msg(timeout=TIMEOUT) |
| 189 |
content = msg["content"] |
| 190 |
assert content["found"] |
| 191 |
text = content["data"]["text/plain"] |
| 192 |
assert str(i) in text |
| 193 |
|
| 194 |
# exit from embed_kernel |
| 195 |
client.execute("get_ipython().exit_now = True") |
| 196 |
msg = client.get_shell_msg(timeout=TIMEOUT) |
| 197 |
time.sleep(0.2) |
| 198 |
|
| 199 |
|
| 200 |
def test_embed_kernel_func(): |
| 201 |
from types import ModuleType |
| 202 |
|
| 203 |
module = ModuleType("test") |
| 204 |
|
| 205 |
def trigger_stop(): |
| 206 |
time.sleep(1) |
| 207 |
app = IPKernelApp.instance() |
| 208 |
app.io_loop.add_callback(app.io_loop.stop) |
| 209 |
IPKernelApp.clear_instance() |
| 210 |
|
| 211 |
thread = threading.Thread(target=trigger_stop) |
| 212 |
thread.start() |
| 213 |
|
| 214 |
embed_kernel(module, outstream_class=None) |