import json import pytest from pydantic import BaseModel from src.worker import NonEmptyStr, WorkerRequest, run_handler from src.worker.subprocess import WORKER_REQUEST class _Request(WorkerRequest): bucket: NonEmptyStr class _Result(BaseModel): is_valid: bool class TestRunHandler: def test_handler_invoked_with_parsed_request( self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: monkeypatch.setenv(WORKER_REQUEST, json.dumps({"task_token": "tok", "bucket": "b"})) captured: dict[str, _Request] = {} def handler(request: _Request) -> _Result: captured["request"] = request return _Result(is_valid=True) run_handler(_Request, handler) assert captured["request"] == _Request(task_token="tok", bucket="b") assert json.loads(capsys.readouterr().out) == {"is_valid": True} def test_handler_exception_emits_error_output_and_exits_one( self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: monkeypatch.setenv(WORKER_REQUEST, json.dumps({"task_token": "tok", "bucket": "b"})) def handler(_: _Request) -> _Result: raise RuntimeError("boom") with pytest.raises(SystemExit) as exc_info: run_handler(_Request, handler) assert exc_info.value.code == 1 captured = capsys.readouterr() assert json.loads(captured.out) == {"error": "RuntimeError", "message": "boom"} assert "RuntimeError: boom" in captured.err def test_custom_exception_class_name_preserved( self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: monkeypatch.setenv(WORKER_REQUEST, json.dumps({"task_token": "tok", "bucket": "b"})) class MyDomainError(Exception): pass def handler(_: _Request) -> _Result: raise MyDomainError("specific message") with pytest.raises(SystemExit): run_handler(_Request, handler) result = json.loads(capsys.readouterr().out) assert result == {"error": "MyDomainError", "message": "specific message"} def test_invalid_request_json_emits_error_output( self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: monkeypatch.setenv(WORKER_REQUEST, "{not valid json") def handler(_: _Request) -> _Result: raise AssertionError("handler should not be called") with pytest.raises(SystemExit) as exc_info: run_handler(_Request, handler) assert exc_info.value.code == 1 result = json.loads(capsys.readouterr().out) assert result["error"] == "ValidationError"