Repository Public
1# =============================================================================2# SP BOUCHER | INFRASTRUCTURE & AUTOMATION3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : MacLustr Identity7# File : sdk/python/tests/test_client.py8# Module : sdk9# Repository : https://git.spboucher.ai/maclustr-identity10# Project Website : https://identity.spboucher.ai11# Created : 2026-12-0112# Last Modified : 2026-12-0113#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: admin@spboucher.ai22# Technical Contact: dev@spboucher.ai23# Security/Admin : admin@spboucher.ai24#25# Copyright (c) 202626# Simon-Pierre Boucher27# All rights reserved where applicable. This file is governed by the28# applicable project license, copyright notices and relevant law.29# Existing third-party rights and notices remain unaffected.30#31# License : None specified (no license file in this repository)32#33# Do not embed credentials, private keys, access tokens,34# certificates or confidential personal information.35#36# =============================================================================37# END OF SP BOUCHER SOURCE HEADER38# =============================================================================3940import asyncio41import json4243import httpx44import pytest4546from maclustr_identity import (APIConnectionError, APIServerError, AsyncMacLustrIdentity, AuthenticationError, ConflictError, InvalidRequestError,47 MacLustrIdentity, MacLustrIdentityError, NotFoundError, PermissionDeniedError, RateLimitError, backoff_delay, should_retry)4849SESSION = {"id": "vs_1", "object": "verification_session", "status": "created", "livemode": False, "external_user_id": "u1", "purpose": "p",50 "verification_policy": "identity_document_face_v1", "policy_version": "1.0", "locale": "fr-CA", "return_url": None, "method": None, "metadata": {},51 "verification_id": None, "created_at": "2026-12-01T09:00:00-05:00", "expires_at": "2026-12-01T10:00:00-05:00", "completed_at": None}52CREATED = {**SESSION, "client_secret": "vsc_x", "url": "http://identity.test/verify/vs_1#vsc_x"}535455def ver(vid: str, **over):56 return {"verification_id": vid, "object": "verification", "session_id": "vs_" + vid, "status": "verified", "assurance_level": "document_check",57 "method": "document_only", "verification_policy": "identity_document_v1", "policy_version": "1.0", "livemode": False, "simulated": False,58 "external_user_id": "u1", "reasons": [], "dimensions": {}, "decision_engine": "risk-1.0", "created_at": "2026-12-01T09:00:00-05:00",59 "verified_at": "2026-12-01T09:00:00-05:00", "expires_at": None, "revoked_at": None, "personal_data_deleted_at": None, **over}606162def err(status: int, code: str, headers: dict | None = None, **extra):63 return httpx.Response(status, json={"error": {"type": "x_error", "code": code, "message": f"m-{code}", "request_id": "req_body", **extra}}, headers=headers)646566class Script:67 """A scripted transport: each call consumes the next step (the last one repeats)."""6869 def __init__(self, *steps):70 self.steps, self.calls, self.waits = list(steps), [], []7172 def handler(self, request: httpx.Request) -> httpx.Response:73 self.calls.append(request)74 step = self.steps[min(len(self.calls) - 1, len(self.steps) - 1)]75 if isinstance(step, Exception):76 raise step77 return step(request) if callable(step) else step7879 def sync(self, **kw) -> MacLustrIdentity:80 c = MacLustrIdentity("mlid_sk_test_unit", base_url="http://identity.test/", http_client=httpx.Client(transport=httpx.MockTransport(self.handler)), **kw)81 c._sleep = self.waits.append82 return c8384 def asynchronous(self, **kw) -> AsyncMacLustrIdentity:85 c = AsyncMacLustrIdentity("mlid_sk_test_unit", base_url="http://identity.test/", http_client=httpx.AsyncClient(transport=httpx.MockTransport(self.handler)), **kw)8687 async def nosleep(s: float) -> None:88 self.waits.append(s)89 c._sleep = nosleep90 return c919293def ok(body) -> httpx.Response:94 return httpx.Response(200, json=body, headers={"request-id": "req_test"})959697# ------------------------------------------------------------------ construction9899def test_requires_a_well_formed_secret_key_and_never_prints_it():100 with pytest.raises(MacLustrIdentityError, match="api_key is required"):101 MacLustrIdentity("")102 with pytest.raises(MacLustrIdentityError, match="mlid_sk_test_ or mlid_sk_live_"):103 MacLustrIdentity("vsc_abc")104 c = MacLustrIdentity("mlid_sk_live_hidden")105 assert c.livemode and c.base_url == "https://identity.spboucher.ai"106 assert "hidden" not in repr(c) and "hidden" not in str(vars(c).keys() - {"_BaseClient__api_key"}) and "hidden" not in repr(AsyncMacLustrIdentity("mlid_sk_test_hidden"))107108109# ------------------------------------------------------------------ requests110111def test_sends_bearer_key_json_body_and_returns_typed_object():112 s = Script(ok(CREATED))113 out = s.sync().verification_sessions.create(purpose="p", external_user_id="u1", metadata={"k": 1})114 r = s.calls[0]115 assert (r.method, str(r.url)) == ("POST", "http://identity.test/v1/verification-sessions")116 assert r.headers["authorization"] == "Bearer mlid_sk_test_unit"117 assert json.loads(r.content) == {"purpose": "p", "external_user_id": "u1", "metadata": {"k": 1}}118 assert out.id == "vs_1" and out.client_secret == "vsc_x" and out.url.endswith("#vsc_x") and out.status == "created"119 assert "vsc_x" not in repr(out)120121122def test_encodes_query_and_path():123 s = Script(ok({"object": "list", "data": [], "has_more": False}), ok(ver("ver_1")))124 c = s.sync()125 c.verifications.list(external_user_id="a b&c", status="verified", limit=5)126 assert dict(s.calls[0].url.params) == {"external_user_id": "a b&c", "status": "verified", "limit": "5"}127 c.verifications.retrieve("ver/../x")128 assert s.calls[1].url.raw_path == b"/v1/verifications/ver%2F..%2Fx"129 with pytest.raises(MacLustrIdentityError):130 c.verifications.retrieve("")131132133# ------------------------------------------------------------------ idempotency134135def test_idempotency_key_on_posts_only_overridable_and_stable_across_retries():136 s = Script(ok(CREATED), ok(CREATED), ok(SESSION), ok({"verification_id": "ver_1", "deleted": True}), ok(CREATED))137 c = s.sync()138 c.verification_sessions.create(purpose="p")139 c.verification_sessions.create(purpose="p")140 c.verification_sessions.retrieve("vs_1")141 c.verifications.delete_personal_data("ver_1")142 c.verification_sessions.create(purpose="p", idempotency_key="order-42")143 k0, k1 = s.calls[0].headers["idempotency-key"], s.calls[1].headers["idempotency-key"]144 assert k0.startswith("sdk-") and len(k0) == 40 and k0 != k1145 assert "idempotency-key" not in s.calls[2].headers and "idempotency-key" not in s.calls[3].headers146 assert s.calls[4].headers["idempotency-key"] == "order-42"147148 s = Script(err(503, "unavailable"), httpx.ConnectError("boom"), ok(CREATED))149 s.sync().verification_sessions.create(purpose="p")150 assert len(s.calls) == 3 and len({r.headers["idempotency-key"] for r in s.calls}) == 1151152153# ------------------------------------------------------------------ retries154155def test_retries_5xx_with_exponential_backoff_and_jitter():156 s = Script(err(500, "internal_error"), err(502, "bad_gateway"), ok(SESSION))157 c = s.sync()158 c._random = lambda: 1.0159 assert c.verification_sessions.retrieve("vs_1").id == "vs_1"160 assert len(s.calls) == 3 and s.waits == [0.5, 1.0]161 assert backoff_delay(0, 0.0) == 0.25 and backoff_delay(0, 1.0) == 0.5 and backoff_delay(3, 1.0) == 4.0 and backoff_delay(10, 1.0) == 8.0162 assert all(1.0 <= backoff_delay(2) <= 2.0 for _ in range(50))163164165def test_retries_network_errors_and_timeouts():166 s = Script(httpx.ConnectError("refused"), httpx.ReadTimeout("slow"), ok(SESSION))167 assert s.sync().verification_sessions.retrieve("vs_1").id == "vs_1"168 assert len(s.calls) == 3169170171def test_honours_retry_after_on_429():172 s = Script(err(429, "rate_limited", headers={"Retry-After": "7"}), ok(SESSION))173 s.sync().verification_sessions.retrieve("vs_1")174 assert len(s.calls) == 2 and s.waits == [7.0]175176177def test_gives_up_after_max_retries():178 s = Script(err(503, "unavailable"))179 with pytest.raises(APIServerError):180 s.sync().verification_sessions.retrieve("vs_1")181 assert len(s.calls) == 3182 s = Script(httpx.ConnectError("refused"))183 with pytest.raises(APIConnectionError) as e:184 s.sync(max_retries=1).verification_sessions.retrieve("vs_1")185 assert len(s.calls) == 2 and e.value.status is None and e.value.code == "connection_failed" and isinstance(e.value.__cause__, httpx.ConnectError)186 s = Script(httpx.ReadTimeout("slow"))187 with pytest.raises(APIConnectionError) as e:188 s.sync(max_retries=0).verification_sessions.retrieve("vs_1")189 assert e.value.code == "request_timeout"190 s = Script(err(429, "rate_limited", headers={"Retry-After": "3"}))191 with pytest.raises(RateLimitError) as e:192 s.sync(max_retries=0).verification_sessions.retrieve("vs_1")193 assert e.value.retry_after == 3.0194195196@pytest.mark.parametrize("status", [400, 401, 403, 404, 409, 413, 422])197def test_never_retries_client_errors(status):198 s = Script(err(status, "nope"))199 with pytest.raises(MacLustrIdentityError):200 s.sync().verification_sessions.create(purpose="p")201 assert len(s.calls) == 1 and s.waits == []202203204def test_webhook_creation_and_rotation_are_retried_with_the_same_key():205 """The service deduplicates these calls on the Idempotency-Key: a retry returns the first result."""206 s = Script(err(503, "service_unavailable"), ok({"id": "we_1", "secret": "whsec_2"}))207 assert s.sync().webhooks.rotate_secret("we_1").secret == "whsec_2" and len(s.calls) == 2208 assert s.calls[0].headers["idempotency-key"].startswith("sdk-") and s.calls[0].headers["idempotency-key"] == s.calls[1].headers["idempotency-key"]209 s = Script(httpx.ConnectError("down"), ok({"id": "we_1", "object": "webhook_endpoint", "secret": "whsec_1"}))210 assert s.sync().webhooks.create(url="https://app.example/hook").secret == "whsec_1" and len(s.calls) == 2211 assert s.calls[0].headers["idempotency-key"] == s.calls[1].headers["idempotency-key"] and s.calls[0].content == s.calls[1].content212 s = Script(err(503, "service_unavailable"))213 with pytest.raises(APIServerError):214 s.sync().webhooks.rotate_secret("we_1", max_retries=0)215 assert len(s.calls) == 1216 s = Script(ok({"id": "we_1", "secret": "whsec_2"}))217 c = s.sync()218 c.webhooks.rotate_secret("we_1"), c.webhooks.rotate_secret("we_1")219 assert s.calls[0].headers["idempotency-key"] != s.calls[1].headers["idempotency-key"] # two calls, two rotations220221222def test_honours_retry_after_on_503_and_caps_it():223 s = Script(err(503, "service_unavailable", headers={"Retry-After": "5"}), ok(CREATED))224 s.sync().verification_sessions.create(purpose="p")225 assert s.waits == [5.0]226 s = Script(err(503, "service_unavailable", headers={"Retry-After": "5"}))227 with pytest.raises(APIServerError) as e:228 s.sync(max_retries=0).verification_sessions.retrieve("vs_1")229 assert (e.value.status, e.value.code, e.value.retry_after) == (503, "service_unavailable", 5.0)230 s = Script(err(429, "rate_limited", headers={"Retry-After": "86400"}), ok(SESSION))231 s.sync().verification_sessions.retrieve("vs_1")232 assert s.waits == [60.0]233 s = Script(err(500, "internal_error"), ok(SESSION))234 c = s.sync()235 c._random = lambda: 1.0236 c.verification_sessions.retrieve("vs_1")237 assert s.waits == [0.5] # no Retry-After: exponential backoff238239240@pytest.mark.parametrize("status,code,cls", [(413, "payload_too_large", InvalidRequestError), (411, "length_required", InvalidRequestError),241 (400, "invalid_cursor", InvalidRequestError), (403, "forbidden_network", PermissionDeniedError),242 (404, "resource_missing", NotFoundError)])243def test_new_transport_errors_are_typed_and_never_retried(status, code, cls):244 s = Script(err(status, code))245 with pytest.raises(cls) as e:246 s.sync().webhooks.rotate_secret("we_other_mode")247 assert (e.value.status, e.value.code) == (status, code) and len(s.calls) == 1248249250def test_models_tolerate_unknown_fields_statuses_and_scoreless_dimensions():251 body = ver("ver_1", status="some_future_status", a_new_field={"x": 1}, dimensions={"document": {"status": "pass"}, "face": {"status": "review", "notes": ["n"]}, "odd": "pass"},252 reasons=[{"code": "review_not_completed", "message": {"fr": "a", "en": "b"}}, {"code": "future_code"}, "garbage", {"code": "x", "message": "not a dict"}])253 v = Script(ok(body)).sync().verifications.retrieve("ver_1")254 assert v.status == "some_future_status" and not v.is_valid and v.raw["a_new_field"] == {"x": 1}255 assert v.dimensions == {"document": {"status": "pass"}, "face": {"status": "review", "notes": ["n"]}, "odd": {"status": "pass"}}256 assert v.reason_codes == ["review_not_completed", "future_code", "x"] and v.reasons[1].message == {} and v.reasons[2].message == {}257 sparse = Script(ok({"verification_id": "ver_2", "reasons": None, "dimensions": None, "expires_at": "not a date"})).sync().verifications.retrieve("ver_2")258 assert sparse.status is None and sparse.reasons == [] and sparse.dimensions == {} and not sparse.is_valid259 s = Script(ok({"id": "vs_9", "status": "brand_new_status", "extra": True})).sync().verification_sessions.retrieve("vs_9")260 assert s.status == "brand_new_status" and s.purpose is None and s.metadata == {}261262263def test_daily_quota_is_not_retried_and_policy_is_pure():264 for code in ("daily_session_limit", "too_many_uploads", "too_many_challenges"):265 s = Script(err(429, code))266 with pytest.raises(RateLimitError):267 s.sync().verification_sessions.create(purpose="p")268 assert len(s.calls) == 1 and not should_retry(429, code)269 assert should_retry(None) and should_retry(429) and should_retry(500) and should_retry(599)270 assert not any(should_retry(x) for x in (200, 301, 400, 401, 403, 404, 409, 422))271272273# ------------------------------------------------------------------ errors274275@pytest.mark.parametrize("status,cls", [(400, InvalidRequestError), (401, AuthenticationError), (403, PermissionDeniedError), (404, NotFoundError),276 (409, ConflictError), (413, InvalidRequestError), (429, RateLimitError), (500, APIServerError)])277def test_error_mapping(status, cls):278 s = Script(err(status, "some_code", param="purpose"))279 with pytest.raises(cls) as e:280 s.sync(max_retries=0).verification_sessions.create(purpose="p")281 x = e.value282 assert isinstance(x, MacLustrIdentityError) and (x.status, x.type, x.code, x.param, x.request_id, x.message) == (status, "x_error", "some_code", "purpose", "req_body", "m-some_code")283 assert str(x) == "m-some_code"284285286def test_non_envelope_error_and_non_json_success():287 s = Script(httpx.Response(404, text="<html>", headers={"request-id": "req_hdr"}))288 with pytest.raises(NotFoundError) as e:289 s.sync().verification_sessions.retrieve("x")290 assert e.value.request_id == "req_hdr" and e.value.message == "HTTP 404"291 s = Script(httpx.Response(200, text="<html>"))292 with pytest.raises(MacLustrIdentityError) as e2:293 s.sync().verification_sessions.retrieve("x")294 assert e2.value.code == "invalid_response" and len(s.calls) == 1295296297# ------------------------------------------------------------------ pagination, is_user_verified298299def test_auto_pagination_uses_the_last_item_as_cursor():300 s = Script(ok({"object": "list", "data": [{**SESSION, "id": "vs_3"}, {**SESSION, "id": "vs_2"}], "has_more": True}),301 ok({"object": "list", "data": [{**SESSION, "id": "vs_1"}], "has_more": False}))302 assert [x.id for x in s.sync().verification_sessions.list_auto_paging(limit=2)] == ["vs_3", "vs_2", "vs_1"]303 assert dict(s.calls[0].url.params) == {"limit": "2"} and dict(s.calls[1].url.params) == {"limit": "2", "starting_after": "vs_2"}304 s = Script(ok({"object": "list", "data": [ver("ver_2")], "has_more": True}), ok({"object": "list", "data": [ver("ver_1")], "has_more": False}))305 page_ids = [v.verification_id for v in s.sync().verifications.list_auto_paging()]306 assert page_ids == ["ver_2", "ver_1"] and s.calls[1].url.params["starting_after"] == "ver_2"307308309def test_is_user_verified_returns_newest_valid():310 s = Script(ok({"object": "list", "has_more": False, "data": [ver("ver_expired", expires_at="2020-01-01T00:00:00+00:00"),311 ver("ver_ok", expires_at="2999-01-01T00:00:00+00:00"), ver("ver_older")]}))312 v = s.sync().is_user_verified("u1")313 assert v is not None and v.verification_id == "ver_ok"314 assert dict(s.calls[0].url.params) == {"external_user_id": "u1", "status": "verified", "limit": "100"}315 assert Script(ok({"object": "list", "data": [], "has_more": False})).sync().is_user_verified("u1") is None316 assert Script(ok({"object": "list", "data": [ver("v", status="revoked")], "has_more": False})).sync().is_user_verified("u1") is None317 with pytest.raises(APIConnectionError):318 Script(httpx.ConnectError("down")).sync().is_user_verified("u1")319 with pytest.raises(MacLustrIdentityError):320 Script(ok({})).sync().is_user_verified("")321322323# ------------------------------------------------------------------ async client: same behaviour324325def test_async_client_same_surface_and_policy():326 async def main():327 s = Script(err(503, "unavailable"), ok(CREATED))328 async with s.asynchronous() as c:329 c._random = lambda: 1.0330 out = await c.verification_sessions.create(purpose="p", external_user_id="u1")331 assert out.id == "vs_1" and len(s.calls) == 2 and s.waits == [0.5]332 assert s.calls[0].headers["idempotency-key"] == s.calls[1].headers["idempotency-key"]333334 s = Script(ok({"object": "list", "data": [ver("ver_2")], "has_more": True}), ok({"object": "list", "data": [ver("ver_1")], "has_more": False}))335 c = s.asynchronous()336 assert [v.verification_id async for v in c.verifications.list_auto_paging(limit=1)] == ["ver_2", "ver_1"]337338 s = Script(ok({"object": "list", "has_more": False, "data": [ver("ver_expired", expires_at="2020-01-01T00:00:00+00:00"), ver("ver_ok")]}))339 v = await s.asynchronous().is_user_verified("u1")340 assert v is not None and v.verification_id == "ver_ok"341342 s = Script(err(404, "resource_missing"))343 with pytest.raises(NotFoundError):344 await s.asynchronous().verifications.retrieve("ver_x")345 assert len(s.calls) == 1346347 s = Script(httpx.ConnectError("down"))348 with pytest.raises(APIConnectionError):349 await s.asynchronous(max_retries=1).is_user_verified("u1")350 assert len(s.calls) == 2351352 s = Script(err(429, "rate_limited", headers={"Retry-After": "2"}), ok({"id": "we_1", "secret": "whsec_new"}))353 with pytest.raises(RateLimitError):354 await s.asynchronous().webhooks.rotate_secret("we_1", max_retries=0)355 assert len(s.calls) == 1356 s = Script(err(429, "rate_limited", headers={"Retry-After": "2"}), ok({"id": "we_1", "secret": "whsec_new"}))357 rotated = await s.asynchronous().webhooks.rotate_secret("we_1") # retried with the same key358 assert rotated.secret == "whsec_new" and s.waits == [2.0] and "whsec_new" not in repr(rotated)359 assert s.calls[0].headers["idempotency-key"] == s.calls[1].headers["idempotency-key"]360 s = Script(err(503, "service_unavailable", headers={"Retry-After": "4"}), ok({"id": "we_1", "object": "webhook_endpoint", "secret": "whsec_1"}))361 assert (await s.asynchronous().webhooks.create(url="https://app.example/hook")).id == "we_1" and s.waits == [4.0]362363 asyncio.run(main())364365366def test_sync_and_async_expose_the_same_methods():367 def surface(obj):368 return {n for n in dir(obj) if not n.startswith("_")}369 s, a = MacLustrIdentity("mlid_sk_test_x"), AsyncMacLustrIdentity("mlid_sk_test_x")370 for res in ("verification_sessions", "verifications", "webhooks"):371 assert surface(getattr(s, res)) == surface(getattr(a, res)), res372 assert surface(s) - {"close"} == surface(a) - {"aclose"}373