58 lines
1.8 KiB
Python
58 lines
1.8 KiB
Python
"""Process boundary failures must stay bounded and map to contract errors."""
|
|
|
|
import signal
|
|
import subprocess
|
|
from io import BytesIO
|
|
|
|
import pytest
|
|
|
|
from messenger.attachments import validate_image
|
|
from messenger.domain import Failure
|
|
|
|
|
|
class FakeProcess:
|
|
pid = 999999999
|
|
returncode = 0
|
|
|
|
def __init__(self, output=b'{"ok":["image/png",1,1]}', crash=False, timeout=False):
|
|
self.output, self.timeout, self.calls = output, timeout, 0
|
|
self.returncode = -11 if crash else 0
|
|
|
|
def __enter__(self):
|
|
return self
|
|
|
|
def __exit__(self, *args):
|
|
pass
|
|
|
|
def communicate(self, input=None, timeout=None):
|
|
self.calls += 1
|
|
if self.timeout and self.calls == 1:
|
|
raise subprocess.TimeoutExpired("validator", 5)
|
|
return self.output, b""
|
|
|
|
|
|
def test_timeout_kills_group_and_returns_415(monkeypatch):
|
|
process = FakeProcess(timeout=True)
|
|
killed = []
|
|
monkeypatch.setattr("messenger.attachments.subprocess.Popen", lambda *a, **k: process)
|
|
monkeypatch.setattr(
|
|
"messenger.attachments.os.killpg", lambda pid, sig: killed.append((pid, sig))
|
|
)
|
|
with pytest.raises(Failure) as failure:
|
|
validate_image(BytesIO(b"synthetic"), "image/png")
|
|
assert failure.value.status == 415
|
|
assert killed == [(process.pid, signal.SIGKILL)]
|
|
assert process.calls == 2
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"output,crash", [(b"", True), (b"not-json", False), (b"null", False), (b"[]", False)]
|
|
)
|
|
def test_crash_or_malformed_child_result_returns_415(monkeypatch, output, crash):
|
|
monkeypatch.setattr(
|
|
"messenger.attachments.subprocess.Popen", lambda *a, **k: FakeProcess(output, crash=crash)
|
|
)
|
|
with pytest.raises(Failure) as failure:
|
|
validate_image(BytesIO(b"synthetic"), "image/png")
|
|
assert failure.value.status == 415
|