Debian Codegraph @

tests/test_notify_base.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 datetime import datetime, timedelta
29
30 # Disable logging for a cleaner testing output
31 import logging
32 from timeit import default_timer
33
34 import pytest
35
36 from apprise import AppriseAsset, NotifyImageSize, NotifyType
37 from apprise.plugins import NotifyBase
38
39 logging.disable(logging.CRITICAL)
40
41
42 def test_notify_base():
43 """
44 API: NotifyBase() object
45
46 """
47
48 # invalid types throw exceptions
49 with pytest.raises(TypeError):
50 NotifyBase(**{"format": "invalid"})
51
52 # invalid types throw exceptions
53 with pytest.raises(TypeError):
54 NotifyBase(**{"overflow": "invalid"})
55
56 # Bad port information
57 nb = NotifyBase(port="invalid")
58 assert nb.port is None
59
60 nb = NotifyBase(port=10)
61 assert nb.port == 10
62
63 assert isinstance(nb.url(), str)
64 assert str(nb) == nb.url()
65
66 with pytest.raises(NotImplementedError):
67 # Each sub-module is that inherits this as a parent is required to
68 # over-ride this function. So direct calls to this throws a not
69 # implemented error intentionally
70 nb.send("test message")
71
72 # Throttle overrides..
73 nb = NotifyBase()
74 nb.request_rate_per_sec = 0.0
75 start_time = default_timer()
76 nb.throttle()
77 elapsed = default_timer() - start_time
78 # Should be a very fast response time since we set it to zero but we'll
79 # check for less then 500 to be fair as some testing systems may be slower
80 # then other
81 assert elapsed < 0.5
82
83 # Concurrent calls should achieve the same response
84 start_time = default_timer()
85 nb.throttle()
86 elapsed = default_timer() - start_time
87 assert elapsed < 0.5
88
89 nb = NotifyBase()
90 nb.request_rate_per_sec = 1.0
91
92 # Set our time to now
93 start_time = default_timer()
94 nb.throttle()
95 elapsed = default_timer() - start_time
96 # A first call to throttle (Without telling it a time previously ran) does
97 # not block for any length of time; it just merely sets us up for
98 # concurrent calls to block
99 assert elapsed < 0.5
100
101 # Concurrent calls could take up to the rate_per_sec though...
102 start_time = default_timer()
103 nb.throttle(last_io=datetime.now())
104 elapsed = default_timer() - start_time
105 assert elapsed > 0.48 and elapsed < 1.5
106
107 nb = NotifyBase()
108 nb.request_rate_per_sec = 1.0
109
110 # Set our time to now
111 start_time = default_timer()
112 nb.throttle(last_io=datetime.now())
113 elapsed = default_timer() - start_time
114 # because we told it that we had already done a previous action (now)
115 # the throttle holds out until the right time has passed
116 assert elapsed > 0.48 and elapsed < 1.5
117
118 # Concurrent calls could take up to the rate_per_sec though...
119 start_time = default_timer()
120 nb.throttle(last_io=datetime.now())
121 elapsed = default_timer() - start_time
122 assert elapsed > 0.48 and elapsed < 1.5
123
124 nb = NotifyBase()
125 start_time = default_timer()
126 nb.request_rate_per_sec = 1.0
127 # Force a time in the past
128 nb.throttle(last_io=(datetime.now() - timedelta(seconds=20)))
129 elapsed = default_timer() - start_time
130 # Should be a very fast response time since we set it to zero but we'll
131 # check for less then 500 to be fair as some testing systems may be slower
132 # then other
133 assert elapsed < 0.5
134
135 # Force a throttle time
136 start_time = default_timer()
137 nb.throttle(wait=0.5)
138 elapsed = default_timer() - start_time
139 assert elapsed > 0.48 and elapsed < 1.5
140
141 # our NotifyBase wasn't initialized with an ImageSize so this will fail
142 assert nb.image_url(notify_type=NotifyType.INFO) is None
143 assert nb.image_path(notify_type=NotifyType.INFO) is None
144 assert nb.image_raw(notify_type=NotifyType.INFO) is None
145
146 # Color handling
147 assert nb.color(notify_type="invalid") == AppriseAsset.default_html_color
148 assert isinstance(
149 nb.color(notify_type=NotifyType.INFO, color_type=None), str
150 )
151 assert isinstance(
152 nb.color(notify_type=NotifyType.INFO, color_type=int), int
153 )
154 assert isinstance(
155 nb.color(notify_type=NotifyType.INFO, color_type=tuple), tuple
156 )
157
158 # Ascii Handling
159 assert nb.ascii(notify_type="invalid") == AppriseAsset.default_ascii_chars
160 assert nb.ascii(NotifyType.INFO) == "[i]"
161 assert nb.ascii(NotifyType.SUCCESS) == "[+]"
162 assert nb.ascii(NotifyType.WARNING) == "[~]"
163 assert nb.ascii(NotifyType.FAILURE) == "[!]"
164
165 # Create an object
166 nb = NotifyBase()
167 # Force an image size since the default doesn't have one
168 nb.image_size = NotifyImageSize.XY_256
169
170 # We'll get an object this time around
171 assert nb.image_url(notify_type=NotifyType.INFO) is not None
172 assert nb.image_path(notify_type=NotifyType.INFO) is not None
173 assert nb.image_raw(notify_type=NotifyType.INFO) is not None
174
175 # Static function testing
176 assert (
177 NotifyBase.escape_html("<content>'\t \n</content>")
178 == "&lt;content&gt;&apos;&emsp;&nbsp;\n&lt;/content&gt;"
179 )
180
181 assert (
182 NotifyBase.escape_html(
183 "<content>'\t \n</content>", convert_new_lines=True
184 )
185 == "&lt;content&gt;&apos;&emsp;&nbsp;<br/>&lt;/content&gt;"
186 )
187
188 # Test invalid data
189 assert NotifyBase.split_path(None) == []
190 assert NotifyBase.split_path(object()) == []
191 assert NotifyBase.split_path(42) == []
192
193 assert NotifyBase.split_path(
194 "/path/?name=Dr%20Disrespect", unquote=False
195 ) == [
196 "path",
197 "?name=Dr%20Disrespect",
198 ]
199
200 assert NotifyBase.split_path(
201 "/path/?name=Dr%20Disrespect", unquote=True
202 ) == [
203 "path",
204 "?name=Dr Disrespect",
205 ]
206
207 # a slash found inside the path, if escaped properly will not be broken
208 # by split_path while additional concatinated slashes are ignored
209 # FYI: %2F = /
210 assert NotifyBase.split_path(
211 "/%2F///%2F%2F////%2F%2F%2F////", unquote=True
212 ) == [
213 "/",
214 "//",
215 "///",
216 ]
217
218 # Test invalid data
219 assert NotifyBase.parse_list(None) == []
220 assert NotifyBase.parse_list(object()) == []
221 assert NotifyBase.parse_list(42) == []
222
223 result = NotifyBase.parse_list(
224 ",path,?name=Dr%20Disrespect", unquote=False
225 )
226 assert isinstance(result, list)
227 assert len(result) == 2
228 assert "path" in result
229 assert "?name=Dr%20Disrespect" in result
230
231 result = NotifyBase.parse_list(",path,?name=Dr%20Disrespect", unquote=True)
232 assert isinstance(result, list)
233 assert len(result) == 2
234 assert "path" in result
235 assert "?name=Dr Disrespect" in result
236
237 # by parse_list while additional concatinated slashes are ignored
238 # FYI: %2F = /
239 # In this lit there are actually 4 entries, however parse_list
240 # eliminates duplicates in addition to unquoting content by default
241 result = NotifyBase.parse_list(
242 ",%2F,%2F%2F, , , ,%2F%2F%2F, %2F", unquote=True
243 )
244 assert isinstance(result, list)
245 assert len(result) == 3
246 assert "/" in result
247 assert "//" in result
248 assert "///" in result
249
250 # Phone number parsing
251 assert NotifyBase.parse_phone_no(None) == []
252 assert NotifyBase.parse_phone_no(object()) == []
253 assert NotifyBase.parse_phone_no(42) == []
254
255 result = NotifyBase.parse_phone_no(
256 "+1-800-123-1234,(800) 123-4567", unquote=False
257 )
258 assert isinstance(result, list)
259 assert len(result) == 2
260 assert "+1-800-123-1234" in result
261 assert "(800) 123-4567" in result
262
263 # %2B == +
264 result = NotifyBase.parse_phone_no(
265 "%2B1-800-123-1234,%2B1%20800%20123%204567", unquote=True
266 )
267 assert isinstance(result, list)
268 assert len(result) == 2
269 assert "+1-800-123-1234" in result
270 assert "+1 800 123 4567" in result
271
272 # Give nothing, get nothing
273 assert NotifyBase.escape_html("") == ""
274 assert NotifyBase.escape_html(None) == ""
275 assert NotifyBase.escape_html(object()) == ""
276
277 # Test quote
278 assert NotifyBase.unquote("%20") == " "
279 assert NotifyBase.quote(" ") == "%20"
280 assert NotifyBase.unquote(None) == ""
281 assert NotifyBase.quote(None) == ""
282
283
284 def test_notify_base_urls():
285 """
286 API: NotifyBase() URLs
287
288 """
289
290 # Test verify switch whih is used as part of the SSL Verification
291 # by default all SSL sites are verified unless this flag is set to
292 # something like 'No', 'False', 'Disabled', etc. Boolean values are
293 # pretty forgiving.
294 results = NotifyBase.parse_url("https://localhost:8080/?verify=No")
295 assert "verify" in results
296 assert results["verify"] is False
297
298 results = NotifyBase.parse_url("https://localhost:8080/?verify=Yes")
299 assert "verify" in results
300 assert results["verify"] is True
301
302 # The default is to verify
303 results = NotifyBase.parse_url("https://localhost:8080")
304 assert "verify" in results
305 assert results["verify"] is True
306
307 # Password Handling
308
309 # pass keyword over-rides default password
310 results = NotifyBase.parse_url("https://user:pass@localhost")
311 assert "password" in results
312 assert results["password"] == "pass"
313
314 # pass keyword over-rides default password
315 results = NotifyBase.parse_url(
316 "https://user:pass@localhost?pass=newpassword"
317 )
318 assert "password" in results
319 assert results["password"] == "newpassword"
320
321 # password keyword can also optionally be used
322 results = NotifyBase.parse_url(
323 "https://user:pass@localhost?password=passwd"
324 )
325 assert "password" in results
326 assert results["password"] == "passwd"
327
328 # pass= override password=
329 # password keyword can also optionally be used
330 results = NotifyBase.parse_url(
331 "https://user:pass@localhost?pass=pw1&password=pw2"
332 )
333 assert "password" in results
334 assert results["password"] == "pw1"
335
336 # Options
337 results = NotifyBase.parse_url("https://localhost?format=invalid")
338 assert "format" not in results
339 results = NotifyBase.parse_url("https://localhost?format=text")
340 assert "format" in results
341 assert results["format"] == "text"
342 results = NotifyBase.parse_url("https://localhost?format=markdown")
343 assert "format" in results
344 assert results["format"] == "markdown"
345 results = NotifyBase.parse_url("https://localhost?format=html")
346 assert "format" in results
347 assert results["format"] == "html"
348
349 results = NotifyBase.parse_url("https://localhost?overflow=invalid")
350 assert "overflow" not in results
351 results = NotifyBase.parse_url("https://localhost?overflow=upstream")
352 assert "overflow" in results
353 assert results["overflow"] == "upstream"
354 results = NotifyBase.parse_url("https://localhost?overflow=split")
355 assert "overflow" in results
356 assert results["overflow"] == "split"
357 results = NotifyBase.parse_url("https://localhost?overflow=truncate")
358 assert "overflow" in results
359 assert results["overflow"] == "truncate"
360
361 # User Handling
362
363 # user keyword over-rides default password
364 results = NotifyBase.parse_url("https://user:pass@localhost")
365 assert "user" in results
366 assert results["user"] == "user"
367
368 # user keyword over-rides default password
369 results = NotifyBase.parse_url("https://user:pass@localhost?user=newuser")
370 assert "user" in results
371 assert results["user"] == "newuser"
372
373 # Test invalid urls
374 assert NotifyBase.parse_url("https://:@/") is None
375 assert NotifyBase.parse_url("http://:@") is None
376 assert NotifyBase.parse_url("http://@") is None
377 assert NotifyBase.parse_url("http:///") is None
378 assert NotifyBase.parse_url("http://:test/") is None
379 assert NotifyBase.parse_url("http://pass:test/") is None
380
381
382 def test_notify_base_runtime_deps():
383 """NotifyBase.runtime_deps() returns an empty tuple by default."""
384
385 assert NotifyBase.runtime_deps() == ()
386 assert isinstance(NotifyBase.runtime_deps(), tuple)
387
388
389 def test_notify_base_enable_disable():
390 """NotifyBase.enable() and disable() toggle the enabled flag."""
391
392 class ToggleNotification(NotifyBase):
393 protocol = "toggle"
394
395 def notify(self, *args, **kwargs):
396 return True
397
398 def url(self, **kwargs):
399 return "toggle://"
400
401 # Starts enabled
402 assert ToggleNotification.enabled is True
403
404 # disable() sets it False
405 ToggleNotification.disable()
406 assert ToggleNotification.enabled is False
407
408 # enable() restores it
409 ToggleNotification.enable()
410 assert ToggleNotification.enabled is True
411
412 # Calling disable() twice is idempotent
413 ToggleNotification.disable()
414 ToggleNotification.disable()
415 assert ToggleNotification.enabled is False
416
417 # Calling enable() twice is idempotent
418 ToggleNotification.enable()
419 ToggleNotification.enable()
420 assert ToggleNotification.enabled is True
421
422 # Changes are on the class, not on instances
423 instance = ToggleNotification(host="localhost")
424 ToggleNotification.disable()
425 assert instance.enabled is False
426 ToggleNotification.enable()
427 assert instance.enabled is True
428
429
430 def test_notify_base_runtime_deps_override():
431 """Subclasses can override runtime_deps() to declare their dependencies."""
432
433 class DepFreePlugin(NotifyBase):
434 protocol = "depfree"
435
436 def notify(self, *args, **kwargs):
437 return True
438
439 def url(self, **kwargs):
440 return "depfree://"
441
442 class SingleDepPlugin(NotifyBase):
443 protocol = "singledep"
444
445 def notify(self, *args, **kwargs):
446 return True
447
448 def url(self, **kwargs):
449 return "singledep://"
450
451 @staticmethod
452 def runtime_deps():
453 return ("fakelibA",)
454
455 class MultiDepPlugin(NotifyBase):
456 protocol = "multidep"
457
458 def notify(self, *args, **kwargs):
459 return True
460
461 def url(self, **kwargs):
462 return "multidep://"
463
464 @staticmethod
465 def runtime_deps():
466 return ("fakelibA", "fakelibB")
467
468 # No override -> inherits the empty tuple from NotifyBase
469 assert DepFreePlugin.runtime_deps() == ()
470
471 # Single-dep override
472 assert SingleDepPlugin.runtime_deps() == ("fakelibA",)
473
474 # Multi-dep override preserves order
475 deps = MultiDepPlugin.runtime_deps()
476 assert deps == ("fakelibA", "fakelibB")
477 assert deps[0] == "fakelibA"
478 assert deps[1] == "fakelibB"