SPB Git

Repository Public

test_unit.py 10.7 KB 224 lines python

1"""Client behaviour with a scripted transport: no network. Run: python3 -m unittest discover -s tests (from packages/sdk-python)."""2from __future__ import annotations34import hashlib5import hmac6import json7import os8import subprocess9import sys10import time11import unittest12from pathlib import Path1314ROOT = Path(__file__).resolve().parent.parent15sys.path.insert(0, str(ROOT / "src"))1617import spmail  # noqa: E40218from spmail import SPMail  # noqa: E402192021def ok(body, status=200, headers=None):22    return status, {"content-type": "application/json", "x-request-id": "req_test", **(headers or {})}, json.dumps(body).encode()232425def err(status, code, headers=None):26    return ok({"error": {"code": code, "message": f"msg {code}", "details": {"n": 1}}}, status, headers)272829class Fake:30    """Scripted transport: a queue of answers (or exceptions) and a log of calls."""3132    def __init__(self, *script):33        self.script = list(script)34        self.calls = []3536    def __call__(self, method, url, headers, body, timeout):37        self.calls.append({"method": method, "url": url, "headers": headers, "body": body, "timeout": timeout})38        nxt = self.script.pop(0)39        if isinstance(nxt, BaseException):40            raise nxt41        return nxt424344def client(fake, **kw):45    c = SPMail("spm_unit_test", "http://localhost:1", transport=fake, **kw)46    c._http._sleep = lambda s: slept.append(s)  # no real waiting in unit tests47    return c484950slept: list = []515253class Construction(unittest.TestCase):54    def test_key_required_and_http_refused(self):55        with self.assertRaises(ValueError):56            SPMail("")57        with self.assertRaisesRegex(ValueError, "plain http"):58            SPMail("spm_x", "http://mail.example.org")59        self.assertEqual(SPMail("spm_x").base_url, "https://mail.spboucher.ai/api/v1")60        self.assertEqual(SPMail("spm_x", "https://h.example/api/v1/").base_url, "https://h.example/api/v1")6162    def test_environment(self):63        old = dict(os.environ)64        try:65            os.environ["SPMAIL_API_KEY"] = "spm_env"66            os.environ["SPMAIL_BASE_URL"] = "http://127.0.0.1:9"67            self.assertEqual(SPMail().base_url, "http://127.0.0.1:9/api/v1")68        finally:69            os.environ.clear()70            os.environ.update(old)7172    def test_key_never_in_repr_or_errors(self):73        f = Fake(err(401, "invalid_api_key"))74        c = SPMail("spm_secretsecret_value", "http://localhost:1", transport=f)75        self.assertNotIn("secretsecret", repr(c) + repr(c._http) + repr(c.messages))76        with self.assertRaises(spmail.AuthenticationError) as cm:77            c.me()78        self.assertNotIn("secretsecret", str(cm.exception) + repr(cm.exception) + repr(vars(cm.exception)))79        self.assertEqual(f.calls[0]["headers"]["Authorization"], "Bearer spm_secretsecret_value")808182class Errors(unittest.TestCase):83    def test_typed_errors(self):84        cases = [(400, "invalid_request", spmail.BadRequestError), (401, "key_revoked", spmail.AuthenticationError),85                 (403, "insufficient_scope", spmail.PermissionDeniedError), (404, "not_found", spmail.NotFoundError),86                 (409, "idempotency_conflict", spmail.ConflictError), (429, "daily_send_limit_exceeded", spmail.RateLimitError),87                 (500, "internal", spmail.ServerError)]88        for status, code, cls in cases:89            with self.assertRaises(cls) as cm:90                client(Fake(err(status, code)), max_retries=0).messages.get("msg_x")91            e = cm.exception92            self.assertIsInstance(e, spmail.SPMailError)93            self.assertEqual((e.status, e.code, e.message, e.details, e.request_id), (status, code, f"msg {code}", {"n": 1}, "req_test"))9495    def test_legacy_envelope_and_non_json(self):96        with self.assertRaises(spmail.PermissionDeniedError) as cm:97            client(Fake(ok({"error": "reauth_required", "message": "again"}, 403))).me()98        self.assertEqual((cm.exception.code, cm.exception.message), ("reauth_required", "again"))99        with self.assertRaises(spmail.ServerError) as cm:100            client(Fake((502, {}, b"<html>")), max_retries=0).me()101        self.assertEqual(cm.exception.code, "http_error")102103104class Retries(unittest.TestCase):105    def setUp(self):106        slept.clear()107108    def test_429_honours_retry_after(self):109        f = Fake(err(429, "rate_limited", {"retry-after": "2"}), ok({"type": "key"}))110        client(f).me()111        self.assertEqual(len(f.calls), 2)112        self.assertTrue(2 <= slept[0] <= 2.25)113114    def test_429_too_long_or_daily_limit_is_raised(self):115        f = Fake(err(429, "rate_limited", {"retry-after": "3600"}))116        with self.assertRaises(spmail.RateLimitError) as cm:117            client(f).me()118        self.assertEqual((cm.exception.retry_after, len(f.calls)), (3600.0, 1))119        f = Fake(err(429, "daily_send_limit_exceeded", {"retry-after": "1"}))120        with self.assertRaises(spmail.RateLimitError):121            client(f).messages.send(from_="a@x", to=["b@x"], text="x")122        self.assertEqual(len(f.calls), 1)123124    def test_get_retries_5xx_and_network_with_backoff(self):125        f = Fake(err(503, "mail_server_unavailable"), OSError("connection reset"), ok({"data": [], "next_cursor": None, "has_more": False}))126        client(f).messages.list()127        self.assertEqual(len(f.calls), 3)128        self.assertTrue(0.25 <= slept[0] <= 0.5 and 0.5 <= slept[1] <= 1.0, slept)129        f = Fake(err(502, "mail_server_error"), err(502, "mail_server_error"))130        with self.assertRaises(spmail.ServerError):131            client(f, max_retries=1).me()132        self.assertEqual(len(f.calls), 2)133134    def test_post_reuses_one_idempotency_key(self):135        f = Fake(OSError("reset"), err(504, "x"), ok({"id": "msg_out_1", "status": "sent"}))136        client(f).messages.send(from_="a@x", to=["b@x"], text="x")137        keys = [c["headers"]["Idempotency-Key"] for c in f.calls]138        self.assertEqual(len(keys), 3)139        self.assertRegex(keys[0], r"^sdk-[0-9a-f-]{36}$")140        self.assertEqual(len(set(keys)), 1)141        self.assertEqual(json.loads(f.calls[0]["body"]), {"from": "a@x", "to": ["b@x"], "text": "x"})142        f = Fake(ok({}), ok({}), ok({}))143        c = client(f)144        c.messages.send(from_="a@x", to=["b@x"], text="x")145        c.messages.send({"from": "a@x", "to": ["b@x"], "text": "x"})146        c.messages.send(from_="a@x", to=["b@x"], text="x", idempotency_key="order-42")147        self.assertNotEqual(f.calls[0]["headers"]["Idempotency-Key"], f.calls[1]["headers"]["Idempotency-Key"])148        self.assertEqual(f.calls[2]["headers"]["Idempotency-Key"], "order-42")149        with self.assertRaises(ValueError):150            c.messages.send(from_="a@x", to=["b@x"], text="x", idempotency_key="é\n")151152    def test_non_idempotent_requests_are_not_retried(self):153        f = Fake(err(503, "mail_server_unavailable"))154        with self.assertRaises(spmail.ServerError):155            client(f).files.upload(b"x", filename="a.txt")156        self.assertEqual(len(f.calls), 1)157        self.assertNotIn("Idempotency-Key", f.calls[0]["headers"])158        f = Fake(OSError("reset"))159        with self.assertRaises(spmail.ConnectionError):160            client(f).drafts.update("msg_x", subject="x")161        self.assertEqual(len(f.calls), 1)162        f = Fake(TimeoutError("timed out"))163        with self.assertRaises(spmail.TimeoutError) as cm:164            client(f, max_retries=0).me()165        self.assertEqual(cm.exception.code, "timeout")166167    def test_idempotency_in_progress_is_retried(self):168        f = Fake(err(409, "idempotency_in_progress"), ok({"id": "msg_out_1"}))169        client(f).messages.send(from_="a@x", to=["b@x"], text="x")170        self.assertEqual(len(f.calls), 2)171172173class Pagination(unittest.TestCase):174    def test_iterate_follows_cursor_and_encodes_filters(self):175        page = lambda ids, nxt: ok({"data": [{"id": i} for i in ids], "next_cursor": nxt, "has_more": nxt is not None})  # noqa: E731176        f = Fake(page(["1", "2"], "c1"), page([], "c2"), page(["3"], None))177        seen = [m["id"] for m in client(f).messages.iterate(folder="inbox", unread=True, address=["a@x", "b@x"], from_="z@x", limit=2)]178        self.assertEqual(seen, ["1", "2", "3"])179        self.assertEqual(f.calls[0]["url"], "http://localhost:1/api/v1/messages?folder=inbox&unread=true&address=a%40x%2Cb%40x&from=z%40x&limit=2")180        self.assertTrue(f.calls[1]["url"].endswith("cursor=c1") and f.calls[2]["url"].endswith("cursor=c2"))181182183class WaitForDelivery(unittest.TestCase):184    def test_polls_until_final_and_times_out(self):185        f = Fake(ok({"id": "o", "status": "sent"}), ok({"id": "o", "status": "delivered"}))186        self.assertEqual(client(f).wait_for_delivery("o", timeout=5, interval=0.1)["status"], "delivered")187        f = Fake(*[ok({"id": "o", "status": "pending_approval"})] * 5)188        with self.assertRaises(spmail.TimeoutError) as cm:189            client(f).wait_for_delivery("o", timeout=0.25, interval=0.1)190        self.assertEqual(cm.exception.details["last"]["status"], "pending_approval")191192193class Signature(unittest.TestCase):194    def test_verify(self):195        secret = "whsec_test_secret"196        payload = json.dumps({"id": "evt_1", "type": "message.received", "data": {}})197        header = spmail.sign_webhook_payload(payload, secret)198        ts = header.split(",")[0][2:]199        reference = hmac.new(secret.encode(), f"{ts}.{payload}".encode(), hashlib.sha256).hexdigest()  # docs/API.md 11.4200        self.assertEqual(header, f"t={ts},v1={reference}")201        self.assertTrue(spmail.verify_webhook_signature(payload, header, secret))202        self.assertTrue(spmail.verify_webhook_signature(payload.encode(), header, secret))203        self.assertFalse(spmail.verify_webhook_signature(payload + " ", header, secret))204        self.assertFalse(spmail.verify_webhook_signature(payload, header, "whsec_other"))205        self.assertFalse(spmail.verify_webhook_signature(payload, None, secret))206        self.assertFalse(spmail.verify_webhook_signature(payload, "v1=abc", secret))207        old = spmail.sign_webhook_payload(payload, secret, timestamp=time.time() - 301)208        self.assertFalse(spmail.verify_webhook_signature(payload, old, secret))209        self.assertTrue(spmail.verify_webhook_signature(payload, old, secret, tolerance=600))210        self.assertEqual(spmail.construct_event(payload, header, secret)["type"], "message.received")211        with self.assertRaises(spmail.SignatureVerificationError):212            spmail.construct_event(payload, old, secret)213214215class Generated(unittest.TestCase):216    def test_generated_types_are_up_to_date(self):217        r = subprocess.run([sys.executable, str(ROOT / "scripts/generate_types.py"), "--check"], capture_output=True, text=True)218        self.assertEqual(r.returncode, 0, r.stderr)219        self.assertEqual(spmail.OPERATION_SCOPES["getMessagesId"], ["mail.read"])220221222if __name__ == "__main__":223    unittest.main()224
Files main
Menu

Theme