Debian Codegraph @

tests/test_notify_base.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 import asyncio
29 from datetime import datetime, timedelta
30 import glob
31
32 # Disable logging for a cleaner testing output
33 import logging
34 import time
35 from timeit import default_timer
36
37 import pytest
38
39 from apprise import AppriseAsset, NotifyFormat, NotifyImageSize, NotifyType
40 from apprise.common import OverflowMode
41 from apprise.exception import AppriseImproperlyConfigured
42 from apprise.plugins import NotifyBase
43
44 logging.disable(logging.CRITICAL)
45
46
47 def test_notify_base():
48 """
49 API: NotifyBase() object
50
51 """
52
53 # invalid types throw exceptions
54 with pytest.raises(AppriseImproperlyConfigured):
55 NotifyBase(**{"format": "invalid"})
56
57 # invalid types throw exceptions
58 with pytest.raises(AppriseImproperlyConfigured):
59 NotifyBase(**{"overflow": "invalid"})
60
61 # Bad port information
62 nb = NotifyBase(port="invalid")
63 assert nb.port is None
64
65 nb = NotifyBase(port=10)
66 assert nb.port == 10
67
68 assert isinstance(nb.url(), str)
69 assert str(nb) == nb.url()
70
71 with pytest.raises(NotImplementedError):
72 # Each sub-module is that inherits this as a parent is required to
73 # over-ride this function. So direct calls to this throws a not
74 # implemented error intentionally
75 nb.send("test message")
76
77 # Throttle overrides..
78 nb = NotifyBase()
79 nb.request_rate_per_sec = 0.0
80 start_time = default_timer()
81 nb.throttle()
82 elapsed = default_timer() - start_time
83 # Should be a very fast response time since we set it to zero but we'll
84 # check for less then 500 to be fair as some testing systems may be slower
85 # then other
86 assert elapsed < 0.5
87
88 # Concurrent calls should achieve the same response
89 start_time = default_timer()
90 nb.throttle()
91 elapsed = default_timer() - start_time
92 assert elapsed < 0.5
93
94 nb = NotifyBase()
95 nb.request_rate_per_sec = 1.0
96
97 # Set our time to now
98 start_time = default_timer()
99 nb.throttle()
100 elapsed = default_timer() - start_time
101 # A first call to throttle (Without telling it a time previously ran) does
102 # not block for any length of time; it just merely sets us up for
103 # concurrent calls to block
104 assert elapsed < 0.5
105
106 # Concurrent calls could take up to the rate_per_sec though...
107 start_time = default_timer()
108 nb.throttle(last_io=datetime.now())
109 elapsed = default_timer() - start_time
110 assert elapsed > 0.48 and elapsed < 1.5
111
112 nb = NotifyBase()
113 nb.request_rate_per_sec = 1.0
114
115 # Set our time to now
116 start_time = default_timer()
117 nb.throttle(last_io=datetime.now())
118 elapsed = default_timer() - start_time
119 # because we told it that we had already done a previous action (now)
120 # the throttle holds out until the right time has passed
121 assert elapsed > 0.48 and elapsed < 1.5
122
123 # Concurrent calls could take up to the rate_per_sec though...
124 start_time = default_timer()
125 nb.throttle(last_io=datetime.now())
126 elapsed = default_timer() - start_time
127 assert elapsed > 0.48 and elapsed < 1.5
128
129 nb = NotifyBase()
130 start_time = default_timer()
131 nb.request_rate_per_sec = 1.0
132 # Force a time in the past
133 nb.throttle(last_io=(datetime.now() - timedelta(seconds=20)))
134 elapsed = default_timer() - start_time
135 # Should be a very fast response time since we set it to zero but we'll
136 # check for less then 500 to be fair as some testing systems may be slower
137 # then other
138 assert elapsed < 0.5
139
140 # Force a throttle time
141 start_time = default_timer()
142 nb.throttle(wait=0.5)
143 elapsed = default_timer() - start_time
144 assert elapsed > 0.48 and elapsed < 1.5
145
146 # our NotifyBase wasn't initialized with an ImageSize so this will fail
147 assert nb.image_url(notify_type=NotifyType.INFO) is None
148 assert nb.image_path(notify_type=NotifyType.INFO) is None
149 assert nb.image_raw(notify_type=NotifyType.INFO) is None
150
151 # Color handling
152 assert nb.color(notify_type="invalid") == AppriseAsset.default_html_color
153 assert isinstance(
154 nb.color(notify_type=NotifyType.INFO, color_type=None), str
155 )
156 assert isinstance(
157 nb.color(notify_type=NotifyType.INFO, color_type=int), int
158 )
159 assert isinstance(
160 nb.color(notify_type=NotifyType.INFO, color_type=tuple), tuple
161 )
162
163 # Ascii Handling
164 assert nb.ascii(notify_type="invalid") == AppriseAsset.default_ascii_chars
165 assert nb.ascii(NotifyType.INFO) == "[i]"
166 assert nb.ascii(NotifyType.SUCCESS) == "[+]"
167 assert nb.ascii(NotifyType.WARNING) == "[~]"
168 assert nb.ascii(NotifyType.FAILURE) == "[!]"
169
170 # Create an object
171 nb = NotifyBase()
172 # Force an image size since the default doesn't have one
173 nb.image_size = NotifyImageSize.XY_256
174
175 # We'll get an object this time around
176 assert nb.image_url(notify_type=NotifyType.INFO) is not None
177 assert nb.image_path(notify_type=NotifyType.INFO) is not None
178 assert nb.image_raw(notify_type=NotifyType.INFO) is not None
179
180 # Static function testing
181 assert (
182 NotifyBase.escape_html("<content>'\t \n</content>")
183 == "&lt;content&gt;&apos;&emsp;&nbsp;\n&lt;/content&gt;"
184 )
185
186 assert (
187 NotifyBase.escape_html(
188 "<content>'\t \n</content>", convert_new_lines=True
189 )
190 == "&lt;content&gt;&apos;&emsp;&nbsp;<br/>&lt;/content&gt;"
191 )
192
193 # Test invalid data
194 assert NotifyBase.split_path(None) == []
195 assert NotifyBase.split_path(object()) == []
196 assert NotifyBase.split_path(42) == []
197
198 assert NotifyBase.split_path(
199 "/path/?name=Dr%20Disrespect", unquote=False
200 ) == [
201 "path",
202 "?name=Dr%20Disrespect",
203 ]
204
205 assert NotifyBase.split_path(
206 "/path/?name=Dr%20Disrespect", unquote=True
207 ) == [
208 "path",
209 "?name=Dr Disrespect",
210 ]
211
212 # a slash found inside the path, if escaped properly will not be broken
213 # by split_path while additional concatinated slashes are ignored
214 # FYI: %2F = /
215 assert NotifyBase.split_path(
216 "/%2F///%2F%2F////%2F%2F%2F////", unquote=True
217 ) == [
218 "/",
219 "//",
220 "///",
221 ]
222
223 # Test invalid data
224 assert NotifyBase.parse_list(None) == []
225 assert NotifyBase.parse_list(object()) == []
226 assert NotifyBase.parse_list(42) == []
227
228 result = NotifyBase.parse_list(
229 ",path,?name=Dr%20Disrespect", unquote=False
230 )
231 assert isinstance(result, list)
232 assert len(result) == 2
233 assert "path" in result
234 assert "?name=Dr%20Disrespect" in result
235
236 result = NotifyBase.parse_list(",path,?name=Dr%20Disrespect", unquote=True)
237 assert isinstance(result, list)
238 assert len(result) == 2
239 assert "path" in result
240 assert "?name=Dr Disrespect" in result
241
242 # by parse_list while additional concatinated slashes are ignored
243 # FYI: %2F = /
244 # In this lit there are actually 4 entries, however parse_list
245 # eliminates duplicates in addition to unquoting content by default
246 result = NotifyBase.parse_list(
247 ",%2F,%2F%2F, , , ,%2F%2F%2F, %2F", unquote=True
248 )
249 assert isinstance(result, list)
250 assert len(result) == 3
251 assert "/" in result
252 assert "//" in result
253 assert "///" in result
254
255 # Phone number parsing
256 assert NotifyBase.parse_phone_no(None) == []
257 assert NotifyBase.parse_phone_no(object()) == []
258 assert NotifyBase.parse_phone_no(42) == []
259
260 result = NotifyBase.parse_phone_no(
261 "+1-800-123-1234,(800) 123-4567", unquote=False
262 )
263 assert isinstance(result, list)
264 assert len(result) == 2
265 assert "+1-800-123-1234" in result
266 assert "(800) 123-4567" in result
267
268 # %2B == +
269 result = NotifyBase.parse_phone_no(
270 "%2B1-800-123-1234,%2B1%20800%20123%204567", unquote=True
271 )
272 assert isinstance(result, list)
273 assert len(result) == 2
274 assert "+1-800-123-1234" in result
275 assert "+1 800 123 4567" in result
276
277 # Give nothing, get nothing
278 assert NotifyBase.escape_html("") == ""
279 assert NotifyBase.escape_html(None) == ""
280 assert NotifyBase.escape_html(object()) == ""
281
282 # Test quote
283 assert NotifyBase.unquote("%20") == " "
284 assert NotifyBase.quote(" ") == "%20"
285 assert NotifyBase.unquote(None) == ""
286 assert NotifyBase.quote(None) == ""
287
288
289 def test_notify_base_urls():
290 """
291 API: NotifyBase() URLs
292
293 """
294
295 # Test verify switch whih is used as part of the SSL Verification
296 # by default all SSL sites are verified unless this flag is set to
297 # something like 'No', 'False', 'Disabled', etc. Boolean values are
298 # pretty forgiving.
299 results = NotifyBase.parse_url("https://localhost:8080/?verify=No")
300 assert "verify" in results
301 assert results["verify"] is False
302
303 results = NotifyBase.parse_url("https://localhost:8080/?verify=Yes")
304 assert "verify" in results
305 assert results["verify"] is True
306
307 # The default is to verify
308 results = NotifyBase.parse_url("https://localhost:8080")
309 assert "verify" in results
310 assert results["verify"] is True
311
312 # Password Handling
313
314 # pass keyword over-rides default password
315 results = NotifyBase.parse_url("https://user:pass@localhost")
316 assert "password" in results
317 assert results["password"] == "pass"
318
319 # pass keyword over-rides default password
320 results = NotifyBase.parse_url(
321 "https://user:pass@localhost?pass=newpassword"
322 )
323 assert "password" in results
324 assert results["password"] == "newpassword"
325
326 # password keyword can also optionally be used
327 results = NotifyBase.parse_url(
328 "https://user:pass@localhost?password=passwd"
329 )
330 assert "password" in results
331 assert results["password"] == "passwd"
332
333 # pass= override password=
334 # password keyword can also optionally be used
335 results = NotifyBase.parse_url(
336 "https://user:pass@localhost?pass=pw1&password=pw2"
337 )
338 assert "password" in results
339 assert results["password"] == "pw1"
340
341 # Options
342 results = NotifyBase.parse_url("https://localhost?format=invalid")
343 assert "format" not in results
344 results = NotifyBase.parse_url("https://localhost?format=text")
345 assert "format" in results
346 assert results["format"] == "text"
347 results = NotifyBase.parse_url("https://localhost?format=markdown")
348 assert "format" in results
349 assert results["format"] == "markdown"
350 results = NotifyBase.parse_url("https://localhost?format=html")
351 assert "format" in results
352 assert results["format"] == "html"
353
354 results = NotifyBase.parse_url("https://localhost?overflow=invalid")
355 assert "overflow" not in results
356 results = NotifyBase.parse_url("https://localhost?overflow=upstream")
357 assert "overflow" in results
358 assert results["overflow"] == "upstream"
359 results = NotifyBase.parse_url("https://localhost?overflow=split")
360 assert "overflow" in results
361 assert results["overflow"] == "split"
362 results = NotifyBase.parse_url("https://localhost?overflow=truncate")
363 assert "overflow" in results
364 assert results["overflow"] == "truncate"
365
366 # User Handling
367
368 # user keyword over-rides default password
369 results = NotifyBase.parse_url("https://user:pass@localhost")
370 assert "user" in results
371 assert results["user"] == "user"
372
373 # user keyword over-rides default password
374 results = NotifyBase.parse_url("https://user:pass@localhost?user=newuser")
375 assert "user" in results
376 assert results["user"] == "newuser"
377
378 # Test invalid urls
379 assert NotifyBase.parse_url("https://:@/") is None
380 assert NotifyBase.parse_url("http://:@") is None
381 assert NotifyBase.parse_url("http://@") is None
382 assert NotifyBase.parse_url("http:///") is None
383 assert NotifyBase.parse_url("http://:test/") is None
384 assert NotifyBase.parse_url("http://pass:test/") is None
385
386
387 def test_notify_base_runtime_deps():
388 """NotifyBase.runtime_deps() returns an empty tuple by default."""
389
390 assert NotifyBase.runtime_deps() == ()
391 assert isinstance(NotifyBase.runtime_deps(), tuple)
392
393
394 def test_notify_base_dialect_convert_default_noop():
395 """The default dialect hook leaves content unchanged.
396
397 Framework conversion only calls plugin overrides, so test the base hook
398 directly.
399 """
400
401 class PlainNotification(NotifyBase):
402 protocol = "plain"
403
404 def notify(self, *args, **kwargs):
405 return True
406
407 def url(self, **kwargs):
408 return "plain://"
409
410 instance = PlainNotification(host="localhost")
411 body = "**not markdown-converted**"
412 assert instance.dialect_convert(body) == body
413 assert instance.dialect_convert(body, NotifyFormat.MARKDOWN) == body
414 assert (
415 instance.dialect_convert(body, NotifyFormat.HTML, "extra", flag=True)
416 == body
417 )
418
419
420 def test_notify_base_notify_type_normalization():
421 """A direct plugin notify() call normalizes a recognized string
422 notify_type into a real NotifyType, exactly like format= and overflow=
423 already do for their own values.
424 """
425
426 class RecordingNotification(NotifyBase):
427 protocol = "recording"
428
429 # Exercise the same notify_type.value path used by
430 # AppriseAsset.image_url()/image_path().
431 image_size = NotifyImageSize.XY_256
432
433 received = []
434
435 def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs):
436 self.received.append(notify_type)
437 # Raises AttributeError if notify_type is still a bare string
438 # instead of a real NotifyType.
439 self.image_url(notify_type=notify_type)
440 return True
441
442 def url(self, **kwargs):
443 return "recording://"
444
445 instance = RecordingNotification(host="localhost")
446
447 # A raw string is normalized to the matching NotifyType member.
448 instance.received.clear()
449 assert instance.notify(body="hi", notify_type="warning") is True
450 assert instance.received == [NotifyType.WARNING]
451 assert isinstance(instance.received[0], NotifyType)
452
453 # An actual NotifyType instance passes through unchanged.
454 instance.received.clear()
455 assert instance.notify(body="hi", notify_type=NotifyType.FAILURE) is True
456 assert instance.received == [NotifyType.FAILURE]
457
458 # The same normalization applies to async_notify().
459 instance.received.clear()
460 assert (
461 asyncio.run(instance.async_notify(body="hi", notify_type="success"))
462 is True
463 )
464 assert instance.received == [NotifyType.SUCCESS]
465
466
467 def test_notify_base_notify_type_unrecognized_string_passthrough():
468 """An unrecognized notify_type string is left exactly as provided,"""
469
470 class ToleratingNotification(NotifyBase):
471 protocol = "tolerating"
472
473 received = []
474
475 def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs):
476 # No notify_type.value access here -- mirrors a plugin like
477 # Notifico that only ever compares notify_type by equality.
478 self.received.append(notify_type)
479 return True
480
481 instance = ToleratingNotification(host="localhost")
482
483 instance.received.clear()
484 assert instance.notify(body="hi", notify_type="not-a-type") is True
485 assert instance.received == ["not-a-type"]
486 assert not isinstance(instance.received[0], NotifyType)
487
488
489 def test_notify_base_enable_disable():
490 """NotifyBase.enable() and disable() toggle the enabled flag."""
491
492 class ToggleNotification(NotifyBase):
493 protocol = "toggle"
494
495 def notify(self, *args, **kwargs):
496 return True
497
498 def url(self, **kwargs):
499 return "toggle://"
500
501 # Starts enabled
502 assert ToggleNotification.enabled is True
503
504 # disable() sets it False
505 ToggleNotification.disable()
506 assert ToggleNotification.enabled is False
507
508 # enable() restores it
509 ToggleNotification.enable()
510 assert ToggleNotification.enabled is True
511
512 # Calling disable() twice is idempotent
513 ToggleNotification.disable()
514 ToggleNotification.disable()
515 assert ToggleNotification.enabled is False
516
517 # Calling enable() twice is idempotent
518 ToggleNotification.enable()
519 ToggleNotification.enable()
520 assert ToggleNotification.enabled is True
521
522 # Changes are on the class, not on instances
523 instance = ToggleNotification(host="localhost")
524 ToggleNotification.disable()
525 assert instance.enabled is False
526 ToggleNotification.enable()
527 assert instance.enabled is True
528
529
530 def test_notify_base_runtime_deps_override():
531 """Subclasses can override runtime_deps() to declare their dependencies."""
532
533 class DepFreePlugin(NotifyBase):
534 protocol = "depfree"
535
536 def notify(self, *args, **kwargs):
537 return True
538
539 def url(self, **kwargs):
540 return "depfree://"
541
542 class SingleDepPlugin(NotifyBase):
543 protocol = "singledep"
544
545 def notify(self, *args, **kwargs):
546 return True
547
548 def url(self, **kwargs):
549 return "singledep://"
550
551 @staticmethod
552 def runtime_deps():
553 return ("fakelibA",)
554
555 class MultiDepPlugin(NotifyBase):
556 protocol = "multidep"
557
558 def notify(self, *args, **kwargs):
559 return True
560
561 def url(self, **kwargs):
562 return "multidep://"
563
564 @staticmethod
565 def runtime_deps():
566 return ("fakelibA", "fakelibB")
567
568 # No override -> inherits the empty tuple from NotifyBase
569 assert DepFreePlugin.runtime_deps() == ()
570
571 # Single-dep override
572 assert SingleDepPlugin.runtime_deps() == ("fakelibA",)
573
574 # Multi-dep override preserves order
575 deps = MultiDepPlugin.runtime_deps()
576 assert deps == ("fakelibA", "fakelibB")
577 assert deps[0] == "fakelibA"
578 assert deps[1] == "fakelibB"
579
580
581 def test_notify_base_flush_store_noop_when_unused(tmpdir):
582 """flush_store() is a silent no-op when self.store was never
583 accessed -- it must not create a PersistentStore (or its on-disk
584 directory structure) just to immediately flush nothing."""
585 asset = AppriseAsset(storage_path=str(tmpdir))
586 obj = NotifyBase(asset=asset)
587
588 # Nothing touched .store yet -- flush_store() must not crash, and
589 # must not create any on-disk content for this service.
590 obj.flush_store()
591
592 assert len(tmpdir.listdir()) == 0
593
594
595 def test_notify_base_flush_store_writes_pending_auto_mode_changes(tmpdir):
596 """Write pending automatic-store changes before the process exits.
597
598 Normally these changes remain cached until the store is collected. An
599 immediate process exit must flush them first.
600 """
601 asset = AppriseAsset(storage_path=str(tmpdir))
602 obj = NotifyBase(asset=asset)
603
604 # Accessing .store alone already creates its namespace directory
605 # structure (independent of whether anything is written), so the
606 # cache file itself -- not "any file at all" -- is what actually
607 # indicates a flush occurred.
608 cache_glob = str(tmpdir.join("**", "*.psdata"))
609
610 obj.store.set("token", "abc123")
611
612 # AUTO mode: the cached change has not been written to disk yet.
613 assert glob.glob(cache_glob, recursive=True) == []
614
615 obj.flush_store()
616
617 # The cache file now exists, and the value survives a fresh
618 # PersistentStore instance reading from the same path/namespace.
619 assert glob.glob(cache_glob, recursive=True) != []
620 assert obj.store.get("token") == "abc123"
621
622
623 def test_notify_base_async_notify_preserves_send_order():
624 """async_notify() dispatches each plugin's split pieces in order."""
625
626 call_order = []
627
628 class OrderedNotification(NotifyBase):
629 protocol = "ordered"
630 body_maxlen = 10
631 title_maxlen = 0
632
633 def send(self, body, title="", notify_type=None, **kwargs):
634 # Delay the first piece so concurrent dispatch would reorder it.
635 time.sleep(0.05 if kwargs.get("index") == 0 else 0)
636 call_order.append(kwargs.get("index"))
637 return True
638
639 def url(self, **kwargs):
640 return "ordered://"
641
642 instance = OrderedNotification(host="localhost")
643
644 # 50 characters split at a 10-character limit produces 5 pieces.
645 body = "0123456789" * 5
646 result = asyncio.run(
647 instance.async_notify(body=body, overflow=OverflowMode.SPLIT)
648 )
649 assert result is True
650 assert call_order == [0, 1, 2, 3, 4]