Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

ci(sdk): type-check the Python client, and make the gate able to fail

Yudhi Armyndharis3c2b981cd7fb
diff --git a/.github/workflows/sdk-ci.yml b/.github/workflows/sdk-ci.yml
index d1a446fd0..5e0ac3b0f 100644
--- a/.github/workflows/sdk-ci.yml
+++ b/.github/workflows/sdk-ci.yml
@@ -69,6 +69,11 @@ jobs:
with:
python-version: ${{ matrix.python }}
- run: pip install -e '.[dev]'
+ # Before pytest: this package ships py.typed, so its annotations are a published contract,
+ # and pytest cannot see a mistake in them — TypedDict keys are not enforced at runtime, so a
+ # request type missing a field passes every test here while a typed caller is told the field
+ # does not exist.
+ - run: mypy
- run: pytest
php:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0f2a54e5a..1ad376149 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- The dashboard bundled all thirteen locales into one 476 KB chunk the page preloaded, so every visitor downloaded twelve languages to read one; each is now fetched on demand.
+- Fifteen return and parameter annotations in the Python SDK named `list[...]` inside classes that define a `list` method, so each resolved to the method rather than the builtin. That package ships `py.typed`, so the wrong types were what a consumer's own type checker read. Its CI now runs mypy, which nothing did before.
- A locale chunk that failed to load left the dashboard right-to-left around English copy, because text direction followed the requested language rather than the catalogue that answered; it now follows what actually rendered.
- `check:sdk-routes` scanned the JavaScript client for backtick-delimited paths only, while its PHP and Python rules already accepted every quote style, so the nine routes that client writes as single-quoted strings were never compared to the contract — `/api/health/ready` among them, which is also the container healthcheck and Kubernetes readiness path. Renaming one of those server-side passed every gate and the JS suite, and the published client would have 404'd with CI green.
- The JavaScript, Python, Go and Java SDKs omitted `contact`, `call` and `ephemeralDuration` from their chat-history message type, so a typed client had to cast to read three fields the endpoint returns; all four now mirror the engine payload.
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index 0308374d8..0a70270b5 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -22,6 +22,7 @@ dependencies = [
dev = [
"pytest>=7.0",
"pytest-asyncio>=0.23",
+ "mypy>=1.8",
]
[project.urls]
@@ -38,3 +39,32 @@ openwa = ["py.typed"]
[tool.pytest.ini_options]
testpaths = ["tests"]
+
+# This package ships py.typed (see package-data above), so its annotations are a published
+# contract — a consumer's own type checker reads them. pytest cannot see a mistake in one:
+# TypedDict keys are not enforced at runtime, so a request type missing a field still passes every
+# test in this suite while a typed caller is told the field does not exist.
+#
+# BOTH settings below were arrived at by mutation, not by taste. Deleting a key from a TypedDict
+# and confirming the gate goes red is the only way to know it watches anything — and the first two
+# configurations that looked correct were green with the key gone:
+#
+# files = ["openwa"] only → exit 0. The resources forward request bodies untouched, so a
+# missing key is invisible from inside the package. The typed
+# CALLERS live in tests/, so that is where the failure surfaces.
+# check_untyped_defs unset → exit 0. The test methods carry no annotations, and mypy skips
+# the body of any unannotated function, so every typed call in
+# the suite went unread.
+#
+# A third blind spot lived outside this file: `make_client()` in tests/conftest.py had no return
+# annotation, so it yielded Any and every `make_client(...).messages.send_*(...)` was unchecked.
+# Do not remove that annotation.
+[tool.mypy]
+files = ["openwa", "tests"]
+check_untyped_defs = true
+warn_unused_ignores = true
+warn_redundant_casts = true
+no_implicit_optional = true
+# No python_version pin on purpose: the CI matrix runs this job on 3.9 and 3.12, so mypy checks
+# against whichever interpreter it is installed under and both floors get covered. Pinning one
+# here would check that version twice and mask the other.
diff --git a/sdk/python/tests/conftest.py b/sdk/python/tests/conftest.py
index 7f4198eb3..b9140a26b 100644
--- a/sdk/python/tests/conftest.py
+++ b/sdk/python/tests/conftest.py
@@ -8,6 +8,14 @@ to test an httpx-based client.
from __future__ import annotations
import json
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ # Import-time cost is why the runtime import stays inside make_client; the annotation still
+ # needs the name so mypy can follow a call chain through this helper. Without a return type
+ # the helper yields Any, and every `make_client(...).messages.send_*(...)` in the suite goes
+ # unchecked — which is exactly how a TypedDict key can go missing with the gate still green.
+ from openwa import OpenWAClient
from dataclasses import dataclass, field
from typing import Any, Callable
@@ -75,7 +83,9 @@ class MockBackend:
return self.calls[-1]
-def make_client(backend: MockBackend, base_url: str = "http://localhost:2785", api_key: str = "owa_k1_test"):
+def make_client(
+ backend: MockBackend, base_url: str = "http://localhost:2785", api_key: str = "owa_k1_test"
+) -> "OpenWAClient":
from openwa import OpenWAClient
return OpenWAClient(base_url=base_url, api_key=api_key, transport=backend.as_transport())
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 1363c34ba..e06c66ec3 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -6,7 +6,9 @@ import httpx
import pytest
from openwa import OpenWAClient, OpenWAApiError, OpenWANotFoundError
+from openwa._http import build_url
from openwa.errors import OpenWAServiceUnavailableError
+from openwa.types import WebhookFilters
from conftest import MockBackend, make_client
@@ -99,9 +101,24 @@ class TestClientCore:
assert "chatId=a%40c.us" in url
assert "limit=10" in url
+ def test_build_url_omits_none_valued_params(self):
+ # The behaviour a caller depends on: a None never reaches the wire as the literal "None".
+ # Tested here because build_url is what implements it — the typed resource signatures
+ # forbid None, so proving it through one of them would mean lying about a type.
+ url = build_url("http://x", "/api/search", {"q": "x", "sessionId": None, "limit": 5})
+
+ assert "q=x" in url
+ assert "limit=5" in url
+ assert "sessionId" not in url
+ assert "None" not in url
+
def test_204_is_none(self):
+ # `delete` is declared `-> None`, so asserting on its result is a type error and proves
+ # nothing the signature does not already guarantee. What is worth asserting is that a 204
+ # completes without trying to parse an empty body as JSON.
backend = MockBackend().on("DELETE", "/api/sessions", status=204)
- assert make_client(backend).sessions.delete("x") is None
+ make_client(backend).sessions.delete("x")
+ assert backend.last_call.method == "DELETE"
def test_404_maps_to_not_found_error(self):
backend = MockBackend().on("GET", "/api/sessions/missing", status=404, body={
@@ -563,7 +580,10 @@ class TestWebhooks:
def test_create_forwards_polymorphic_filter_values_verbatim(self):
backend = MockBackend().on("POST", "/webhooks", body={"id": "w1"})
- filters = {
+ # Annotated, not inferred: an unannotated literal widens to dict[str, list[object]] and the
+ # call below then proves nothing about the declared filter shape — which is the whole point
+ # of a test named "forwards polymorphic filter values verbatim".
+ filters: WebhookFilters = {
"conditions": [
{"field": "sender", "operator": "is", "value": ["[email protected]"]},
{"field": "body", "operator": "contains", "value": "invoice", "caseSensitive": True},
@@ -882,11 +902,16 @@ class TestSearch:
assert res["hits"][0]["direction"] == "incoming"
def test_search_none_values_skipped_in_query(self):
- # None-typed optional filters must be omitted, never sent as the literal "None".
+ # Asserted against build_url, which is where the omission actually happens, rather than by
+ # routing `sessionId: None` through the typed resource. The contract has sessionId optional
+ # but NOT nullable (openapi.json: required false, type string, no nullable), so the
+ # TypedDict is right to demand a str and the old call was sending a payload the gateway
+ # would reject. Testing the mechanism at its owner keeps the regression covered without
+ # anything having to lie about the type.
backend = MockBackend().on("GET", "/api/search", body={
"hits": [], "total": 0, "tookMs": 0, "provider": "builtin-fts",
})
- make_client(backend).search.search({"q": "x", "sessionId": None, "limit": 5})
+ make_client(backend).search.search({"q": "x", "limit": 5})
url = backend.last_call.url
assert "q=x" in url
assert "limit=5" in url