Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test: ratchet global coverage floors and harden test timing

Yudhi Armyndharisfeec72927879
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.md
index 0d9f22904..636f0964c 100644
--- a/docs/09-testing-strategy.md
+++ b/docs/09-testing-strategy.md
@@ -177,7 +177,7 @@ authoritative gate. Current policy:
| Scope | Branches | Functions | Lines | Statements |
| --------------------------- | -------- | --------- | ----- | ---------- |
-| Global | 58% | 63% | 66% | 65% |
+| Global | 61% | 68% | 69% | 69% |
| `src/common/cache/` | 34% | 33% | 42% | 42% |
| `src/common/security/` | 85% | 95% | 93% | 92% |
| `src/common/services/` | 74% | 91% | 87% | 84% |
diff --git a/package.json b/package.json
index 38e3a5356..a108e367f 100644
--- a/package.json
+++ b/package.json
@@ -167,10 +167,10 @@
"coverageDirectory": "../coverage",
"coverageThreshold": {
"global": {
- "branches": 58,
- "functions": 63,
- "lines": 66,
- "statements": 65
+ "branches": 61,
+ "functions": 68,
+ "lines": 69,
+ "statements": 69
},
"./src/common/cache/": {
"branches": 34,
diff --git a/scripts/check-sdk-routes.mjs b/scripts/check-sdk-routes.mjs
index de709ea85..6c1c9c785 100644
--- a/scripts/check-sdk-routes.mjs
+++ b/scripts/check-sdk-routes.mjs
@@ -13,6 +13,8 @@
* - Does NOT cover Go or Java: both assemble paths by concatenating a base with a suffix, so there
* is no literal to harvest. A drift there is invisible to this gate.
* - Checks that a route EXISTS, not that its method, request shape or response shape match.
+ * - The send-media verbs are harvested separately (see SEND_MEDIA_VERBS below): each SDK passes
+ * the verb as a plain string to a shared builder, so no per-route literal exists to scan.
*
* Lives in ci.yml's lint job rather than sdk-ci.yml on purpose: sdk-ci is path-filtered and does not
* list openapi.json, so changing the contract alone runs none of it — and it never runs on a release
@@ -77,6 +79,19 @@ const ALLOWED = new Map([
['/api/sessions/*/messages/*', 'the send-* family shares one builder; the verb itself is the variable'],
]);
+/**
+ * The send-media family is the one set of routes the literal scan above CANNOT see: each SDK passes
+ * the verb as a plain string to a shared builder (`sendMedia(sessionId, 'send-image', body)`), so the
+ * only path literal anywhere is the allowlisted `/api/sessions/{id}/messages/{verb}` template. Renaming
+ * `/messages/send-image` on the server would regenerate the contract, pass `openapi:check`, and pass
+ * the scan above while every send-image call 404s. Harvest the verb arguments themselves and pin
+ * each one to a concrete contract path.
+ */
+const SEND_MEDIA_VERBS = [
+ { name: 'javascript', dir: 'sdk/javascript/src', exts: ['.ts'], re: /\.sendMedia\(\s*\w+\s*,\s*['"`]([\w-]+)['"`]/g },
+ { name: 'python', dir: 'sdk/python/openwa', exts: ['.py'], re: /\._send_media\(\s*\w+\s*,\s*["']([\w-]+)["']/g },
+];
+
const contract = JSON.parse(readFileSync(join(root, 'openapi.json'), 'utf8'));
const known = new Set(Object.keys(contract.paths).map(normalize));
@@ -106,6 +121,29 @@ for (const sdk of SDKS) {
}
}
+for (const sdk of SEND_MEDIA_VERBS) {
+ const verbs = new Set();
+ for (const file of walk(join(root, sdk.dir), sdk.exts)) {
+ // Same comment strip as the literal scan: prose mentions of the helper are not call sites.
+ const src = readFileSync(file, 'utf8')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/^\s*(\/\/|#).*$/gm, '');
+ for (const m of src.matchAll(sdk.re)) verbs.add(m[1]);
+ }
+ // Same non-vacuity guard as the literal scan — today each SDK passes exactly five verbs, so a
+ // pattern that silently stopped matching must fail here rather than pin nothing.
+ if (verbs.size < 5) {
+ errors.push(`${sdk.name}: harvested only ${verbs.size} send-media verbs from ${sdk.dir} — the scan pattern has drifted.`);
+ continue;
+ }
+ for (const verb of [...verbs].sort()) {
+ const route = `/api/sessions/*/messages/${verb}`;
+ if (!known.has(route)) {
+ errors.push(`${sdk.name}: send-media verb '${verb}' builds ${route}, which is not a path in openapi.json.`);
+ }
+ }
+}
+
if (errors.length) {
console.error('\n✖ SDK routes drifted from the committed contract:');
for (const e of errors) console.error(` - ${e}`);
diff --git a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
index a8fe06a31..cb75fbaad 100644
--- a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
@@ -131,7 +131,16 @@ describe('plugin worker — real worker_threads round-trip (B1)', () => {
// shutdown is impossible. terminate() must still reclaim the thread.
const wedged = host.runLifecycle('onEnable');
wedged.catch(() => undefined); // terminate() rejects this pending call; swallow it
- await new Promise(resolve => setTimeout(resolve, 150));
+ // Poll until the loop is genuinely blocked rather than sleeping a fixed 150ms: the health-check
+ // message is queued behind the onEnable call (FIFO on one channel), so it can only time out once
+ // the infinite loop has actually started. Firing terminate() earlier would reclaim an idle worker
+ // and prove nothing.
+ const wedgeDeadline = Date.now() + 10_000;
+ for (;;) {
+ const health = await host.healthCheck(150);
+ if (!health.healthy) break;
+ if (Date.now() > wedgeDeadline) throw new Error('runaway plugin never blocked the worker event loop');
+ }
await expect(host.terminate()).resolves.toBeUndefined();
});
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index 49498c93e..e8032f7b4 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -172,7 +172,14 @@ describe('InfraDataController.importData round-trips export-data (no silent mess
runner.query = (async (...args: unknown[]): Promise<unknown> => {
if (!stalled && typeof args[0] === 'string' && args[0].startsWith('DELETE FROM sessions')) {
stalled = true;
- await new Promise(resolve => setTimeout(resolve, remainingMs * 1.5));
+ // Wait until the original lease has genuinely expired, polling the clock instead of
+ // sleeping a fixed multiple of the TTL: the property under test is "the transaction
+ // outlived the remaining time", so wait for exactly that — no shorter (the lease would
+ // still be live) and no longer (extra sleep only eats the assertion margin below).
+ const expiredAt = readAt + remainingMs;
+ while (Date.now() < expiredAt) {
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
}
return realQuery(...args);
}) as typeof runner.query;
diff --git a/test/webhooks.e2e-spec.ts b/test/webhooks.e2e-spec.ts
index ecc850273..3929e519c 100644
--- a/test/webhooks.e2e-spec.ts
+++ b/test/webhooks.e2e-spec.ts
@@ -291,9 +291,11 @@ describe('Webhooks (e2e)', () => {
filters: { conditions: [{ field: 'sender', operator: 'is', value: ['[email protected]'] }] },
});
+ // dispatch() awaits every per-webhook delivery attempt end-to-end in this queue-off suite
+ // (Promise.allSettled over the direct deliveries, each awaiting the receiver's response), and
+ // the receiver records a hit BEFORE it answers — so a wrongly-attempted delivery would already
+ // be in `received` here. A fixed sleep would only slow the assertion, not strengthen it.
await webhookService.dispatch(session, 'message.received', { from: '[email protected]', body: 'spam' });
- // No way to await a non-event; give dispatch a real chance to (not) deliver, then assert silence.
- await new Promise(r => setTimeout(r, 100));
expect(received).toHaveLength(0);
});
@@ -317,8 +319,9 @@ describe('Webhooks (e2e)', () => {
.send({ active: false })
.expect(200);
+ // Same settled-dispatch reasoning as the filter-mismatch case above: the awaited dispatch()
+ // resolves only after every attempted delivery completed, so no wait is needed before asserting.
await webhookService.dispatch(session, 'message.received', { from: '[email protected]' });
- await new Promise(r => setTimeout(r, 100));
expect(received).toHaveLength(0);
});