Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test(dashboard): cover group send routing, pacing and its stop paths
Cares T.34bcaeefb5a6
diff --git a/dashboard/src/pages/MessageTester.test.ts b/dashboard/src/pages/MessageTester.test.tsindex 25d609168..a960921f2 100644--- a/dashboard/src/pages/MessageTester.test.ts+++ b/dashboard/src/pages/MessageTester.test.ts@@ -58,6 +58,105 @@ async function pickRecipientsFile(size: number): Promise<{ container: HTMLElemenreturn { container };}+let restoreFetch: (() => void) | null = null;++afterEach(() => {+ restoreFetch?.();+ restoreFetch = null;+ window.localStorage.removeItem('openwa_user_role');+});++function groupJsonResponse(data: unknown, status = 200): Response {+ return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });+}++function stubGroupGateway(groups: { id: string; name?: string }[], refuseFirstWith?: number): { textSends: string[] } {+ const previousFetch = globalThis.fetch;+ restoreFetch = () => {+ globalThis.fetch = previousFetch;+ };+ const textSends: string[] = [];+ globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ if (url.endsWith('/sessions')) {+ return Promise.resolve(groupJsonResponse([{ id: 's1', name: 'Main', status: 'ready', phone: '15550000000' }]));+ }+ if (url.endsWith('/sessions/s1/groups')) return Promise.resolve(groupJsonResponse(groups));+ if (url.endsWith('/messages/send-text')) {+ const { chatId } = JSON.parse(String(init?.body)) as { chatId: string };+ textSends.push(chatId);+ if (refuseFirstWith && textSends.length === 1) {+ return Promise.resolve(groupJsonResponse({ message: 'Too many requests' }, refuseFirstWith));+ }+ return Promise.resolve(groupJsonResponse({ messageId: `m${textSends.length}`, timestamp: 1 }, 201));+ }+ return Promise.resolve(groupJsonResponse([]));+ }) as typeof fetch;+ return { textSends };+}++async function renderGroupsAsWriter(): Promise<void> {+ window.localStorage.setItem('openwa_user_role', 'admin');+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });+ rtl.render(+ createElement(QueryClientProvider, { client }, createElement(RoleProvider, null, createElement(MessageTester))),+ );+ await rtl.screen.findByRole('option', { name: /Main/ });+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: 'Group' }));+}++function sendMessageButton(): HTMLButtonElement {+ return rtl.screen.getByRole('button', { name: 'Send Message' }) as HTMLButtonElement;+}++async function sendTextToAllGroups(): Promise<void> {+ await rtl.screen.findByRole('checkbox', { name: 'Work' });+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: 'Select all' }));+ rtl.fireEvent.change(rtl.screen.getByPlaceholderText('Enter your message here...'), { target: { value: 'hi' } });+ await rtl.waitFor(() => assert.equal(sendMessageButton().disabled, false));+ rtl.fireEvent.click(sendMessageButton());+}++test('a group without a name is listed by its id', async () => {+ stubGroupGateway([{ id: '[email protected]' }, { id: '[email protected]', name: 'Work' }]);+ await renderGroupsAsWriter();++ await rtl.screen.findByRole('checkbox', { name: '[email protected]' });+ assert.ok(rtl.screen.getByRole('checkbox', { name: 'Work' }));+});++test('cancelling a group send stops the groups still waiting', async () => {+ const gateway = stubGroupGateway([+ { id: '[email protected]', name: 'Family' },+ { id: '[email protected]', name: 'Work' },+ ]);+ await renderGroupsAsWriter();+ await sendTextToAllGroups();++ await rtl.waitFor(() => assert.equal(gateway.textSends.length, 1));+ rtl.fireEvent.click(await rtl.screen.findByRole('button', { name: 'Cancel' }));++ await rtl.screen.findByText('1, cancelled');+ assert.deepEqual(gateway.textSends, ['[email protected]']);+ assert.ok(rtl.screen.getByText('1/2 sent'));+});++test('a 429 from the gateway stops the run instead of trying the rest', async () => {+ const gateway = stubGroupGateway(+ [+ { id: '[email protected]', name: 'Family' },+ { id: '[email protected]', name: 'Work' },+ ],+ 429,+ );+ await renderGroupsAsWriter();+ await sendTextToAllGroups();++ await rtl.screen.findByText('1, stopped after HTTP 429');+ assert.deepEqual(gateway.textSends, ['[email protected]']);+ assert.ok(rtl.screen.getByText('Failed'));+});+test('a recipients file over the cap is refused without being read', async () => {const { container } = await pickRecipientsFile(maxBytes + 1);diff --git a/dashboard/src/utils/groupSelection.test.ts b/dashboard/src/utils/groupSelection.test.tsindex d78c68b89..75b52c9d5 100644--- a/dashboard/src/utils/groupSelection.test.ts+++ b/dashboard/src/utils/groupSelection.test.ts@@ -1,56 +1,88 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { addGroupIds, filterGroupsByName, groupLabel, toggleGroupId } from './groupSelection.ts';+import {+ addGroupIds,+ filterGroupRows,+ groupLabel,+ groupPickerRows,+ isGatewayRefusal,+ planGroupSend,+ toggleGroupId,+} from './groupSelection.ts';const groups = [{ id: '[email protected]', name: 'Family' },{ id: '[email protected]', name: 'Work Team' },- { id: '[email protected]', name: 'Football' },- { id: '[email protected]', name: ' ' },+ { id: '[email protected]', name: ' ' },+ { id: '[email protected]' },];-test('labels a group by its name, falling back to the id when the name is blank', () => {+test('labels a group by its name, falling back to the id when the name is blank or missing', () => {assert.equal(groupLabel(groups[0]), 'Family');+ assert.equal(groupLabel(groups[2]), '[email protected]');assert.equal(groupLabel(groups[3]), '[email protected]');});-test('an empty or whitespace query keeps every group', () => {- assert.deepEqual(filterGroupsByName(groups, ''), groups);- assert.deepEqual(filterGroupsByName(groups, ' '), groups);-});--test('filters by a case-insensitive substring of the name', () => {+test('rows list every group, then selected ids the list no longer has', () => {+ const rows = groupPickerRows(groups, ['[email protected]', '[email protected]', '[email protected]']);assert.deepEqual(- filterGroupsByName(groups, 'fa').map(group => group.id),- ['[email protected]'],+ rows.map(row => row.label),);+});++test('filters rows by a case-insensitive substring of the label', () => {+ const rows = groupPickerRows(groups, []);+ assert.deepEqual(filterGroupRows(rows, '').length, rows.length);assert.deepEqual(- filterGroupsByName(groups, ' TEAM ').map(group => group.id),+ filterGroupRows(rows, ' TEAM ').map(row => row.id),['[email protected]'],);-});--test('a nameless group is found by its id', () => {assert.deepEqual(- filterGroupsByName(groups, '444').map(group => group.id),+ filterGroupRows(rows, '444').map(row => row.id),['[email protected]'],);});-test('returns a new array so callers never mutate the source list', () => {- const result = filterGroupsByName(groups, '');- assert.notEqual(result, groups);-});-test('toggling adds a missing id and removes a present one', () => {assert.deepEqual(toggleGroupId(['[email protected]'], '[email protected]'), ['[email protected]', '[email protected]']);assert.deepEqual(toggleGroupId(['[email protected]', '[email protected]'], '[email protected]'), ['[email protected]']);});-test('adding ids keeps the existing selection first and drops duplicates', () => {- assert.deepEqual(addGroupIds(['[email protected]', '[email protected]'], ['[email protected]', '[email protected]']), [+test('adding ids keeps the selection first, drops duplicates and stops at the limit', () => {+ assert.deepEqual(addGroupIds(['[email protected]'], ['[email protected]', '[email protected]', '[email protected]'], 10), []);+ assert.deepEqual(addGroupIds(['[email protected]'], ['[email protected]', '[email protected]'], 2), ['[email protected]', '[email protected]']);+ assert.deepEqual(addGroupIds(['[email protected]', '[email protected]'], ['[email protected]'], 2), ['[email protected]', '[email protected]']);+});++test('no selection plans nothing', () => {+ assert.equal(planGroupSend([], 'text'), null);+});++test('one group is a single send', () => {+ assert.deepEqual(planGroupSend(['[email protected]'], 'text'), { mode: 'single', chatId: '[email protected]' });+});++test('several groups are sent one after another', () => {+ assert.deepEqual(planGroupSend(['[email protected]', '[email protected]'], 'poll'), {+ mode: 'sequential',+ chatIds: ['[email protected]', '[email protected]'],+ });+});++test('forward uses the first group as its source chat instead of looping', () => {+ assert.deepEqual(planGroupSend(['[email protected]', '[email protected]'], 'forward'), { mode: 'single', chatId: '[email protected]' });+});++test('429 and 503 are refusals that stop a run, other failures are not', () => {+ const withStatus = (status: number) => Object.assign(new Error('refused'), { status });+ assert.equal(isGatewayRefusal(withStatus(429)), true);+ assert.equal(isGatewayRefusal(withStatus(503)), true);+ assert.equal(isGatewayRefusal(withStatus(404)), false);+ assert.equal(isGatewayRefusal(new Error('offline')), false);+ assert.equal(isGatewayRefusal(null), false);});diff --git a/dashboard/src/utils/sendSequentially.test.ts b/dashboard/src/utils/sendSequentially.test.tsindex f1776bf0e..5da1e1ea1 100644--- a/dashboard/src/utils/sendSequentially.test.ts+++ b/dashboard/src/utils/sendSequentially.test.ts@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';import { sendSequentially } from './sendSequentially.ts';const noSleep = async () => {};+const refusal = (status: number) => Object.assign(new Error(`HTTP ${status}`), { status });test('sends to every target in order and counts the successes', async () => {const calls: string[] = [];@@ -14,7 +15,7 @@ test('sends to every target in order and counts the successes', async () => {{ delayMs: 3000, sleep: noSleep },);assert.deepEqual(calls, ['a', 'b', 'c']);- assert.deepEqual(result, { sent: 3, failures: [] });+ assert.deepEqual(result, { sent: 3, failures: [], notAttempted: [] });});test('waits the delay between targets but not before the first or after the last', async () => {@@ -34,18 +35,83 @@ test('waits the delay between targets but not before the first or after the lastassert.deepEqual(events, ['send:a', 'sleep:3000', 'send:b', 'sleep:3000', 'send:c']);});-test('a failing target is recorded and the remaining targets are still sent', async () => {+test('really waits between targets when no sleep is injected', async () => {+ const sentAt: number[] = [];+ await sendSequentially(+ ['a', 'b'],+ async () => {+ sentAt.push(performance.now());+ },+ { delayMs: 20 },+ );+ assert.equal(sentAt.length, 2);+ assert.ok(sentAt[1] - sentAt[0] >= 15, `second send came ${sentAt[1] - sentAt[0]}ms after the first`);+});++test('a failing target is recorded with its status and the rest are still sent', async () => {const calls: string[] = [];const result = await sendSequentially(['a', 'b', 'c'],async target => {calls.push(target);- if (target === 'b') throw new Error('Group not found');+ if (target === 'b') throw refusal(404);},{ delayMs: 3000, sleep: noSleep },);assert.deepEqual(calls, ['a', 'b', 'c']);- assert.deepEqual(result, { sent: 2, failures: [{ target: 'b', error: 'Group not found' }] });+ assert.deepEqual(result, {+ sent: 2,+ failures: [{ target: 'b', error: 'HTTP 404', status: 404 }],+ notAttempted: [],+ });+});++test('a failure matching stopOn ends the run and reports the rest as not attempted', async () => {+ const calls: string[] = [];+ const result = await sendSequentially(+ ['a', 'b', 'c', 'd'],+ async target => {+ calls.push(target);+ if (target === 'b') throw refusal(429);+ },+ { delayMs: 3000, sleep: noSleep, stopOn: err => (err as { status?: number }).status === 429 },+ );+ assert.deepEqual(calls, ['a', 'b']);+ assert.deepEqual(result, {+ sent: 1,+ failures: [{ target: 'b', error: 'HTTP 429', status: 429 }],+ notAttempted: ['c', 'd'],+ stoppedBy: 'refusal',+ });+});++test('aborting stops before the next target', async () => {+ const controller = new AbortController();+ const calls: string[] = [];+ const result = await sendSequentially(+ ['a', 'b', 'c'],+ async target => {+ calls.push(target);+ controller.abort();+ },+ { delayMs: 3000, sleep: noSleep, signal: controller.signal },+ );+ assert.deepEqual(calls, ['a']);+ assert.deepEqual(result, { sent: 1, failures: [], notAttempted: ['b', 'c'], stoppedBy: 'abort' });+});++test('aborting during the wait ends it without waiting out the delay', async () => {+ const controller = new AbortController();+ const started = performance.now();+ const result = await sendSequentially(+ ['a', 'b'],+ async () => {+ setTimeout(() => controller.abort(), 10);+ },+ { delayMs: 60_000, signal: controller.signal },+ );+ assert.ok(performance.now() - started < 5_000, 'the abort did not cut the wait short');+ assert.deepEqual(result, { sent: 1, failures: [], notAttempted: ['b'], stoppedBy: 'abort' });});test('a non-Error rejection is stringified', async () => {@@ -79,5 +145,5 @@ test('an empty target list sends nothing', async () => {{ delayMs: 3000, sleep: noSleep },);assert.equal(called, false);- assert.deepEqual(result, { sent: 0, failures: [] });+ assert.deepEqual(result, { sent: 0, failures: [], notAttempted: [] });});