| 1 |
"""Tests for kernel connection utilities""" |
| 2 |
|
| 3 |
# Copyright (c) Jupyter Development Team. |
| 4 |
# Distributed under the terms of the Modified BSD License. |
| 5 |
import json |
| 6 |
import os |
| 7 |
from tempfile import TemporaryDirectory |
| 8 |
|
| 9 |
import pytest |
| 10 |
from jupyter_core.application import JupyterApp |
| 11 |
from jupyter_core.paths import jupyter_runtime_dir |
| 12 |
|
| 13 |
from jupyter_client import KernelClient, KernelManager, connect |
| 14 |
from jupyter_client.consoleapp import JupyterConsoleApp |
| 15 |
from jupyter_client.session import Session |
| 16 |
|
| 17 |
|
| 18 |
class TemporaryWorkingDirectory(TemporaryDirectory): |
| 19 |
""" |
| 20 |
Creates a temporary directory and sets the cwd to that directory. |
| 21 |
Automatically reverts to previous cwd upon cleanup. |
| 22 |
Usage example: |
| 23 |
|
| 24 |
with TemporaryWorkingDirectory() as tmpdir: |
| 25 |
... |
| 26 |
""" |
| 27 |
|
| 28 |
def __enter__(self): |
| 29 |
self.old_wd = os.getcwd() |
| 30 |
os.chdir(self.name) |
| 31 |
return super().__enter__() |
| 32 |
|
| 33 |
def __exit__(self, exc, value, tb): |
| 34 |
os.chdir(self.old_wd) |
| 35 |
return super().__exit__(exc, value, tb) |
| 36 |
|
| 37 |
|
| 38 |
class DummyConsoleApp(JupyterApp, JupyterConsoleApp): # type:ignore |
| 39 |
def initialize(self, argv=None): |
| 40 |
JupyterApp.initialize(self, argv=argv or []) |
| 41 |
self.init_connection_file() |
| 42 |
|
| 43 |
|
| 44 |
class DummyConfigurable(connect.ConnectionFileMixin): |
| 45 |
def initialize(self): |
| 46 |
pass |
| 47 |
|
| 48 |
|
| 49 |
sample_info: dict = dict( |
| 50 |
ip="1.2.3.4", |
| 51 |
transport="ipc", |
| 52 |
shell_port=1, |
| 53 |
hb_port=2, |
| 54 |
iopub_port=3, |
| 55 |
stdin_port=4, |
| 56 |
control_port=5, |
| 57 |
key=b"abc123", |
| 58 |
signature_scheme="hmac-md5", |
| 59 |
kernel_name="python", |
| 60 |
) |
| 61 |
|
| 62 |
sample_info_kn: dict = dict( |
| 63 |
ip="1.2.3.4", |
| 64 |
transport="ipc", |
| 65 |
shell_port=1, |
| 66 |
hb_port=2, |
| 67 |
iopub_port=3, |
| 68 |
stdin_port=4, |
| 69 |
control_port=5, |
| 70 |
key=b"abc123", |
| 71 |
signature_scheme="hmac-md5", |
| 72 |
kernel_name="test", |
| 73 |
) |
| 74 |
|
| 75 |
|
| 76 |
def test_write_connection_file(): |
| 77 |
with TemporaryDirectory() as d: |
| 78 |
cf = os.path.join(d, "kernel.json") |
| 79 |
connect.write_connection_file(cf, **sample_info) |
| 80 |
assert os.path.exists(cf) |
| 81 |
with open(cf) as f: |
| 82 |
info = json.load(f) |
| 83 |
info["key"] = info["key"].encode() |
| 84 |
assert info == sample_info |
| 85 |
|
| 86 |
|
| 87 |
def test_load_connection_file_session(): |
| 88 |
"""test load_connection_file() after""" |
| 89 |
session = Session() |
| 90 |
app = DummyConsoleApp(session=Session()) |
| 91 |
app.initialize(argv=[]) |
| 92 |
session = app.session |
| 93 |
|
| 94 |
with TemporaryDirectory() as d: |
| 95 |
cf = os.path.join(d, "kernel.json") |
| 96 |
connect.write_connection_file(cf, **sample_info) |
| 97 |
app.connection_file = cf |
| 98 |
app.load_connection_file() |
| 99 |
|
| 100 |
assert session.key == sample_info["key"] |
| 101 |
assert session.signature_scheme == sample_info["signature_scheme"] |
| 102 |
|
| 103 |
|
| 104 |
def test_load_connection_file_session_with_kn(): |
| 105 |
"""test load_connection_file() after""" |
| 106 |
session = Session() |
| 107 |
app = DummyConsoleApp(session=Session()) |
| 108 |
app.initialize(argv=[]) |
| 109 |
session = app.session |
| 110 |
|
| 111 |
with TemporaryDirectory() as d: |
| 112 |
cf = os.path.join(d, "kernel.json") |
| 113 |
connect.write_connection_file(cf, **sample_info_kn) |
| 114 |
app.connection_file = cf |
| 115 |
app.load_connection_file() |
| 116 |
|
| 117 |
assert session.key == sample_info_kn["key"] |
| 118 |
assert session.signature_scheme == sample_info_kn["signature_scheme"] |
| 119 |
|
| 120 |
|
| 121 |
def test_app_load_connection_file(): |
| 122 |
"""test `ipython console --existing` loads a connection file""" |
| 123 |
with TemporaryDirectory() as d: |
| 124 |
cf = os.path.join(d, "kernel.json") |
| 125 |
connect.write_connection_file(cf, **sample_info) |
| 126 |
app = DummyConsoleApp(connection_file=cf) |
| 127 |
app.initialize(argv=[]) |
| 128 |
|
| 129 |
for attr, expected in sample_info.items(): |
| 130 |
if attr in ("key", "signature_scheme"): |
| 131 |
continue |
| 132 |
value = getattr(app, attr) |
| 133 |
assert value == expected, f"app.{attr} = {value} != {expected}" |
| 134 |
|
| 135 |
|
| 136 |
def test_load_connection_info(): |
| 137 |
client = KernelClient() |
| 138 |
info: dict = { |
| 139 |
"control_port": 53702, |
| 140 |
"hb_port": 53705, |
| 141 |
"iopub_port": 53703, |
| 142 |
"ip": "0.0.0.0", # noqa |
| 143 |
"key": "secret", |
| 144 |
"shell_port": 53700, |
| 145 |
"signature_scheme": "hmac-sha256", |
| 146 |
"stdin_port": 53701, |
| 147 |
"transport": "tcp", |
| 148 |
} |
| 149 |
client.load_connection_info(info) |
| 150 |
assert client.control_port == info["control_port"] |
| 151 |
assert client.session.key.decode("ascii") == info["key"] |
| 152 |
assert client.ip == info["ip"] |
| 153 |
|
| 154 |
|
| 155 |
def test_find_connection_file(): |
| 156 |
with TemporaryDirectory() as d: |
| 157 |
cf = "kernel.json" |
| 158 |
app = DummyConsoleApp(runtime_dir=d, connection_file=cf) |
| 159 |
app.initialize() |
| 160 |
|
| 161 |
security_dir = app.runtime_dir |
| 162 |
profile_cf = os.path.join(security_dir, cf) |
| 163 |
|
| 164 |
with open(profile_cf, "w") as f: |
| 165 |
f.write("{}") |
| 166 |
|
| 167 |
for query in ( |
| 168 |
"kernel.json", |
| 169 |
"kern*", |
| 170 |
"*ernel*", |
| 171 |
"k*", |
| 172 |
): |
| 173 |
assert connect.find_connection_file(query, path=security_dir) == profile_cf |
| 174 |
|
| 175 |
|
| 176 |
def test_find_connection_file_local(): |
| 177 |
with TemporaryWorkingDirectory(): |
| 178 |
cf = "test.json" |
| 179 |
abs_cf = os.path.abspath(cf) |
| 180 |
with open(cf, "w") as f: |
| 181 |
f.write("{}") |
| 182 |
|
| 183 |
for query in ( |
| 184 |
"test.json", |
| 185 |
"test", |
| 186 |
abs_cf, |
| 187 |
os.path.join(".", "test.json"), |
| 188 |
): |
| 189 |
assert connect.find_connection_file(query, path=[".", jupyter_runtime_dir()]) == abs_cf |
| 190 |
|
| 191 |
|
| 192 |
def test_find_connection_file_relative(): |
| 193 |
with TemporaryWorkingDirectory(): |
| 194 |
cf = "test.json" |
| 195 |
os.mkdir("subdir") |
| 196 |
cf = os.path.join("subdir", "test.json") |
| 197 |
abs_cf = os.path.abspath(cf) |
| 198 |
with open(cf, "w") as f: |
| 199 |
f.write("{}") |
| 200 |
|
| 201 |
for query in ( |
| 202 |
os.path.join(".", "subdir", "test.json"), |
| 203 |
os.path.join("subdir", "test.json"), |
| 204 |
abs_cf, |
| 205 |
): |
| 206 |
assert connect.find_connection_file(query, path=[".", jupyter_runtime_dir()]) == abs_cf |
| 207 |
|
| 208 |
|
| 209 |
def test_find_connection_file_abspath(): |
| 210 |
with TemporaryDirectory(): |
| 211 |
cf = "absolute.json" |
| 212 |
abs_cf = os.path.abspath(cf) |
| 213 |
with open(cf, "w") as f: |
| 214 |
f.write("{}") |
| 215 |
assert connect.find_connection_file(abs_cf, path=jupyter_runtime_dir()) == abs_cf |
| 216 |
os.remove(abs_cf) |
| 217 |
|
| 218 |
|
| 219 |
def test_mixin_record_random_ports(): |
| 220 |
with TemporaryDirectory() as d: |
| 221 |
dc = DummyConfigurable(data_dir=d, kernel_name="via-tcp", transport="tcp") |
| 222 |
dc.write_connection_file() |
| 223 |
|
| 224 |
assert dc._connection_file_written |
| 225 |
assert os.path.exists(dc.connection_file) |
| 226 |
assert dc._random_port_names == connect.port_names |
| 227 |
|
| 228 |
|
| 229 |
def test_mixin_cleanup_random_ports(): |
| 230 |
with TemporaryDirectory() as d: |
| 231 |
dc = DummyConfigurable(data_dir=d, kernel_name="via-tcp", transport="tcp") |
| 232 |
dc.write_connection_file() |
| 233 |
filename = dc.connection_file |
| 234 |
dc.cleanup_random_ports() |
| 235 |
|
| 236 |
assert not os.path.exists(filename) |
| 237 |
for name in dc._random_port_names: # type:ignore |
| 238 |
assert getattr(dc, name) == 0 |
| 239 |
|
| 240 |
|
| 241 |
param_values = [ |
| 242 |
(True, True), |
| 243 |
(True, False), |
| 244 |
(False, True), |
| 245 |
(False, False), |
| 246 |
] |
| 247 |
|
| 248 |
|
| 249 |
@pytest.mark.parametrize("file_exists, km_matches", param_values) |
| 250 |
def test_reconcile_connection_info(file_exists, km_matches): |
| 251 |
expected_info = sample_info |
| 252 |
mismatched_info = sample_info.copy() |
| 253 |
mismatched_info["key"] = b"def456" |
| 254 |
mismatched_info["shell_port"] = expected_info["shell_port"] + 42 |
| 255 |
mismatched_info["control_port"] = expected_info["control_port"] + 42 |
| 256 |
|
| 257 |
with TemporaryDirectory() as connection_dir: |
| 258 |
cf = os.path.join(connection_dir, "kernel.json") |
| 259 |
km = KernelManager() |
| 260 |
km.connection_file = cf |
| 261 |
|
| 262 |
if file_exists: |
| 263 |
_, info = connect.write_connection_file(cf, **expected_info) |
| 264 |
# set 'key' back to bytes |
| 265 |
info["key"] = info["key"].encode() # type:ignore |
| 266 |
|
| 267 |
if km_matches: |
| 268 |
# Let this be the case where the connection file exists, and the KM has matching |
| 269 |
# values prior to reconciliation. This is the LocalProvisioner case. |
| 270 |
provisioner_info = info |
| 271 |
km.load_connection_info(provisioner_info) |
| 272 |
else: |
| 273 |
# Let this be the case where the connection file exists, and the KM has those values |
| 274 |
# that differ from the ones returned by the provisioner. This is the restart-with- |
| 275 |
# changed-ports case (typical for remote provisioners). |
| 276 |
km.load_connection_info(expected_info) |
| 277 |
provisioner_info = mismatched_info |
| 278 |
else: # connection file does not exist |
| 279 |
if km_matches: |
| 280 |
# Let this be the case where the connection file does not exist, NOR does the KM |
| 281 |
# have any values of its own and reconciliation sets those values. This is the |
| 282 |
# non-LocalProvisioner case. |
| 283 |
provisioner_info = expected_info |
| 284 |
else: |
| 285 |
# Let this be the case where the connection file does not exist, yet the KM |
| 286 |
# has values that do not match those returned from the provisioner. This case |
| 287 |
# is probably not practical and is equivalent to the True, False case. |
| 288 |
km.load_connection_info(expected_info) |
| 289 |
provisioner_info = mismatched_info |
| 290 |
|
| 291 |
km._reconcile_connection_info(provisioner_info) |
| 292 |
km_info = km.get_connection_info() |
| 293 |
assert km._equal_connections(km_info, provisioner_info) |