Debian Codegraph @

tests/test_plugin_whatsapp.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from json import dumps, loads
29
30 # Disable logging for a cleaner testing output
31 import logging
32 from unittest import mock
33
34 from helpers import AppriseURLTester
35 import pytest
36 import requests
37
38 from apprise import Apprise, NotifyType
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.whatsapp import IS_GROUP_ID, NotifyWhatsApp
41
42 logging.disable(logging.CRITICAL)
43
44 # Our Testing URLs
45 apprise_url_tests = (
46 (
47 "whatsapp://",
48 {
49 # Not enough details
50 "instance": AppriseImproperlyConfigured,
51 },
52 ),
53 (
54 "whatsapp://:@/",
55 {
56 # invalid Access Token
57 "instance": AppriseImproperlyConfigured,
58 },
59 ),
60 (
61 "whatsapp://{}@_".format("a" * 32),
62 {
63 # token provided but invalid from
64 "instance": AppriseImproperlyConfigured,
65 },
66 ),
67 (
68 "whatsapp://%20:{}@12345/{}".format("e" * 32, "4" * 11),
69 {
70 # Invalid template
71 "instance": AppriseImproperlyConfigured,
72 },
73 ),
74 (
75 "whatsapp://{}@{}".format("b" * 32, 10**9),
76 {
77 # token provided and from but no target no
78 "instance": NotifyWhatsApp,
79 # Response will fail due to no targets defined
80 "notify_response": False,
81 },
82 ),
83 (
84 "whatsapp://{}:{}@{}/123/{}/abcd/".format(
85 "a" * 32, "b" * 32, "3" * 11, "9" * 15
86 ),
87 {
88 # valid everything but target numbers
89 "instance": NotifyWhatsApp,
90 # Response will fail due to target not being loaded
91 "notify_response": False,
92 },
93 ),
94 (
95 "whatsapp://{}@12345/{}".format("e" * 32, "4" * 11),
96 {
97 # simple message
98 "instance": NotifyWhatsApp,
99 # Our expected url(privacy=True) startswith() response:
100 "privacy_url": "whatsapp://[email protected]/%2B44444444444/",
101 },
102 ),
103 (
104 "whatsapp://template:{}@12345/{}".format("e" * 32, "4" * 11),
105 {
106 # template
107 "instance": NotifyWhatsApp,
108 # Our expected url(privacy=True) startswith() response:
109 "privacy_url": "whatsapp://template:[email protected]/%2B44444444444/",
110 },
111 ),
112 (
113 "whatsapp://template:{}@12345/{}?lang=fr_CA".format(
114 "e" * 32, "4" * 11
115 ),
116 {
117 # template with language over-ride
118 "instance": NotifyWhatsApp,
119 # Our expected url(privacy=True) startswith() response:
120 "privacy_url": "whatsapp://template:[email protected]/%2B44444444444/",
121 },
122 ),
123 (
124 "whatsapp://{}@12345/{}?template=template&lang=fr_CA".format(
125 "e" * 32, "4" * 11
126 ),
127 {
128 # template specified as kwarg with language over-ride
129 "instance": NotifyWhatsApp,
130 # Our expected url(privacy=True) startswith() response:
131 "privacy_url": "whatsapp://template:[email protected]/%2B44444444444/",
132 },
133 ),
134 (
135 "whatsapp://template:{}@12345/{}?lang=1234".format("e" * 32, "4" * 11),
136 {
137 # template with invalid language over-ride
138 "instance": AppriseImproperlyConfigured,
139 },
140 ),
141 (
142 "whatsapp://template:{}@12345/{}?:1=test&:body=3&:type=2".format(
143 "e" * 32, "4" * 11
144 ),
145 {
146 # template with kwarg assignments
147 # {{1}} assigned test
148 # {{2}} assigned Apprise Message type (special keyword)
149 # {{3}} assigned Apprise Message body (special keyword)
150 "instance": NotifyWhatsApp,
151 # Our expected url(privacy=True) startswith() response:
152 "privacy_url": "whatsapp://template:[email protected]/%2B44444444444/",
153 },
154 ),
155 (
156 "whatsapp://template:{}@12345/{}?:invalid=23".format(
157 "e" * 32, "4" * 11
158 ),
159 {
160 # template with kwarg assignments
161 # Invalid keyword specified; cna only be a digit OR `body'
162 # or 'type'
163 "instance": AppriseImproperlyConfigured,
164 },
165 ),
166 (
167 "whatsapp://template:{}@12345/{}?:body=".format("e" * 32, "4" * 11),
168 {
169 # template with kwarg assignments
170 # No Body Assigment
171 "instance": AppriseImproperlyConfigured,
172 },
173 ),
174 (
175 "whatsapp://template:{}@12345/{}?:1=Test&:body=1".format(
176 "e" * 32, "4" * 11
177 ),
178 {
179 # template with kwarg assignments
180 # Ambiguious assignment {{1}} assigned twice
181 "instance": AppriseImproperlyConfigured,
182 },
183 ),
184 (
185 "whatsapp://{}:{}@123456/{}".format("a" * 32, "b" * 32, "4" * 11),
186 {
187 # using short-code (6 characters)
188 "instance": NotifyWhatsApp,
189 },
190 ),
191 (
192 "whatsapp://_?token={}&from={}&to={}".format(
193 "d" * 32, "5" * 11, "6" * 11
194 ),
195 {
196 # use get args to acomplish the same thing
197 "instance": NotifyWhatsApp,
198 },
199 ),
200 (
201 "whatsapp://_?token={}&source={}&to={}".format(
202 "d" * 32, "5" * 11, "6" * 11
203 ),
204 {
205 # use get args to acomplish the same thing (use source instead
206 # of from)
207 "instance": NotifyWhatsApp,
208 },
209 ),
210 (
211 "whatsapp://{}@12345/{}".format("e" * 32, "4" * 11),
212 {
213 "instance": NotifyWhatsApp,
214 # throw a bizarre code forcing us to fail to look it up
215 "response": False,
216 "requests_response_code": 999,
217 },
218 ),
219 (
220 "whatsapp://{}@12345/{}".format("e" * 32, "4" * 11),
221 {
222 "instance": NotifyWhatsApp,
223 # Throws a series of i/o exceptions with this flag
224 # is set and tests that we gracefully handle them
225 "test_requests_exceptions": True,
226 },
227 ),
228 # Group target tests
229 (
230 # Group ID via '#' prefix
231 "whatsapp://{}@12345/%23120363043968066561".format("e" * 32),
232 {
233 "instance": NotifyWhatsApp,
234 "privacy_url": "whatsapp://[email protected]/%23120363043968066561/",
235 },
236 ),
237 (
238 # Mix of phone number and group ID
239 "whatsapp://{}@12345/{}/%23120363043968066561".format(
240 "e" * 32, "4" * 11
241 ),
242 {
243 "instance": NotifyWhatsApp,
244 },
245 ),
246 (
247 # Group target with HTTP 500
248 "whatsapp://{}@12345/%23120363043968066561".format("e" * 32),
249 {
250 "instance": NotifyWhatsApp,
251 "response": False,
252 "requests_response_code": requests.codes.internal_server_error,
253 },
254 ),
255 (
256 # Group target with request exception
257 "whatsapp://{}@12345/%23120363043968066561".format("e" * 32),
258 {
259 "instance": NotifyWhatsApp,
260 "test_requests_exceptions": True,
261 },
262 ),
263 )
264
265
266 def test_plugin_whatsapp_urls():
267 """NotifyWhatsApp() Apprise URLs."""
268
269 # Run our general tests
270 AppriseURLTester(tests=apprise_url_tests).run_all()
271
272
273 @mock.patch("requests.post")
274 def test_plugin_whatsapp_auth(mock_post):
275 """NotifyWhatsApp() Auth.
276
277 - account-wide auth token
278 - API key and its own auth token
279 """
280
281 response = mock.Mock()
282 response.content = ""
283 response.status_code = requests.codes.ok
284
285 # Prepare Mock
286 mock_post.return_value = response
287
288 # Initialize some generic (but valid) tokens
289 token = "{}".format("b" * 32)
290 from_phone_id = "123456787654321"
291 target = "+1 (555) 987-6543"
292 message_contents = "test"
293
294 # Variation of initialization without API key
295 obj = Apprise.instantiate(f"whatsapp://{token}@{from_phone_id}/{target}")
296 assert isinstance(obj, NotifyWhatsApp) is True
297 assert isinstance(obj.url(), str) is True
298
299 # Send Notification
300 assert obj.send(body=message_contents) is True
301
302 # Validate expected call parameters
303 assert mock_post.call_count == 1
304 first_call = mock_post.call_args_list[0]
305
306 # URL and message parameters are the same for both calls
307 assert first_call[0][0] == (
308 "https://graph.facebook.com/"
309 f"{NotifyWhatsApp.fb_graph_version}/{from_phone_id}/messages"
310 )
311 response = loads(first_call[1]["data"])
312 assert response["text"]["body"] == message_contents
313 assert response["to"] == "+15559876543"
314 assert response["recipient_type"] == "individual"
315
316
317 @mock.patch("requests.post")
318 def test_plugin_whatsapp_edge_cases(mock_post):
319 """NotifyWhatsApp() Edge Cases."""
320
321 # Prepare our response
322 response = requests.Request()
323 response.status_code = requests.codes.ok
324
325 # Prepare Mock
326 mock_post.return_value = response
327
328 # Initialize some generic (but valid) tokens
329 token = "b" * 32
330 from_phone_id = "123456787654321"
331 targets = ("+1 (555) 123-3456",)
332
333 # No token specified
334 with pytest.raises(AppriseImproperlyConfigured):
335 NotifyWhatsApp(
336 token=None, from_phone_id=from_phone_id, targets=targets
337 )
338
339 # No from_phone_id specified
340 with pytest.raises(AppriseImproperlyConfigured):
341 NotifyWhatsApp(token=token, from_phone_id=None, targets=targets)
342
343 # a error response
344 response.status_code = 400
345 response.content = dumps(
346 {
347 "error": {
348 "code": 21211,
349 "message": (
350 "The 'To' number +1234567 is not a valid phone number."
351 ),
352 },
353 }
354 )
355 mock_post.return_value = response
356
357 # Initialize our object
358 obj = NotifyWhatsApp(
359 token=token, from_phone_id=from_phone_id, targets=targets
360 )
361
362 # We will fail with the above error code
363 assert bool(obj.notify("title", "body", "info")) is False
364
365
366 @mock.patch("requests.post")
367 def test_plugin_whatsapp_template_notify_type_value(mock_post):
368 response = mock.Mock()
369 response.content = ""
370 response.status_code = requests.codes.ok
371 mock_post.return_value = response
372
373 token = "b" * 32
374 from_phone_id = "12345"
375 target = "+1 (555) 987-6543"
376
377 # Map notify_type -> {{2}}, body -> {{3}}
378 obj = Apprise.instantiate(
379 f"whatsapp://template:{token}@{from_phone_id}/{target}?:type=2&:body=3"
380 )
381 assert isinstance(obj, NotifyWhatsApp)
382
383 assert (
384 obj.send(body="test", title="t", notify_type=NotifyType.INFO) is True
385 )
386
387 call = mock_post.call_args_list[0]
388 assert "NotifyType." not in call[1]["data"]
389
390 payload = loads(call[1]["data"])
391 params = payload["template"]["components"][0]["parameters"]
392
393 # Ensure values are injected, not literal strings
394 assert params[0]["text"] == NotifyType.INFO.value
395 assert params[1]["text"] == "test"
396
397
398 @mock.patch("requests.post")
399 def test_plugin_whatsapp_groups(mock_post):
400 """NotifyWhatsApp() group target support."""
401
402 def _mk_resp(code=requests.codes.ok):
403 r = mock.Mock()
404 r.content = ""
405 r.status_code = code
406 return r
407
408 mock_post.return_value = _mk_resp()
409
410 token = "e" * 32
411 from_phone_id = "123456787654321"
412 # A realistic-looking numeric group ID
413 group_id = "120363043968066561"
414
415 # IS_GROUP_ID only matches the numeric portion (no prefix/suffix)
416 assert IS_GROUP_ID.match(group_id)
417 assert not IS_GROUP_ID.match(f"#{group_id}")
418 assert not IS_GROUP_ID.match(f"{group_id}@g.us")
419 assert not IS_GROUP_ID.match("abc123")
420
421 # __init__ target classification
422
423 # '#' prefix → group
424 obj = NotifyWhatsApp(
425 token=token,
426 from_phone_id=from_phone_id,
427 targets=[f"#{group_id}"],
428 )
429 assert obj.targets == [f"#{group_id}"]
430
431 # '@g.us' suffix (native API format) → normalised to '#' prefix
432 obj = NotifyWhatsApp(
433 token=token,
434 from_phone_id=from_phone_id,
435 targets=[f"{group_id}@g.us"],
436 )
437 assert obj.targets == [f"#{group_id}"]
438
439 # '#' prefix + '@g.us' suffix (both present) → normalised
440 obj = NotifyWhatsApp(
441 token=token,
442 from_phone_id=from_phone_id,
443 targets=[f"#{group_id}@g.us"],
444 )
445 assert obj.targets == [f"#{group_id}"]
446
447 # Invalid group ID (non-numeric) is dropped with a warning
448 obj = NotifyWhatsApp(
449 token=token,
450 from_phone_id=from_phone_id,
451 targets=["#badgroupid", f"#{group_id}"],
452 )
453 assert obj.targets == [f"#{group_id}"]
454
455 # Mixed: phone number + group ID
456 obj = NotifyWhatsApp(
457 token=token,
458 from_phone_id=from_phone_id,
459 targets=["+14155552671", f"#{group_id}"],
460 )
461 assert len(obj.targets) == 2
462 assert "+14155552671" in obj.targets
463 assert f"#{group_id}" in obj.targets
464
465 # send() payload verification
466
467 mock_post.reset_mock()
468 obj = NotifyWhatsApp(
469 token=token,
470 from_phone_id=from_phone_id,
471 targets=[f"#{group_id}"],
472 )
473 assert obj.send(body="hello group") is True
474 assert mock_post.call_count == 1
475
476 # Group payload must carry recipient_type='group' and 'to'[email protected]
477 sent = loads(mock_post.call_args_list[0][1]["data"])
478 assert sent["recipient_type"] == "group"
479 assert sent["to"] == f"{group_id}@g.us"
480
481 # send() for individual phone preserves recipient_type='individual'
482 mock_post.reset_mock()
483 obj = NotifyWhatsApp(
484 token=token,
485 from_phone_id=from_phone_id,
486 targets=["+14155552671"],
487 )
488 assert obj.send(body="hello individual") is True
489 sent = loads(mock_post.call_args_list[0][1]["data"])
490 assert sent["recipient_type"] == "individual"
491 assert sent["to"] == "+14155552671"
492
493 # mixed send: one phone + one group makes two POST calls
494 mock_post.reset_mock()
495 obj = NotifyWhatsApp(
496 token=token,
497 from_phone_id=from_phone_id,
498 targets=["+14155552671", f"#{group_id}"],
499 )
500 assert obj.send(body="mixed") is True
501 assert mock_post.call_count == 2
502 payloads = [loads(c[1]["data"]) for c in mock_post.call_args_list]
503 types = {p["recipient_type"] for p in payloads}
504 assert types == {"individual", "group"}
505
506 # HTTP error on group target returns False
507 mock_post.return_value = _mk_resp(requests.codes.internal_server_error)
508 obj = NotifyWhatsApp(
509 token=token,
510 from_phone_id=from_phone_id,
511 targets=[f"#{group_id}"],
512 )
513 assert obj.send(body="should fail") is False
514
515 # partial failure: phone succeeds, group errors → overall False
516 mock_post.side_effect = [
517 _mk_resp(requests.codes.ok),
518 _mk_resp(requests.codes.internal_server_error),
519 ]
520 obj = NotifyWhatsApp(
521 token=token,
522 from_phone_id=from_phone_id,
523 targets=["+14155552671", f"#{group_id}"],
524 )
525 assert obj.send(body="partial") is False
526
527 # URL round-trip: group ID survives url() -> parse_url()
528 mock_post.side_effect = None
529 mock_post.return_value = _mk_resp()
530
531 obj = NotifyWhatsApp(
532 token=token,
533 from_phone_id=from_phone_id,
534 targets=[f"#{group_id}"],
535 )
536 rebuilt = NotifyWhatsApp(**NotifyWhatsApp.parse_url(obj.url()))
537 assert rebuilt.targets == obj.targets
538 assert rebuilt.url_identifier == obj.url_identifier
539
540 # Round-trip with mixed targets
541 obj = NotifyWhatsApp(
542 token=token,
543 from_phone_id=from_phone_id,
544 targets=["+14155552671", f"#{group_id}"],
545 )
546 rebuilt = NotifyWhatsApp(**NotifyWhatsApp.parse_url(obj.url()))
547 assert sorted(rebuilt.targets) == sorted(obj.targets)
548
549 # targets as a plain string (comma-separated, not a list)
550 obj = NotifyWhatsApp(
551 token=token,
552 from_phone_id=from_phone_id,
553 targets=f"#{group_id}",
554 )
555 assert obj.targets == [f"#{group_id}"]
556
557 # whitespace-only list entry is silently skipped
558 obj = NotifyWhatsApp(
559 token=token,
560 from_phone_id=from_phone_id,
561 targets=[" ", f"#{group_id}"],
562 )
563 assert obj.targets == [f"#{group_id}"]
564
565 # ?to= query parameter accepts group IDs
566 url = f"whatsapp://_?token={token}&from={from_phone_id}&to=%23{group_id}"
567 obj = Apprise.instantiate(url)
568 assert isinstance(obj, NotifyWhatsApp)
569 assert f"#{group_id}" in obj.targets
570
571 # privacy_url masks group targets correctly
572 obj = NotifyWhatsApp(
573 token=token,
574 from_phone_id=from_phone_id,
575 targets=[f"#{group_id}"],
576 )
577 priv = obj.url(privacy=True)
578 # The token should be masked; the group ID should still be present
579 assert token not in priv
580 assert group_id in priv