Debian Codegraph @

tests/test_plugin_onesignal.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 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
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.one_signal import NotifyOneSignal
41
42 logging.disable(logging.CRITICAL)
43
44 # Our Testing URLs
45 apprise_url_tests = (
46 (
47 "onesignal://",
48 {
49 # We failed to identify any valid authentication
50 "instance": AppriseImproperlyConfigured,
51 },
52 ),
53 (
54 "onesignal://:@/",
55 {
56 # We failed to identify any valid authentication
57 "instance": AppriseImproperlyConfigured,
58 },
59 ),
60 (
61 "onesignal://apikey/",
62 {
63 # no app id specified
64 "instance": AppriseImproperlyConfigured,
65 },
66 ),
67 (
68 "onesignal://appid@%20%20/",
69 {
70 # invalid apikey
71 "instance": AppriseImproperlyConfigured,
72 },
73 ),
74 (
75 "onesignal://appid@apikey/playerid/?lang=X",
76 {
77 # invalid language id (must be 2 characters)
78 "instance": AppriseImproperlyConfigured,
79 },
80 ),
81 (
82 "onesignal://appid@apikey/",
83 {
84 # No targets specified; we will initialize but not notify anything
85 "instance": NotifyOneSignal,
86 "notify_response": False,
87 },
88 ),
89 (
90 "onesignal://appid@apikey/playerid",
91 {
92 # Valid playerid
93 "instance": NotifyOneSignal,
94 "privacy_url": "onesignal://[email protected]/playerid",
95 },
96 ),
97 (
98 "onesignal://appid@apikey/player",
99 {
100 # Valid player id
101 "instance": NotifyOneSignal,
102 # don't include an image by default
103 "include_image": False,
104 },
105 ),
106 (
107 "onesignal://appid@apikey/@user?image=no",
108 {
109 # Valid userid, no image
110 "instance": NotifyOneSignal,
111 },
112 ),
113 (
114 "onesignal://appid@apikey/[email protected]/#seg/player/@user/%20/a",
115 {
116 # Valid email, valid playerid, valid user, invalid entry (%20),
117 # and too short of an entry (a)
118 "instance": NotifyOneSignal,
119 },
120 ),
121 (
122 "onesignal://appid@apikey?to=#segment,playerid",
123 {
124 # Test to=
125 "instance": NotifyOneSignal,
126 },
127 ),
128 (
129 "onesignal://appid@apikey/#segment/@user/?batch=yes",
130 {
131 # Test batch=
132 "instance": NotifyOneSignal,
133 },
134 ),
135 (
136 "onesignal://appid@apikey/#segment/@user/?batch=no",
137 {
138 # Test batch=
139 "instance": NotifyOneSignal,
140 },
141 ),
142 (
143 "onesignal://templateid:appid@apikey/playerid",
144 {
145 # Test Template ID
146 "instance": NotifyOneSignal,
147 },
148 ),
149 (
150 "onesignal://appid@apikey/playerid/?lang=es&subtitle=Sub",
151 {
152 # Test Language and Subtitle Over-ride (lang= alias)
153 "instance": NotifyOneSignal,
154 },
155 ),
156 (
157 "onesignal://appid@apikey/playerid/?language=es&subtitle=Sub",
158 {
159 # Test Language and Subtitle Over-ride (language= as declared
160 # in template_args)
161 "instance": NotifyOneSignal,
162 },
163 ),
164 (
165 "onesignal://appid@apikey/playerid/?language=X",
166 {
167 # invalid language id (must be 2 characters)
168 "instance": AppriseImproperlyConfigured,
169 },
170 ),
171 (
172 "onesignal://?apikey=abc&template=tp&app=123&to=playerid",
173 {
174 # Test Kwargs
175 "instance": NotifyOneSignal,
176 },
177 ),
178 (
179 (
180 "onesignal://?apikey=abc&template=tp&app=123&to=playerid&body=no"
181 "&:key1=val1&:key2=val2"
182 ),
183 {
184 # Test Kwargs
185 "instance": NotifyOneSignal,
186 },
187 ),
188 (
189 (
190 "onesignal://?apikey=abc&template=tp&app=123&to=playerid&body=no"
191 "&+key1=val1&+key2=val2"
192 ),
193 {
194 # Test Kwargs
195 "instance": NotifyOneSignal,
196 },
197 ),
198 (
199 "onesignal://appid@apikey/#segment/playerid/",
200 {
201 "instance": NotifyOneSignal,
202 # throw a bizarre code forcing us to fail to look it up
203 "response": False,
204 "requests_response_code": 999,
205 },
206 ),
207 (
208 "onesignal://appid@apikey/#segment/playerid/",
209 {
210 "instance": NotifyOneSignal,
211 # Throws a series of i/o exceptions with this flag
212 # is set and tests that we gracefully handle them
213 "test_requests_exceptions": True,
214 },
215 ),
216 )
217
218
219 def test_plugin_onesignal_urls():
220 """NotifyOneSignal() Apprise URLs."""
221
222 # Run our general tests
223 AppriseURLTester(tests=apprise_url_tests).run_all()
224
225
226 def test_plugin_onesignal_edge_cases():
227 """NotifyOneSignal() Batch Validation."""
228 obj = Apprise.instantiate(
229 "onesignal://appid@apikey/#segment/@user/playerid/[email protected]"
230 "/?batch=yes"
231 )
232 # Validate that it loaded okay
233 assert isinstance(obj, NotifyOneSignal)
234
235 # all 4 types defined; but even in a batch mode, they can not be
236 # sent in one submission
237 assert len(obj) == 4
238
239 #
240 # Users
241 #
242 obj = Apprise.instantiate(
243 "onesignal://appid@apikey/@user1/@user2/@user3/@user4/?batch=yes"
244 )
245 assert isinstance(obj, NotifyOneSignal)
246
247 # We can lump these together - no problem
248 assert len(obj) == 1
249
250 # Same query, but no batch mode set
251 obj = Apprise.instantiate(
252 "onesignal://appid@apikey/@user1/@user2/@user3/@user4/?batch=no"
253 )
254 assert isinstance(obj, NotifyOneSignal)
255
256 # Individual queries
257 assert len(obj) == 4
258
259 #
260 # Segments
261 #
262 obj = Apprise.instantiate(
263 "onesignal://appid@apikey/#segment1/#seg2/#seg3/#seg4/?batch=yes"
264 )
265 assert isinstance(obj, NotifyOneSignal)
266
267 # We can lump these together - no problem
268 assert len(obj) == 1
269
270 # Same query, but no batch mode set
271 obj = Apprise.instantiate(
272 "onesignal://appid@apikey/#segment1/#seg2/#seg3/#seg4/?batch=no"
273 )
274 assert isinstance(obj, NotifyOneSignal)
275
276 # Individual queries
277 assert len(obj) == 4
278
279 #
280 # Player ID's
281 #
282 obj = Apprise.instantiate(
283 "onesignal://appid@apikey/pid1/pid2/pid3/pid4/?batch=yes"
284 )
285 assert isinstance(obj, NotifyOneSignal)
286
287 # We can lump these together - no problem
288 assert len(obj) == 1
289
290 # Same query, but no batch mode set
291 obj = Apprise.instantiate(
292 "onesignal://appid@apikey/pid1/pid2/pid3/pid4/?batch=no"
293 )
294 assert isinstance(obj, NotifyOneSignal)
295
296 # Individual queries
297 assert len(obj) == 4
298
299 #
300 # Emails
301 #
302 emails = ("[email protected]", "[email protected]", "[email protected]", "[email protected]")
303 obj = Apprise.instantiate(
304 "onesignal://appid@apikey/{}/?batch=yes".format("/".join(emails))
305 )
306 assert isinstance(obj, NotifyOneSignal)
307
308 # We can lump these together - no problem
309 assert len(obj) == 1
310
311 # Same query, but no batch mode set
312 obj = Apprise.instantiate(
313 "onesignal://appid@apikey/{}/?batch=no".format("/".join(emails))
314 )
315 assert isinstance(obj, NotifyOneSignal)
316
317 # Individual queries
318 assert len(obj) == 4
319
320 #
321 # Mixed
322 #
323 emails = ("[email protected]", "[email protected]", "[email protected]", "[email protected]")
324 users = ("@user1", "@user2", "@user3", "@user4")
325 players = ("player1", "player2", "player3", "player4")
326 segments = ("#seg1", "#seg2", "#seg3", "#seg4")
327
328 path = "{}/{}/{}/{}".format(
329 "/".join(emails),
330 "/".join(users),
331 "/".join(players),
332 "/".join(segments),
333 )
334
335 obj = Apprise.instantiate(f"onesignal://appid@apikey/{path}/?batch=yes")
336 assert isinstance(obj, NotifyOneSignal)
337
338 # We can lump these together - no problem
339 assert len(obj) == 4
340
341 # Same query, but no batch mode set
342 obj = Apprise.instantiate(f"onesignal://appid@apikey/{path}/?batch=no")
343 assert isinstance(obj, NotifyOneSignal)
344
345 # Individual queries
346 assert len(obj) == 16
347
348 # custom must be a dictionary
349 with pytest.raises(AppriseImproperlyConfigured):
350 NotifyOneSignal(
351 app="appid", apikey="key", targets=["@user"], custom="not-a-dict"
352 )
353
354 # postback must be a dictionary
355 with pytest.raises(AppriseImproperlyConfigured):
356 NotifyOneSignal(
357 app="appid",
358 apikey="key",
359 targets=["@user"],
360 custom=[],
361 postback="not-a-dict",
362 )
363
364
365 def test_plugin_onesignal_url_round_trip():
366 """NotifyOneSignal() url() is reloadable without mutating targets."""
367 obj = Apprise.instantiate(
368 "onesignal://appid@apikey/@user/#segment/player/[email protected]"
369 )
370 assert isinstance(obj, NotifyOneSignal)
371
372 # The user and segment prefixes are stored as part of the target
373 assert obj.targets["include_external_user_ids"] == ["@user"]
374 assert obj.targets["included_segments"] == ["#segment"]
375
376 # Reloading the url() must not double the @ / # prefixes, and the
377 # generated url() must be stable (idempotent) across reloads.
378 url = obj.url()
379 reloaded = Apprise.instantiate(url)
380 assert isinstance(reloaded, NotifyOneSignal)
381
382 assert reloaded.targets["include_external_user_ids"] == ["@user"]
383 assert reloaded.targets["included_segments"] == ["#segment"]
384 assert reloaded.url() == url
385
386
387 @mock.patch("requests.post")
388 def test_plugin_onesignal_language_and_subtitle(mock_post):
389 """NotifyOneSignal() language= and subtitle= handling."""
390 mock_post.return_value = requests.Request()
391 mock_post.return_value.status_code = requests.codes.ok
392
393 # language= is the argument declared in template_args; it must be honored
394 obj = Apprise.instantiate("onesignal://appid@apikey/player/?language=fr")
395 assert isinstance(obj, NotifyOneSignal)
396 assert obj.language == "fr"
397
398 # lang= remains supported as an alias
399 obj = Apprise.instantiate("onesignal://appid@apikey/player/?lang=fr")
400 assert isinstance(obj, NotifyOneSignal)
401 assert obj.language == "fr"
402
403 # When both are provided, the declared language= entry wins
404 obj = Apprise.instantiate(
405 "onesignal://appid@apikey/player/?language=fr&lang=de"
406 )
407 assert isinstance(obj, NotifyOneSignal)
408 assert obj.language == "fr"
409
410 # An invalid language= is rejected the same way lang= is
411 with pytest.raises(AppriseImproperlyConfigured):
412 Apprise.instantiate(
413 "onesignal://appid@apikey/player/?language=X",
414 suppress_exceptions=False,
415 )
416
417 # Both settings must survive a url() reload; previously neither was
418 # emitted, so a saved configuration silently reverted to the 'en'
419 # default and dropped the subtitle entirely.
420 obj = Apprise.instantiate(
421 "onesignal://appid@apikey/player/?language=fr&subtitle=Heads%20Up"
422 )
423 assert isinstance(obj, NotifyOneSignal)
424
425 url = obj.url()
426 assert "language=fr" in url
427 assert "subtitle=Heads%20Up" in url
428
429 reloaded = Apprise.instantiate(url)
430 assert isinstance(reloaded, NotifyOneSignal)
431 assert reloaded.language == "fr"
432 assert reloaded.subtitle == "Heads Up"
433 assert reloaded.url() == url
434
435 # The default language is not emitted, and no subtitle means no entry
436 obj = Apprise.instantiate("onesignal://appid@apikey/player")
437 assert isinstance(obj, NotifyOneSignal)
438 assert obj.language == "en"
439 assert "language=" not in obj.url()
440 assert "subtitle=" not in obj.url()
441
442 # The language keys the payload OneSignal is sent, so losing it changed
443 # what was actually delivered
444 assert reloaded.notify(title="Title", body="Body") is True
445 assert mock_post.call_count == 1
446 payload = loads(mock_post.call_args_list[0][1]["data"])
447 assert payload["headings"] == {"fr": "Title"}
448 assert payload["contents"] == {"fr": "Body"}
449 assert payload["subtitle"] == {"fr": "Heads Up"}
450
451
452 @mock.patch("requests.post")
453 def test_plugin_onesignal_notifications(mock_post):
454 """OneSignal() Notifications Support."""
455 # Prepare Mock
456 mock_post.return_value = requests.Request()
457 mock_post.return_value.status_code = requests.codes.ok
458
459 # Load URL with Template
460 instance = Apprise.instantiate(
461 "onesignal://templateid:appid@apikey/@user/?:key1=value1&+key3=value3"
462 )
463
464 # Validate that it loaded okay
465 assert isinstance(instance, NotifyOneSignal)
466
467 response = instance.notify("hello world")
468 assert response is True
469 assert mock_post.call_count == 1
470 assert (
471 mock_post.call_args_list[0][0][0]
472 == "https://api.onesignal.com/notifications"
473 )
474
475 details = mock_post.call_args_list[0]
476 payload = loads(details[1]["data"])
477
478 assert payload == {
479 "app_id": "appid",
480 "contents": {"en": "hello world"},
481 "content_available": True,
482 "template_id": "templateid",
483 "custom_data": {"key1": "value1"},
484 "data": {"key3": "value3"},
485 "large_icon": (
486 "https://github.com/caronc/apprise"
487 "/raw/master/apprise/assets/themes/default/apprise-info-72x72.png"
488 ),
489 "small_icon": (
490 "https://github.com/caronc/apprise"
491 "/raw/master/apprise/assets/themes/default/apprise-info-32x32.png"
492 ),
493 "include_external_user_ids": ["@user"],
494 }
495
496 mock_post.reset_mock()
497
498 # Load URL with Template and disable body
499 instance = Apprise.instantiate(
500 "onesignal://templateid:appid@apikey/@user/?contents=no"
501 )
502
503 # Validate that it loaded okay
504 assert isinstance(instance, NotifyOneSignal)
505
506 response = instance.notify("hello world")
507 assert response is True
508 assert mock_post.call_count == 1
509 assert (
510 mock_post.call_args_list[0][0][0]
511 == "https://api.onesignal.com/notifications"
512 )
513
514 details = mock_post.call_args_list[0]
515 payload = loads(details[1]["data"])
516
517 assert payload == {
518 "app_id": "appid",
519 "content_available": True,
520 "template_id": "templateid",
521 "large_icon": (
522 "https://github.com/caronc/apprise"
523 "/raw/master/apprise/assets/themes/default/apprise-info-72x72.png"
524 ),
525 "small_icon": (
526 "https://github.com/caronc/apprise"
527 "/raw/master/apprise/assets/themes/default/apprise-info-32x32.png"
528 ),
529 "include_external_user_ids": ["@user"],
530 }
531
532 # Now set a title
533 mock_post.reset_mock()
534
535 response = instance.notify("hello world", title="mytitle")
536
537 assert response is True
538 assert mock_post.call_count == 1
539 assert (
540 mock_post.call_args_list[0][0][0]
541 == "https://api.onesignal.com/notifications"
542 )
543
544 details = mock_post.call_args_list[0]
545 payload = loads(details[1]["data"])
546
547 assert payload == {
548 "app_id": "appid",
549 "headings": {"en": "mytitle"},
550 "content_available": True,
551 "template_id": "templateid",
552 "large_icon": (
553 "https://github.com/caronc/apprise"
554 "/raw/master/apprise/assets/themes/default/apprise-info-72x72.png"
555 ),
556 "small_icon": (
557 "https://github.com/caronc/apprise"
558 "/raw/master/apprise/assets/themes/default/apprise-info-32x32.png"
559 ),
560 "include_external_user_ids": ["@user"],
561 }
562
563 # Test without decoding parameters
564 instance = Apprise.instantiate(
565 "onesignal://templateid:appid@apikey/@user/"
566 "?:par=b64:eyJhIjoxLCJiIjoyfQ==&decode=no"
567 )
568 assert isinstance(instance, NotifyOneSignal) and instance.custom_data == {
569 "par": "b64:eyJhIjoxLCJiIjoyfQ=="
570 }
571
572 # Now same with loading parameters
573 instance = Apprise.instantiate(
574 "onesignal://templateid:appid@apikey/@user/"
575 "?:par=b64:eyJhIjoxLCJiIjoyfQ==&decode=yes"
576 )
577 assert isinstance(instance, NotifyOneSignal) and instance.custom_data == {
578 "par": {"a": 1, "b": 2}
579 }
580
581 # Test bad data in general
582 instance = Apprise.instantiate(
583 "onesignal://templateid:appid@apikey/@user/?:par=garbage1&decode=yes"
584 )
585 assert isinstance(instance, NotifyOneSignal) and instance.custom_data == {
586 "par": "garbage1"
587 }
588
589 instance = Apprise.instantiate(
590 "onesignal://templateid:appid@apikey/@user/"
591 "?:par=b64:garbage2&decode=yes"
592 )
593 assert isinstance(instance, NotifyOneSignal) and instance.custom_data == {
594 "par": "b64:garbage2"
595 }
596
597 instance = Apprise.instantiate(
598 "onesignal://templateid:appid@apikey/@user/"
599 "?:par=b64:garbage3==&decode=yes"
600 )
601 assert isinstance(instance, NotifyOneSignal) and instance.custom_data == {
602 "par": "b64:garbage3=="
603 }
604
605 # Now same with not-base64 parameters
606 instance = Apprise.instantiate(
607 "onesignal://templateid:appid@apikey/@user/"
608 "?:par=eyJhIjoxLCJiIjoyfQ==&:par2=123&decode=yes"
609 )
610 assert isinstance(instance, NotifyOneSignal) and instance.custom_data == {
611 "par": "eyJhIjoxLCJiIjoyfQ==",
612 "par2": "123",
613 }
614
615 # Test incorrect base64 parameters. Second one has incorrect padding
616 url = (
617 "onesignal://templateid:appid@apikey/@user/"
618 "?:par=b64:1234=&:par2=b64:eyJhIjoxLCJiIjoyfQ&"
619 ":par3=b64:eyJhIjoxLCJiIjoyfQ==&decode=yes"
620 )
621 instance = Apprise.instantiate(url)
622 assert isinstance(instance, NotifyOneSignal) and instance.custom_data == {
623 "par": "b64:1234=",
624 "par2": "b64:eyJhIjoxLCJiIjoyfQ",
625 "par3": {"a": 1, "b": 2},
626 }