Debian Codegraph @

tests/test_plugin_whatsapp.py

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