| 1 |
|
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import inspect |
| 5 |
import os |
| 6 |
import subprocess |
| 7 |
import sys |
| 8 |
import textwrap |
| 9 |
from dataclasses import dataclass |
| 10 |
from io import BytesIO |
| 11 |
from pathlib import Path |
| 12 |
from typing import Any |
| 13 |
from typing import Callable |
| 14 |
|
| 15 |
import pytest |
| 16 |
|
| 17 |
import execnet |
| 18 |
from execnet import gateway |
| 19 |
from execnet import gateway_base |
| 20 |
from execnet import gateway_io |
| 21 |
from execnet.gateway_base import ChannelFactory |
| 22 |
from execnet.gateway_base import ExecModel |
| 23 |
from execnet.gateway_base import Message |
| 24 |
from execnet.gateway_base import Popen2IO |
| 25 |
|
| 26 |
skip_win_pypy = pytest.mark.xfail( |
| 27 |
condition=hasattr(sys, "pypy_version_info") and sys.platform.startswith("win"), |
| 28 |
reason="failing on Windows on PyPy (#63)", |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
@pytest.mark.parametrize("val", ["123", 42, [1, 2, 3], ["23", 25]]) |
| 33 |
class TestSerializeAPI: |
| 34 |
def test_serializer_api(self, val: object) -> None: |
| 35 |
dumped = execnet.dumps(val) |
| 36 |
val2 = execnet.loads(dumped) |
| 37 |
assert val == val2 |
| 38 |
|
| 39 |
def test_mmap(self, tmp_path: Path, val: object) -> None: |
| 40 |
mmap = pytest.importorskip("mmap").mmap |
| 41 |
p = tmp_path / "data.bin" |
| 42 |
|
| 43 |
p.write_bytes(execnet.dumps(val)) |
| 44 |
with p.open("r+b") as f: |
| 45 |
m = mmap(f.fileno(), 0) |
| 46 |
val2 = execnet.load(m) |
| 47 |
assert val == val2 |
| 48 |
|
| 49 |
def test_bytesio(self, val: object) -> None: |
| 50 |
f = BytesIO() |
| 51 |
execnet.dump(f, val) |
| 52 |
read = BytesIO(f.getvalue()) |
| 53 |
val2 = execnet.load(read) |
| 54 |
assert val == val2 |
| 55 |
|
| 56 |
|
| 57 |
def test_serializer_api_version_error(monkeypatch: pytest.MonkeyPatch) -> None: |
| 58 |
bchr = gateway_base.bchr |
| 59 |
monkeypatch.setattr(gateway_base, "DUMPFORMAT_VERSION", bchr(1)) |
| 60 |
dumped = execnet.dumps(42) |
| 61 |
monkeypatch.setattr(gateway_base, "DUMPFORMAT_VERSION", bchr(2)) |
| 62 |
pytest.raises(execnet.DataFormatError, lambda: execnet.loads(dumped)) |
| 63 |
|
| 64 |
|
| 65 |
def test_errors_on_execnet() -> None: |
| 66 |
assert hasattr(execnet, "RemoteError") |
| 67 |
assert hasattr(execnet, "TimeoutError") |
| 68 |
assert hasattr(execnet, "DataFormatError") |
| 69 |
|
| 70 |
|
| 71 |
def test_subprocess_interaction(anypython: str) -> None: |
| 72 |
line = gateway_io.popen_bootstrapline |
| 73 |
compile(line, "xyz", "exec") |
| 74 |
args = [str(anypython), "-c", line] |
| 75 |
popen = subprocess.Popen( |
| 76 |
args, |
| 77 |
bufsize=0, |
| 78 |
universal_newlines=True, |
| 79 |
stdin=subprocess.PIPE, |
| 80 |
stdout=subprocess.PIPE, |
| 81 |
) |
| 82 |
|
| 83 |
assert popen.stdin is not None |
| 84 |
assert popen.stdout is not None |
| 85 |
|
| 86 |
def send(line: str) -> None: |
| 87 |
assert popen.stdin is not None |
| 88 |
popen.stdin.write(line) |
| 89 |
popen.stdin.flush() |
| 90 |
|
| 91 |
def receive() -> str: |
| 92 |
assert popen.stdout is not None |
| 93 |
return popen.stdout.readline() |
| 94 |
|
| 95 |
try: |
| 96 |
source = inspect.getsource(read_write_loop) + "read_write_loop()" |
| 97 |
send(repr(source) + "\n") |
| 98 |
s = receive() |
| 99 |
assert s == "ok\n" |
| 100 |
send("hello\n") |
| 101 |
s = receive() |
| 102 |
assert s == "received: hello\n" |
| 103 |
send("world\n") |
| 104 |
s = receive() |
| 105 |
assert s == "received: world\n" |
| 106 |
send("\n") |
| 107 |
finally: |
| 108 |
popen.stdin.close() |
| 109 |
popen.stdout.close() |
| 110 |
popen.wait() |
| 111 |
|
| 112 |
|
| 113 |
def read_write_loop() -> None: |
| 114 |
sys.stdout.write("ok\n") |
| 115 |
sys.stdout.flush() |
| 116 |
while 1: |
| 117 |
try: |
| 118 |
line = sys.stdin.readline() |
| 119 |
if not line.strip(): |
| 120 |
break |
| 121 |
sys.stdout.write("received: %s" % line) |
| 122 |
sys.stdout.flush() |
| 123 |
except (OSError, EOFError): |
| 124 |
break |
| 125 |
|
| 126 |
|
| 127 |
IO_MESSAGE_EXTRA_SOURCE = """ |
| 128 |
import sys |
| 129 |
backend = sys.argv[1] |
| 130 |
from io import BytesIO |
| 131 |
import tempfile |
| 132 |
temp_out = BytesIO() |
| 133 |
temp_in = BytesIO() |
| 134 |
io = Popen2IO(temp_out, temp_in, get_execmodel(backend)) |
| 135 |
for i, handler in enumerate(Message._types): |
| 136 |
print ("checking", i, handler) |
| 137 |
for data in "hello", "hello".encode('ascii'): |
| 138 |
msg1 = Message(i, i, dumps(data)) |
| 139 |
msg1.to_io(io) |
| 140 |
x = io.outfile.getvalue() |
| 141 |
io.outfile.truncate(0) |
| 142 |
io.outfile.seek(0) |
| 143 |
io.infile.seek(0) |
| 144 |
io.infile.write(x) |
| 145 |
io.infile.seek(0) |
| 146 |
msg2 = Message.from_io(io) |
| 147 |
assert msg1.channelid == msg2.channelid, (msg1, msg2) |
| 148 |
assert msg1.data == msg2.data, (msg1.data, msg2.data) |
| 149 |
assert msg1.msgcode == msg2.msgcode |
| 150 |
print ("all passed") |
| 151 |
""" |
| 152 |
|
| 153 |
|
| 154 |
@dataclass |
| 155 |
class Checker: |
| 156 |
python: str |
| 157 |
path: Path |
| 158 |
idx: int = 0 |
| 159 |
|
| 160 |
def run_check( |
| 161 |
self, script: str, *extra_args: str, **process_args: Any |
| 162 |
) -> subprocess.CompletedProcess[str]: |
| 163 |
self.idx += 1 |
| 164 |
check_path = self.path / f"check{self.idx}.py" |
| 165 |
check_path.write_text(script) |
| 166 |
return subprocess.run( |
| 167 |
[self.python, os.fspath(check_path), *extra_args], |
| 168 |
capture_output=True, |
| 169 |
text=True, |
| 170 |
check=True, |
| 171 |
**process_args, |
| 172 |
) |
| 173 |
|
| 174 |
|
| 175 |
@pytest.fixture |
| 176 |
def checker(anypython: str, tmp_path: Path) -> Checker: |
| 177 |
return Checker(python=anypython, path=tmp_path) |
| 178 |
|
| 179 |
|
| 180 |
def test_io_message(checker: Checker, execmodel: ExecModel) -> None: |
| 181 |
out = checker.run_check( |
| 182 |
inspect.getsource(gateway_base) + IO_MESSAGE_EXTRA_SOURCE, execmodel.backend |
| 183 |
) |
| 184 |
print(out.stdout) |
| 185 |
assert "all passed" in out.stdout |
| 186 |
|
| 187 |
|
| 188 |
def test_popen_io(checker: Checker, execmodel: ExecModel) -> None: |
| 189 |
out = checker.run_check( |
| 190 |
inspect.getsource(gateway_base) |
| 191 |
+ f""" |
| 192 |
io = init_popen_io(get_execmodel({execmodel.backend!r})) |
| 193 |
io.write(b"hello") |
| 194 |
s = io.read(1) |
| 195 |
assert s == b"x" |
| 196 |
""", |
| 197 |
input="x", |
| 198 |
) |
| 199 |
print(out.stderr) |
| 200 |
assert "hello" in out.stdout |
| 201 |
|
| 202 |
|
| 203 |
def test_popen_io_readloop(execmodel: ExecModel) -> None: |
| 204 |
sio = BytesIO(b"test") |
| 205 |
io = Popen2IO(sio, sio, execmodel) |
| 206 |
real_read = io._read |
| 207 |
|
| 208 |
def newread(numbytes: int) -> bytes: |
| 209 |
if numbytes > 1: |
| 210 |
numbytes = numbytes - 1 |
| 211 |
return real_read(numbytes) |
| 212 |
|
| 213 |
io._read = newread |
| 214 |
result = io.read(3) |
| 215 |
assert result == b"tes" |
| 216 |
|
| 217 |
|
| 218 |
def test_rinfo_source(checker: Checker) -> None: |
| 219 |
out = checker.run_check( |
| 220 |
f""" |
| 221 |
class Channel: |
| 222 |
def send(self, data): |
| 223 |
assert eval(repr(data), {{}}) == data |
| 224 |
channel = Channel() |
| 225 |
{inspect.getsource(gateway.rinfo_source)} |
| 226 |
print ('all passed') |
| 227 |
""" |
| 228 |
) |
| 229 |
|
| 230 |
print(out.stdout) |
| 231 |
assert "all passed" in out.stdout |
| 232 |
|
| 233 |
|
| 234 |
def test_geterrortext(checker: Checker) -> None: |
| 235 |
out = checker.run_check( |
| 236 |
inspect.getsource(gateway_base) |
| 237 |
+ """ |
| 238 |
class Arg(Exception): |
| 239 |
pass |
| 240 |
errortext = geterrortext(Arg()) |
| 241 |
assert "Arg" in errortext |
| 242 |
try: |
| 243 |
raise ValueError("17") |
| 244 |
except ValueError as exc: |
| 245 |
s = geterrortext(exc) |
| 246 |
assert "17" in s |
| 247 |
print ("all passed") |
| 248 |
""" |
| 249 |
) |
| 250 |
print(out.stdout) |
| 251 |
assert "all passed" in out.stdout |
| 252 |
|
| 253 |
|
| 254 |
@pytest.mark.skipif("not hasattr(os, 'dup')") |
| 255 |
def test_stdouterrin_setnull( |
| 256 |
execmodel: ExecModel, capfd: pytest.CaptureFixture[str] |
| 257 |
) -> None: |
| 258 |
|
| 259 |
|
| 260 |
orig_stdin = sys.stdin |
| 261 |
orig_stdin_fd = os.dup(0) |
| 262 |
try: |
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
gateway_base.init_popen_io(execmodel) |
| 268 |
os.write(1, b"hello") |
| 269 |
os.read(0, 1) |
| 270 |
out, err = capfd.readouterr() |
| 271 |
assert not out |
| 272 |
assert not err |
| 273 |
finally: |
| 274 |
sys.stdin = orig_stdin |
| 275 |
os.dup2(orig_stdin_fd, 0) |
| 276 |
os.close(orig_stdin_fd) |
| 277 |
|
| 278 |
|
| 279 |
class PseudoChannel: |
| 280 |
class gateway: |
| 281 |
class _channelfactory: |
| 282 |
finished = False |
| 283 |
|
| 284 |
def __init__(self) -> None: |
| 285 |
self._sent: list[object] = [] |
| 286 |
self._closed: list[str | None] = [] |
| 287 |
self.id = 1000 |
| 288 |
|
| 289 |
def send(self, obj: object) -> None: |
| 290 |
self._sent.append(obj) |
| 291 |
|
| 292 |
def close(self, errortext: str | None = None) -> None: |
| 293 |
self._closed.append(errortext) |
| 294 |
|
| 295 |
|
| 296 |
def test_exectask(execmodel: ExecModel) -> None: |
| 297 |
io = BytesIO() |
| 298 |
io.execmodel = execmodel |
| 299 |
gw = gateway_base.WorkerGateway(io, id="something") |
| 300 |
ch = PseudoChannel() |
| 301 |
gw.executetask((ch, ("raise ValueError()", None, {}))) |
| 302 |
assert "ValueError" in str(ch._closed[0]) |
| 303 |
|
| 304 |
|
| 305 |
class TestMessage: |
| 306 |
def test_wire_protocol(self) -> None: |
| 307 |
for i, handler in enumerate(Message._types): |
| 308 |
one = BytesIO() |
| 309 |
data = b"23" |
| 310 |
|
| 311 |
Message(i, 42, data).to_io(one) |
| 312 |
two = BytesIO(one.getvalue()) |
| 313 |
msg = Message.from_io(two) |
| 314 |
assert msg.msgcode == i |
| 315 |
assert isinstance(msg, Message) |
| 316 |
assert msg.channelid == 42 |
| 317 |
assert msg.data == data |
| 318 |
assert isinstance(repr(msg), str) |
| 319 |
|
| 320 |
|
| 321 |
class TestPureChannel: |
| 322 |
@pytest.fixture |
| 323 |
def fac(self, execmodel: ExecModel) -> ChannelFactory: |
| 324 |
class FakeGateway: |
| 325 |
def _trace(self, *args) -> None: |
| 326 |
pass |
| 327 |
|
| 328 |
def _send(self, *k) -> None: |
| 329 |
pass |
| 330 |
|
| 331 |
FakeGateway.execmodel = execmodel |
| 332 |
return ChannelFactory(FakeGateway()) |
| 333 |
|
| 334 |
def test_factory_create(self, fac: ChannelFactory) -> None: |
| 335 |
chan1 = fac.new() |
| 336 |
assert chan1.id == 1 |
| 337 |
chan2 = fac.new() |
| 338 |
assert chan2.id == 3 |
| 339 |
|
| 340 |
def test_factory_getitem(self, fac: ChannelFactory) -> None: |
| 341 |
chan1 = fac.new() |
| 342 |
assert fac._channels[chan1.id] == chan1 |
| 343 |
chan2 = fac.new() |
| 344 |
assert fac._channels[chan2.id] == chan2 |
| 345 |
|
| 346 |
def test_channel_timeouterror(self, fac: ChannelFactory) -> None: |
| 347 |
channel = fac.new() |
| 348 |
pytest.raises(IOError, channel.waitclose, timeout=0.01) |
| 349 |
|
| 350 |
def test_channel_makefile_incompatmode(self, fac) -> None: |
| 351 |
channel = fac.new() |
| 352 |
with pytest.raises(ValueError): |
| 353 |
channel.makefile("rw") |
| 354 |
|
| 355 |
|
| 356 |
class TestSourceOfFunction: |
| 357 |
def test_lambda_unsupported(self) -> None: |
| 358 |
pytest.raises(ValueError, gateway._source_of_function, lambda: 1) |
| 359 |
|
| 360 |
def test_wrong_prototype_fails(self) -> None: |
| 361 |
def prototype(wrong) -> None: |
| 362 |
pass |
| 363 |
|
| 364 |
pytest.raises(ValueError, gateway._source_of_function, prototype) |
| 365 |
|
| 366 |
def test_function_without_known_source_fails(self) -> None: |
| 367 |
|
| 368 |
mess: dict[str, Any] = {} |
| 369 |
exec("def fail(channel): pass", mess, mess) |
| 370 |
print(inspect.getsourcefile(mess["fail"])) |
| 371 |
with pytest.raises(ValueError): |
| 372 |
gateway._source_of_function(mess["fail"]) |
| 373 |
|
| 374 |
def test_function_with_closure_fails(self) -> None: |
| 375 |
mess: dict[str, Any] = {} |
| 376 |
|
| 377 |
def closure(channel: object) -> None: |
| 378 |
print(mess) |
| 379 |
|
| 380 |
with pytest.raises(ValueError): |
| 381 |
gateway._source_of_function(closure) |
| 382 |
|
| 383 |
def test_source_of_nested_function(self) -> None: |
| 384 |
def working(channel: object) -> None: |
| 385 |
pass |
| 386 |
|
| 387 |
send_source = gateway._source_of_function(working).lstrip("\r\n") |
| 388 |
expected = "def working(channel: object) -> None:\n pass\n" |
| 389 |
assert send_source == expected |
| 390 |
|
| 391 |
|
| 392 |
class TestGlobalFinder: |
| 393 |
def check(self, func) -> list[str]: |
| 394 |
src = textwrap.dedent(inspect.getsource(func)) |
| 395 |
code = func.__code__ |
| 396 |
return gateway._find_non_builtin_globals(src, code) |
| 397 |
|
| 398 |
def test_local(self) -> None: |
| 399 |
def f(a, b, c): |
| 400 |
d = 3 |
| 401 |
return d |
| 402 |
|
| 403 |
assert self.check(f) == [] |
| 404 |
|
| 405 |
def test_global(self) -> None: |
| 406 |
def f(a, b): |
| 407 |
sys |
| 408 |
d = 4 |
| 409 |
return d |
| 410 |
|
| 411 |
assert self.check(f) == ["sys"] |
| 412 |
|
| 413 |
def test_builtin(self) -> None: |
| 414 |
def f() -> None: |
| 415 |
len |
| 416 |
|
| 417 |
assert self.check(f) == [] |
| 418 |
|
| 419 |
def test_function_with_global_fails(self) -> None: |
| 420 |
def func(channel) -> None: |
| 421 |
sys |
| 422 |
|
| 423 |
pytest.raises(ValueError, gateway._source_of_function, func) |
| 424 |
|
| 425 |
def test_method_call(self) -> None: |
| 426 |
|
| 427 |
|
| 428 |
def f(channel): |
| 429 |
channel.send(dict(testing=2)) |
| 430 |
|
| 431 |
assert self.check(f) == [] |
| 432 |
|
| 433 |
|
| 434 |
@skip_win_pypy |
| 435 |
def test_remote_exec_function_with_kwargs( |
| 436 |
anypython: str, makegateway: Callable[[str], gateway.Gateway] |
| 437 |
) -> None: |
| 438 |
def func(channel, data) -> None: |
| 439 |
channel.send(data) |
| 440 |
|
| 441 |
gw = makegateway("popen//python=%s" % anypython) |
| 442 |
print(f"local version_info {sys.version_info!r}") |
| 443 |
print(f"remote info: {gw._rinfo()}") |
| 444 |
ch = gw.remote_exec(func, data=1) |
| 445 |
result = ch.receive() |
| 446 |
assert result == 1 |
| 447 |
|
| 448 |
|
| 449 |
def test_remote_exc__no_kwargs(makegateway: Callable[[], gateway.Gateway]) -> None: |
| 450 |
gw = makegateway() |
| 451 |
with pytest.raises(TypeError): |
| 452 |
gw.remote_exec(gateway_base, kwarg=1) |
| 453 |
with pytest.raises(TypeError): |
| 454 |
gw.remote_exec("pass", kwarg=1) |
| 455 |
|
| 456 |
|
| 457 |
@skip_win_pypy |
| 458 |
def test_remote_exec_inspect_stack( |
| 459 |
makegateway: Callable[[], gateway.Gateway], |
| 460 |
) -> None: |
| 461 |
gw = makegateway() |
| 462 |
ch = gw.remote_exec( |
| 463 |
""" |
| 464 |
import inspect |
| 465 |
inspect.stack() |
| 466 |
import traceback |
| 467 |
channel.send('\\n'.join(traceback.format_stack())) |
| 468 |
""" |
| 469 |
) |
| 470 |
received = ch.receive() |
| 471 |
assert isinstance(received, str) |
| 472 |
assert 'File "<remote exec>"' in received |
| 473 |
ch.waitclose() |