|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import importlib.util |
| 4 | +import json |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | +from clawbench.runner.run_support import email as native_email |
| 10 | + |
| 11 | +REPO_ROOT = Path(__file__).resolve().parents[1] |
| 12 | + |
| 13 | + |
| 14 | +class FakeResponse: |
| 15 | + def __init__(self, payload: object) -> None: |
| 16 | + self.payload = payload |
| 17 | + |
| 18 | + def __enter__(self): |
| 19 | + return self |
| 20 | + |
| 21 | + def __exit__(self, *_args) -> None: |
| 22 | + return None |
| 23 | + |
| 24 | + def read(self) -> bytes: |
| 25 | + return json.dumps(self.payload).encode() |
| 26 | + |
| 27 | + |
| 28 | +def load_harbor_script(name: str): |
| 29 | + path = REPO_ROOT / "src" / "clawbench" / "runtime" / "harbor" / name |
| 30 | + spec = importlib.util.spec_from_file_location(name.replace("-", "_"), path) |
| 31 | + assert spec and spec.loader |
| 32 | + module = importlib.util.module_from_spec(spec) |
| 33 | + spec.loader.exec_module(module) |
| 34 | + return module |
| 35 | + |
| 36 | + |
| 37 | +@pytest.mark.parametrize( |
| 38 | + "module", |
| 39 | + [ |
| 40 | + native_email, |
| 41 | + pytest.param(load_harbor_script("prepare-task.py"), id="harbor-prepare"), |
| 42 | + pytest.param(load_harbor_script("cleanup-email.py"), id="harbor-cleanup"), |
| 43 | + ], |
| 44 | +) |
| 45 | +def test_purelymail_api_errors_fail_closed(monkeypatch, module) -> None: |
| 46 | + monkeypatch.setattr( |
| 47 | + module, |
| 48 | + "urlopen", |
| 49 | + lambda *_args, **_kwargs: FakeResponse( |
| 50 | + { |
| 51 | + "type": "error", |
| 52 | + "code": "invalidToken", |
| 53 | + "message": "Token not valid.", |
| 54 | + } |
| 55 | + ), |
| 56 | + ) |
| 57 | + |
| 58 | + with pytest.raises( |
| 59 | + RuntimeError, |
| 60 | + match=r"PurelyMail createUser failed \(invalidToken\): Token not valid\.", |
| 61 | + ): |
| 62 | + module.purelymail_request("createUser", {}, "secret-token") |
| 63 | + |
| 64 | + |
| 65 | +def test_purelymail_rejects_non_object_responses(monkeypatch) -> None: |
| 66 | + monkeypatch.setattr( |
| 67 | + native_email, |
| 68 | + "urlopen", |
| 69 | + lambda *_args, **_kwargs: FakeResponse(["unexpected"]), |
| 70 | + ) |
| 71 | + |
| 72 | + with pytest.raises(RuntimeError, match="returned an invalid response"): |
| 73 | + native_email.purelymail_request("createUser", {}, "secret-token") |
0 commit comments