SPB Git

Repository Public

test_client.py 16.4 KB 316 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr SMS Gateway7# File             : sdk/python/tests/test_client.py8# Description      : Tests unitaires (serveur HTTP local) et, si9#                    MACLUSTR_SMS_E2E=1, scénario de bout en bout contre un10#                    vrai backend.11# Module           : sdk12# Repository       : https://git.spboucher.ai/maclustr-sms13# Project Website  : https://sms.spboucher.ai14# Created          : 2026-11-3015# Last Modified    : 2026-11-3016#17# Author           : Simon-Pierre Boucher18# Position         : Professor of Finance19# Institution      : Université du Québec en Outaouais (UQO)20# Organization     : SP Boucher21# Website          : https://spboucher.ai22# Git              : https://git.spboucher.ai23#24# Preferred Contact: admin@spboucher.ai25# Technical Contact: dev@spboucher.ai26# Security/Admin   : admin@spboucher.ai27#28# Copyright (c) 202629# Simon-Pierre Boucher30# All rights reserved where applicable. This file is governed by the31# applicable project license, copyright notices and relevant law.32# Existing third-party rights and notices remain unaffected.33#34# License          : None specified (no license file in this repository)35#36# Do not embed credentials, private keys, access tokens,37# certificates or confidential personal information.38#39# =============================================================================40# END OF SP BOUCHER SOURCE HEADER41# =============================================================================4243"""Tests unitaires (serveur HTTP local) et, si MACLUSTR_SMS_E2E=1, scénario de bout en bout contre un vrai backend."""44import hashlib45import hmac46import json47import os48import threading49import time50import unittest51import urllib.parse52import urllib.request53from http.server import BaseHTTPRequestHandler, HTTPServer5455from maclustr_sms import MacLustrSMS, MacLustrSMSError, MacLustrSMSTimeout, WebhookVerificationError, verify_webhook565758class Stub(BaseHTTPRequestHandler):59    script = []      # réponses programmées : (status, corps, en-têtes)60    seen = []        # requêtes reçues6162    def log_message(self, *a):63        pass6465    def _handle(self):66        n = int(self.headers.get("Content-Length") or 0)67        body = self.rfile.read(n).decode() if n else ""68        Stub.seen.append({"method": self.command, "path": self.path, "headers": {k.lower(): v for k, v in self.headers.items()}, "body": json.loads(body) if body else None})69        status, payload, headers = Stub.script.pop(0) if Stub.script else (200, {}, {})70        raw = json.dumps(payload).encode()71        self.send_response(status)72        self.send_header("Content-Type", "application/json")73        self.send_header("Content-Length", str(len(raw)))74        for k, v in headers.items():75            self.send_header(k, v)76        self.end_headers()77        self.wfile.write(raw)7879    do_GET = do_POST = do_DELETE = _handle808182MSG = {"id": "sms_1", "direction": "outbound", "status": "queued", "to": "+14185550123", "from": "+14185550124", "text": "x", "segments": 1, "champ_futur": 1}838485class UnitTests(unittest.TestCase):86    @classmethod87    def setUpClass(cls):88        cls.srv = HTTPServer(("127.0.0.1", 0), Stub)89        threading.Thread(target=cls.srv.serve_forever, daemon=True).start()90        cls.url = f"http://127.0.0.1:{cls.srv.server_port}"9192    @classmethod93    def tearDownClass(cls):94        cls.srv.shutdown()95        cls.srv.server_close()9697    def setUp(self):98        Stub.script, Stub.seen = [], []99        self.slept = []100        self.sms = MacLustrSMS(api_key="mlsk_test", base_url=self.url, sleep=self.slept.append)101102    def test_send(self):103        Stub.script = [(201, MSG, {})]104        m = self.sms.send(to="+14185550123", text="x", sim_id="sim-1", from_="+14185550124")105        self.assertEqual((m.id, m.status, m.from_, m.replayed), ("sms_1", "queued", "+14185550124", False))106        self.assertEqual(m.raw["champ_futur"], 1)107        r = Stub.seen[0]108        self.assertEqual(r["headers"]["authorization"], "Bearer mlsk_test")109        self.assertEqual(r["body"], {"to": "+14185550123", "text": "x", "sim_id": "sim-1", "from": "+14185550124"})110        self.assertGreaterEqual(len(r["headers"]["idempotency-key"]), 16)111112    def test_retries_reuse_the_same_idempotency_key(self):113        Stub.script = [(503, {"error": {"code": "kill_switch_active", "message": "x"}}, {}), (429, {"error": {"code": "rate_limited", "message": "x"}}, {"Retry-After": "7"}), (200, MSG, {"Idempotent-Replayed": "true"})]114        m = self.sms.send(to="+14185550123", text="x")115        self.assertTrue(m.replayed)116        keys = {r["headers"]["idempotency-key"] for r in Stub.seen}117        self.assertEqual((len(Stub.seen), len(keys)), (3, 1))118        self.assertEqual(self.slept, [0.5, 7.0])119120    def test_no_retry_on_client_error(self):121        Stub.script = [(422, {"error": {"code": "invalid_phone_number", "message": "numéro invalide", "details": [1]}}, {})]122        with self.assertRaises(MacLustrSMSError) as c:123            self.sms.send(to="123", text="x")124        self.assertEqual((c.exception.status, c.exception.code, c.exception.message, c.exception.details), (422, "invalid_phone_number", "numéro invalide", [1]))125        self.assertEqual(len(Stub.seen), 1)126127    def test_gives_up_after_max_retries(self):128        Stub.script = [(500, {}, {})] * 4129        with self.assertRaises(MacLustrSMSError) as c:130            self.sms.get_message("sms_1")131        self.assertEqual((c.exception.status, len(Stub.seen)), (500, 4))132133    def test_network_error(self):134        sms = MacLustrSMS(api_key="k", base_url="http://127.0.0.1:1", max_retries=1, sleep=lambda s: None)135        with self.assertRaises(MacLustrSMSError) as c:136            sms.health()137        self.assertEqual((c.exception.status, c.exception.code), (0, "network_error"))138139    def test_pagination_iterator(self):140        Stub.script = [(200, {"data": [dict(MSG, id="a"), dict(MSG, id="b")], "has_more": True, "next_cursor": "c1"}, {}), (200, {"data": [dict(MSG, id="c")], "has_more": False, "next_cursor": None}, {})]141        self.assertEqual([m.id for m in self.sms.iter_messages(limit=2, status="queued")], ["a", "b", "c"])142        self.assertIn("cursor=c1", Stub.seen[1]["path"])143        self.assertIn("status=queued", Stub.seen[1]["path"])144145    def test_wait(self):146        Stub.script = [(200, dict(MSG, status="dispatched"), {}), (200, dict(MSG, status="submitted"), {})]147        self.assertEqual(self.sms.wait("sms_1").status, "submitted")148        Stub.script = [(200, dict(MSG, status="submitted"), {}), (200, dict(MSG, status="delivered"), {})]149        self.assertEqual(self.sms.wait("sms_1", until="final").status, "delivered")150        Stub.script = [(200, dict(MSG, status="queued"), {})]151        with self.assertRaises(MacLustrSMSTimeout) as c:152            self.sms.wait("sms_1", timeout=0.5)153        self.assertEqual(c.exception.message_obj.status, "queued")154155    def test_health_has_no_auth_header_and_key_required(self):156        Stub.script = [(200, {"status": "ok"}, {})]157        self.sms.health()158        self.assertNotIn("authorization", Stub.seen[0]["headers"])159        old = os.environ.pop("MACLUSTR_SMS_API_KEY", None)160        try:161            with self.assertRaises(ValueError):162                MacLustrSMS()163        finally:164            if old:165                os.environ["MACLUSTR_SMS_API_KEY"] = old166167    def test_verification_is_never_retried(self):168        ver = {"id": "ver_1", "to": "+14185550123", "status": "pending", "attempts": 0, "attempts_remaining": 5, "message_id": "sms_1", "message_status": "queued"}169        Stub.script = [(201, ver, {})]170        v = self.sms.start_verification("+14185550123", brand="Lou-Ka", locale="fr")171        self.assertEqual((v.id, v.status, v.attempts_remaining, v.message_status), ("ver_1", "pending", 5, "queued"))172        self.assertEqual(Stub.seen[0]["body"], {"to": "+14185550123", "brand": "Lou-Ka", "locale": "fr"})173        self.assertNotIn("idempotency-key", Stub.seen[0]["headers"])174        for status, payload, hdr in ((503, {}, {}), (429, {"error": {"code": "verification_too_soon", "message": "x"}}, {"Retry-After": "27"})):175            Stub.script, Stub.seen = [(status, payload, hdr), (201, ver, {})], []176            with self.assertRaises(MacLustrSMSError) as c:177                self.sms.start_verification("+14185550123")178            self.assertEqual((len(Stub.seen), c.exception.status), (1, status))179        self.assertEqual((c.exception.code, c.exception.retry_after), ("verification_too_soon", 27.0))180        Stub.script, Stub.seen = [(500, {}, {}), (200, dict(ver, valid=True), {})], []181        with self.assertRaises(MacLustrSMSError):182            self.sms.check_verification("ver_1", "123456")183        self.assertEqual(len(Stub.seen), 1)184        Stub.script, Stub.seen = [(200, dict(ver, status="approved", valid=True), {})], []185        chk = self.sms.check_verification("ver_1", 123456)186        self.assertTrue(chk.valid)187        self.assertEqual((Stub.seen[0]["path"], Stub.seen[0]["body"]), ("/v1/verifications/ver_1/check", {"code": "123456"}))188        Stub.script, Stub.seen = [(500, {}, {}), (200, ver, {})], []189        self.assertEqual(self.sms.get_verification("ver_1").status, "pending")     # la lecture, elle, est réessayée190        self.assertEqual(len(Stub.seen), 2)191192    def test_verify_webhook(self):193        body = '{"event":"sms.received","id":"evt_1","data":{"text":"é"}}'194        ts = str(int(time.time()))195        sig = "v1=" + hmac.new(b"whsec_x", f"{ts}.{body}".encode(), hashlib.sha256).hexdigest()196        self.assertEqual(verify_webhook("whsec_x", ts, body, sig)["event"], "sms.received")197        self.assertEqual(verify_webhook("whsec_x", ts, body.encode(), sig)["id"], "evt_1")198        for args in (("autre", ts, body, sig), ("whsec_x", ts, body + " ", sig), ("whsec_x", ts, body, "v1=00"), ("whsec_x", ts, body, ""), ("whsec_x", "abc", body, sig)):199            with self.assertRaises(WebhookVerificationError):200                verify_webhook(*args)201        old = str(int(time.time()) - 301)202        old_sig = "v1=" + hmac.new(b"whsec_x", f"{old}.{body}".encode(), hashlib.sha256).hexdigest()203        with self.assertRaises(WebhookVerificationError):204            verify_webhook("whsec_x", old, body, old_sig)205        self.assertEqual(verify_webhook("whsec_x", old, body, old_sig, tolerance=600)["id"], "evt_1")206207208@unittest.skipUnless(os.environ.get("MACLUSTR_SMS_E2E") == "1", "bout en bout : lancer sdk/tests-e2e/run.mjs")209class EndToEnd(unittest.TestCase):210    """Contre un vrai backend ; le téléphone est SIMULÉ (aucun SMS réel n'est émis)."""211212    def setUp(self):213        self.sms = MacLustrSMS()214        self.control = os.environ["E2E_CONTROL"]215        self.to = os.environ["E2E_TO"]216217    def control_get(self, path):218        with urllib.request.urlopen(self.control + path) as r:219            return json.loads(r.read())220221    def test_scenario(self):222        sms = self.sms223        self.assertEqual(sms.health()["status"], "ok")224        hook = sms.create_webhook(self.control + "/hook", ["sms.delivered", "sms.received"], description="python-e2e")225        self.assertTrue(hook.secret.startswith("whsec_"))226        try:227            m = sms.send(to=self.to, text="Notification MacLustr (python)", idempotency_key="py-e2e-1")228            self.assertIn(m.status, ("queued", "dispatched", "accepted", "submitting", "submitted", "delivered"))229            again = sms.send(to=self.to, text="Notification MacLustr (python)", idempotency_key="py-e2e-1")230            self.assertEqual((again.id, again.replayed), (m.id, True))231            done = sms.wait(m.id, timeout=20, until="final", interval=0.2)232            self.assertEqual(done.status, "delivered")233            self.assertEqual([e["to"] for e in done.events if not e["detail"].get("ignored")][-1], "delivered")234235            with self.assertRaises(MacLustrSMSError) as c:236                sms.send(to="12345", text="x")237            self.assertEqual((c.exception.status, c.exception.code), (422, "invalid_phone_number"))238            with self.assertRaises(MacLustrSMSError) as c:239                sms.send(to="+15145550111", text="x")240            self.assertEqual((c.exception.status, c.exception.code), (403, "recipient_not_allowed"))241            with self.assertRaises(MacLustrSMSError) as c:242                sms.cancel(m.id)243            self.assertEqual(c.exception.code, "not_cancellable")244245            for i in range(2):246                sms.send(to=self.to, text=f"page {i} (python)")247            page = sms.list_messages(limit=2)248            self.assertEqual((len(page), page.has_more), (2, True))249            ids = [x.id for x in sms.iter_messages(limit=2)]250            self.assertTrue(len(ids) >= 3 and len(set(ids)) == len(ids) and m.id in ids)251252            text = f"Réponse python {time.time()}"253            req = urllib.request.Request(self.control + "/receive", data=json.dumps({"from": self.to, "text": text}).encode(), headers={"Content-Type": "application/json"})254            urllib.request.urlopen(req).read()255            got = None256            for _ in range(50):257                got = next((x for x in sms.inbox(from_=self.to, limit=20) if x.text == text), None)258                if got:259                    break260                time.sleep(0.1)261            self.assertIsNotNone(got)262            self.assertEqual((got.status, got.direction, got.from_), ("received", "inbound", self.to))263            conv = next(c for c in sms.conversations() if c.peer == self.to)264            self.assertTrue(any(x.id == got.id for x in sms.conversation_messages(conv.id)))265266            # Vérification par code : le code n'est lisible que dans le SMS (ici : celui reçu par l'appareil simulé).267            vto = os.environ["E2E_VERIFY_TO"]268            v = sms.start_verification(vto, brand="Tests SDK", locale="fr")269            self.assertEqual((v.status, v.attempts_remaining, v.to), ("pending", 5, vto))270            with self.assertRaises(MacLustrSMSError) as c:271                sms.start_verification(vto)272            self.assertEqual((c.exception.status, c.exception.code), (429, "verification_too_soon"))273            self.assertTrue(0 < c.exception.retry_after <= 30)274            code = self.control_get("/code?to=" + urllib.parse.quote(vto))["code"]275            wrong = "%06d" % ((int(code) + 1) % 1000000)276            bad = sms.check_verification(v.id, wrong)277            self.assertEqual((bad.valid, bad.status, bad.attempts_remaining), (False, "pending", 4))278            good = sms.check_verification(v.id, code[:3] + " " + code[3:])279            self.assertEqual((good.valid, good.status), (True, "approved"))280            self.assertFalse(sms.check_verification(v.id, code).valid)       # usage unique281            self.assertEqual(sms.get_verification(v.id).status, "approved")282            with self.assertRaises(MacLustrSMSError) as c:283                sms.get_verification("ver_inconnu")284            self.assertEqual(c.exception.status, 404)285            self.assertNotIn(code, sms.get_message(v.message_id).text or "")   # le code n'est jamais relisible par l'API286287            dev = sms.devices()[0]288            self.assertTrue(dev.online and dev.sims[0].send_enabled)289            self.assertEqual(sms.device(dev.id).id, dev.id)290            self.assertEqual(sms.sims(dev.id)[0].id, dev.sims[0].id)291            self.assertEqual(sms.numbers()[0].sim_id, dev.sims[0].id)292            self.assertGreaterEqual(sms.usage()["quota"]["used_today"], 3)293            self.assertIn("pending", sms.queue())294295            mine = []296            for _ in range(80):297                mine = []298                for h in self.control_get("/hits"):299                    try:300                        ev = verify_webhook(hook.secret, h["headers"]["x-maclustr-timestamp"], h["body"], h["headers"]["x-maclustr-signature"])301                        mine.append(ev)302                    except WebhookVerificationError:303                        pass   # livraison destinée au webhook d'un autre SDK (autre secret)304                if {"sms.delivered", "sms.received"} <= {e["event"] for e in mine}:305                    break306                time.sleep(0.1)307            self.assertTrue(any(e["event"] == "sms.delivered" and e["data"]["id"] == m.id for e in mine))308            self.assertTrue(any(e["event"] == "sms.received" and e["data"]["text"] == text for e in mine))309            self.assertIn(hook.id, [w.id for w in sms.list_webhooks()])310        finally:311            self.assertTrue(sms.delete_webhook(hook.id))312313314if __name__ == "__main__":315    unittest.main()316
Files main
Menu

Theme