Debian Codegraph @

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