Debian Codegraph @

tests/helpers/rest.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
29
30 # Disable logging for a cleaner testing output
31 import logging
32 import os
33 from random import choice
34 import re
35 from string import ascii_uppercase as str_alpha, digits as str_num
36 from unittest import mock
37
38 import requests
39
40 from apprise import (
41 Apprise,
42 AppriseAsset,
43 AppriseAttachment,
44 NotifyBase,
45 NotifyType,
46 PersistentStoreMode,
47 )
48 from apprise.common import OverflowMode
49
50 logging.disable(logging.CRITICAL)
51
52
53 class AppriseURLTester:
54 # Some exception handling we'll use
55 req_exceptions = (
56 requests.ConnectionError(0, "requests.ConnectionError() not handled"),
57 requests.RequestException(
58 0, "requests.RequestException() not handled"
59 ),
60 requests.HTTPError(0, "requests.HTTPError() not handled"),
61 requests.ReadTimeout(0, "requests.ReadTimeout() not handled"),
62 requests.TooManyRedirects(
63 0, "requests.TooManyRedirects() not handled"
64 ),
65 )
66
67 # Attachment Testing Directory
68 __test_var_dir = os.path.join(
69 os.path.dirname(os.path.dirname(__file__)), "var"
70 )
71
72 # Our URLs we'll test against
73 __tests = []
74
75 # Define how many characters exist per line
76 row = 80
77
78 # Some variables we use to control the data we work with
79 body_len = 1024
80 title_len = 1024
81
82 def __init__(self, tests=None, *args, **kwargs):
83 """Our initialization."""
84 # Create a large body and title with random data
85 self.body = "".join(
86 choice(str_alpha + str_num + " ") for _ in range(self.body_len)
87 )
88 self.body = "\r\n".join(
89 [
90 self.body[i : i + self.row]
91 for i in range(0, len(self.body), self.row)
92 ]
93 )
94
95 # Create our title using random data
96 self.title = "".join(
97 choice(str_alpha + str_num) for _ in range(self.title_len)
98 )
99
100 if tests:
101 self.__tests = tests
102
103 def add(self, url, meta):
104 """Adds a test suite to our object."""
105 self.__tests.append(
106 {
107 "url": url,
108 "meta": meta,
109 }
110 )
111
112 def run_all(self, tmpdir=None):
113 """Run all of our tests."""
114 # iterate over our dictionary and test it out
115 for url, meta in self.__tests:
116 self.run(url, meta, tmpdir)
117
118 @mock.patch("requests.get")
119 @mock.patch("requests.post")
120 @mock.patch("requests.request")
121 def run(self, url, meta, tmpdir, mock_request, mock_post, mock_get):
122 """Run a specific test."""
123
124 if meta is False:
125 # Prepare a default structure to make life easy
126 meta = {
127 "instance": TypeError,
128 }
129
130 # Our expected instance
131 instance = meta.get("instance")
132
133 # Our expected server objects
134 self_ = meta.get("self")
135
136 # Our expected privacy url
137 # Don't set this if don't need to check it's value
138 privacy_url = meta.get("privacy_url")
139
140 # Our regular expression
141 url_matches = meta.get("url_matches")
142
143 # Detect our storage path (used to set persistent storage
144 # mode
145 storage_path = (
146 tmpdir
147 if tmpdir and isinstance(tmpdir, str) and os.path.isdir(tmpdir)
148 else None
149 )
150
151 # Our storage mode to set
152 storage_mode = meta.get(
153 "storage_mode",
154 (
155 PersistentStoreMode.MEMORY
156 if not storage_path
157 else PersistentStoreMode.AUTO
158 ),
159 )
160
161 # Debug Mode
162 pdb = meta.get("pdb", False)
163
164 # Whether or not we should include an image with our request; unless
165 # otherwise specified, we assume that images are to be included
166 include_image = meta.get("include_image", True)
167 if include_image:
168 # a default asset
169 asset = AppriseAsset(
170 storage_mode=storage_mode,
171 storage_path=storage_path,
172 )
173
174 else:
175 # Disable images
176 asset = AppriseAsset(
177 image_path_mask=False,
178 image_url_mask=False,
179 storage_mode=storage_mode,
180 storage_path=storage_path,
181 )
182 asset.image_url_logo = None
183
184 # Mock our request object
185 robj = mock.Mock()
186 robj.content = ""
187 mock_get.return_value = robj
188 mock_post.return_value = robj
189 mock_request.return_value = robj
190
191 if pdb:
192 # Makes it easier to debug with this peice of code
193 # just add `pdb': True to the call that is failing
194 import pdb
195
196 pdb.set_trace()
197
198 try:
199 # We can now instantiate our object:
200 obj = Apprise.instantiate(
201 url, asset=asset, suppress_exceptions=False
202 )
203
204 except Exception as e:
205 # Handle our exception
206 if instance is None:
207 raise e
208
209 if not isinstance(e, instance):
210 raise e
211
212 # We're okay if we get here
213 return
214
215 if obj is None:
216 if instance is not None:
217 # We're done (assuming this is what we were
218 # expecting)
219 raise AssertionError()
220 # We're done because we got the results we expected
221 return
222
223 if instance is None:
224 # Expected None but didn't get it
225 raise AssertionError()
226
227 if not isinstance(obj, instance):
228 raise AssertionError()
229
230 if isinstance(obj, NotifyBase):
231 # Ensure we are not performing any type of thorttling
232 obj.request_rate_per_sec = 0
233
234 # We loaded okay; now lets make sure we can reverse
235 # this url
236 assert isinstance(obj.url(), str) is True
237
238 # Test that we support a url identifier
239 url_id = obj.url_id()
240
241 # It can be either disabled or a string; nothing else
242 assert isinstance(url_id, str) or (
243 url_id is None and obj.url_identifier is False
244 )
245
246 # Verify we can acquire a target count as an integer
247 assert isinstance(len(obj), int)
248
249 # Test url() with privacy=True
250 assert isinstance(obj.url(privacy=True), str) is True
251
252 # Some Simple Invalid Instance Testing
253 assert instance.parse_url(None) is None
254 assert instance.parse_url(object) is None
255 assert instance.parse_url(42) is None
256
257 # Assess that our privacy url is as expected
258 if privacy_url and not obj.url(privacy=True).startswith(
259 privacy_url
260 ):
261 raise AssertionError(
262 f"URL: {url} Privacy URL:"
263 f" '{obj.url(privacy=True)[: len(privacy_url)]}' !="
264 f" expected '{privacy_url}'"
265 )
266
267 # Assess that our URL matches a set regex
268 if url_matches and not re.search(url_matches, obj.url()):
269 raise AssertionError(
270 f"URL: {url} generated an reloadable "
271 f"url() of {obj.url()} that does not match "
272 f"'{url_matches}'"
273 )
274
275 # Instantiate the exact same object again using the URL
276 # from the one that was already created properly
277 obj_cmp = Apprise.instantiate(obj.url())
278
279 if not isinstance(obj_cmp, NotifyBase):
280 raise AssertionError(
281 f"URL: {url} generated an un-reloadable "
282 f"url() of {obj.url()}"
283 )
284
285 # Our new object should produce the same url identifier
286 elif obj.url_identifier != obj_cmp.url_identifier:
287 raise AssertionError(
288 f"URL: {url} URL Identifier: "
289 f"'{obj_cmp.url_identifier}' != expected"
290 f" '{obj.url_identifier}'"
291 )
292
293 # Back our check up
294 if obj.url_id() != obj_cmp.url_id():
295 raise AssertionError(
296 f"URL: {url} URL ID(): '{obj_cmp.url_id()}' != expected"
297 f" '{obj.url_id()}'"
298 )
299
300 # Verify there is no change from the old and the new
301 if len(obj) != len(obj_cmp):
302 raise AssertionError(
303 f"URL: {url} generated an reloadable "
304 f"url() of {obj.url()} produced target miscount "
305 f"{len(obj)} != {len(obj_cmp)}"
306 )
307
308 # Tidy our object
309 del obj_cmp
310 del instance
311
312 if self_:
313 # Iterate over our expected entries inside of our
314 # object
315 for key, val in self_.items():
316 # Test that our object has the desired key
317 assert hasattr(obj, key) is True
318 assert getattr(obj, key) == val
319
320 try:
321 self.__notify(url, obj, meta, asset)
322
323 except AssertionError:
324 # Don't mess with these entries
325 raise
326
327 # Tidy our object and allow any possible defined destructors to
328 # be executed.
329 del obj
330
331 @mock.patch("requests.get")
332 @mock.patch("requests.post")
333 @mock.patch("requests.head")
334 @mock.patch("requests.put")
335 @mock.patch("requests.delete")
336 @mock.patch("requests.patch")
337 @mock.patch("requests.request")
338 def __notify(
339 self,
340 url,
341 obj,
342 meta,
343 asset,
344 mock_request,
345 mock_patch,
346 mock_del,
347 mock_put,
348 mock_head,
349 mock_post,
350 mock_get,
351 ):
352 """Perform notification testing against object specified."""
353 #
354 # Prepare our options
355 #
356
357 # Allow notification type override, otherwise default to INFO
358 notify_type = meta.get("notify_type", NotifyType.INFO)
359
360 # Whether or not we're testing exceptions or not
361 test_requests_exceptions = meta.get("test_requests_exceptions", False)
362
363 # Our expected Query response (True, False, or exception type)
364 response = meta.get("response", True)
365
366 # Our expected Notify response (True or False)
367 notify_response = meta.get("notify_response", response)
368
369 # Our expected Notify Attachment response (True or False)
370 attach_response = meta.get("attach_response", notify_response)
371
372 # Test attachments
373 # Don't set this if don't need to check it's value
374 check_attachments = meta.get("check_attachments", True)
375
376 # Debug/Trace Monitoring
377 force_debug = meta.get("force_debug", False)
378
379 # Allow us to force the server response code to be something other then
380 # the defaults
381 requests_response_code = meta.get(
382 "requests_response_code",
383 requests.codes.ok if response else requests.codes.not_found,
384 )
385
386 # Allow us to force the server response text to be something other then
387 # the defaults
388 requests_response_text = meta.get("requests_response_text")
389 requests_response_content = None
390
391 if isinstance(requests_response_text, str):
392 requests_response_content = requests_response_text.encode("utf-8")
393
394 elif isinstance(requests_response_text, bytes):
395 requests_response_content = requests_response_text
396 requests_response_text = requests_response_text.decode("utf-8")
397
398 elif not isinstance(requests_response_text, str):
399 # Convert to string
400 requests_response_text = dumps(requests_response_text)
401 requests_response_content = requests_response_text.encode("utf-8")
402
403 else:
404 requests_response_content = ""
405 requests_response_text = ""
406
407 # A request
408 robj = mock.Mock()
409 robj.content = ""
410 robj.text = ""
411 mock_get.return_value = robj
412 mock_post.return_value = robj
413 mock_head.return_value = robj
414 mock_patch.return_value = robj
415 mock_del.return_value = robj
416 mock_put.return_value = robj
417 mock_request.return_value = robj
418
419 if test_requests_exceptions is False:
420 # Handle our default response
421 mock_put.return_value.status_code = requests_response_code
422 mock_head.return_value.status_code = requests_response_code
423 mock_del.return_value.status_code = requests_response_code
424 mock_post.return_value.status_code = requests_response_code
425 mock_get.return_value.status_code = requests_response_code
426 mock_patch.return_value.status_code = requests_response_code
427 mock_request.return_value.status_code = requests_response_code
428
429 # Handle our default text response
430 mock_get.return_value.content = requests_response_content
431 mock_post.return_value.content = requests_response_content
432 mock_del.return_value.content = requests_response_content
433 mock_put.return_value.content = requests_response_content
434 mock_head.return_value.content = requests_response_content
435 mock_patch.return_value.content = requests_response_content
436 mock_request.return_value.content = requests_response_content
437
438 mock_get.return_value.text = requests_response_text
439 mock_post.return_value.text = requests_response_text
440 mock_put.return_value.text = requests_response_text
441 mock_del.return_value.text = requests_response_text
442 mock_head.return_value.text = requests_response_text
443 mock_patch.return_value.text = requests_response_text
444 mock_request.return_value.text = requests_response_text
445
446 # Ensure there is no side effect set
447 mock_post.side_effect = None
448 mock_del.side_effect = None
449 mock_put.side_effect = None
450 mock_head.side_effect = None
451 mock_get.side_effect = None
452 mock_patch.side_effect = None
453 mock_request.side_effect = None
454
455 else:
456 # Handle exception testing; first we turn the boolean flag
457 # into a list of exceptions
458 test_requests_exceptions = self.req_exceptions
459
460 try:
461 if test_requests_exceptions is False:
462 # Verify we can acquire a target count as an integer
463 targets = len(obj)
464
465 # check that we're as expected
466 resp = obj.notify(
467 body=self.body, title=self.title, notify_type=notify_type
468 )
469 if resp != notify_response:
470 raise AssertionError(
471 f"notify() call; notify_response={resp} "
472 f"(expected {notify_response}) on {url}"
473 )
474
475 if notify_response:
476 # If we successfully got a response, there must have been
477 # at least 1 target present
478 assert targets > 0
479
480 # check that this doesn't change using different overflow
481 # methods
482 assert (
483 obj.notify(
484 body=self.body,
485 title=self.title,
486 notify_type=notify_type,
487 overflow=OverflowMode.UPSTREAM,
488 )
489 == notify_response
490 )
491 assert (
492 obj.notify(
493 body=self.body,
494 title=self.title,
495 notify_type=notify_type,
496 overflow=OverflowMode.TRUNCATE,
497 )
498 == notify_response
499 )
500 assert (
501 obj.notify(
502 body=self.body,
503 title=self.title,
504 notify_type=notify_type,
505 overflow=OverflowMode.SPLIT,
506 )
507 == notify_response
508 )
509
510 #
511 # Handle varations of the Asset Object missing fields
512 #
513
514 # First make a backup
515 app_id = asset.app_id
516 app_desc = asset.app_desc
517
518 # now clear records
519 asset.app_id = None
520 asset.app_desc = None
521
522 # Notify should still work
523 assert (
524 obj.notify(
525 body=self.body,
526 title=self.title,
527 notify_type=notify_type,
528 )
529 == notify_response
530 )
531
532 # App ID only
533 asset.app_id = app_id
534 asset.app_desc = None
535
536 # Notify should still work
537 assert (
538 obj.notify(
539 body=self.body,
540 title=self.title,
541 notify_type=notify_type,
542 )
543 == notify_response
544 )
545
546 # App Desc only
547 asset.app_id = None
548 asset.app_desc = app_desc
549
550 if force_debug:
551 # Enable access to areas otherwise locked away by the log
552 # level
553 original_is_enabled_for = obj.logger.isEnabledFor
554 original_debug = obj.logger.debug
555 try:
556 # Force code paths guarded by isEnabledFor(DEBUG)
557 obj.logger.isEnabledFor = mock.Mock(return_value=True)
558
559 # Prevent actual logging emission (avoids pytest
560 # capture closed stream)
561 obj.logger.debug = mock.Mock()
562
563 assert (
564 obj.notify(
565 body=self.body,
566 title=self.title,
567 notify_type=notify_type,
568 )
569 == notify_response
570 )
571
572 finally:
573 # Restore
574 obj.logger.isEnabledFor = original_is_enabled_for
575 obj.logger.debug = original_debug
576 else:
577 assert (
578 obj.notify(
579 body=self.body,
580 title=self.title,
581 notify_type=notify_type,
582 )
583 == notify_response
584 )
585
586 # Restore
587 asset.app_id = app_id
588 asset.app_desc = app_desc
589
590 if check_attachments:
591 # Test single attachment support; even if the service
592 # doesn't support attachments, it should still
593 # gracefully ignore the data
594 attach = os.path.join(
595 self.__test_var_dir, "apprise-test.gif"
596 )
597 assert (
598 obj.notify(
599 body=self.body,
600 title=self.title,
601 notify_type=notify_type,
602 attach=attach,
603 )
604 == attach_response
605 )
606
607 # Same results should apply to a list of attachments
608 attach = AppriseAttachment(
609 (
610 os.path.join(
611 self.__test_var_dir, "apprise-test.gif"
612 ),
613 os.path.join(
614 self.__test_var_dir, "apprise-test.png"
615 ),
616 os.path.join(
617 self.__test_var_dir, "apprise-test.jpeg"
618 ),
619 )
620 )
621
622 assert (
623 obj.notify(
624 body=self.body,
625 title=self.title,
626 notify_type=notify_type,
627 attach=attach,
628 )
629 == attach_response
630 )
631
632 if obj.attachment_support:
633 #
634 # Services that support attachments should support
635 # sending a attachment (or more) without a body or
636 # title specified:
637 #
638 assert (
639 obj.notify(
640 body=None,
641 title=None,
642 notify_type=notify_type,
643 attach=attach,
644 )
645 == attach_response
646 )
647
648 # Turn off attachment support on the notifications
649 # that support it so we can test that any logic we
650 # have ot test against this flag is ran
651 obj.attachment_support = False
652
653 #
654 # Notifications should still transmit as normal if
655 # Attachment support is flipped off
656 #
657 assert (
658 obj.notify(
659 body=self.body,
660 title=self.title,
661 notify_type=notify_type,
662 attach=attach,
663 )
664 == notify_response
665 )
666
667 #
668 # We should not be able to send a message without a
669 # body or title in this circumstance
670 #
671 assert (
672 obj.notify(
673 body=None,
674 title=None,
675 notify_type=notify_type,
676 attach=attach,
677 )
678 is False
679 )
680
681 # Toggle Back
682 obj.attachment_support = True
683
684 else: # No Attachment support
685 #
686 # We should not be able to send a message without a
687 # body or title in this circumstance
688 #
689 assert (
690 obj.notify(
691 body=None,
692 title=None,
693 notify_type=notify_type,
694 attach=attach,
695 )
696 is False
697 )
698 else:
699 for exception in self.req_exceptions:
700 mock_post.side_effect = exception
701 mock_head.side_effect = exception
702 mock_del.side_effect = exception
703 mock_put.side_effect = exception
704 mock_get.side_effect = exception
705 mock_patch.side_effect = exception
706 mock_request.side_effect = exception
707
708 try:
709 assert (
710 obj.notify(
711 body=self.body,
712 title=self.title,
713 notify_type=notify_type,
714 )
715 is False
716 )
717
718 except AssertionError:
719 # Don't mess with these entries
720 raise
721
722 except Exception:
723 # We can't handle this exception type
724 raise
725
726 except AssertionError:
727 # Don't mess with these entries
728 raise
729
730 except Exception as e:
731 # Check that we were expecting this exception to happen
732 try:
733 if not isinstance(e, response):
734 raise e
735
736 except TypeError:
737 raise e # noqa: B904 - intentional re-raising in test helper
738
739 #
740 # Do the test again but without a title defined
741 #
742 try:
743 if test_requests_exceptions is False:
744 # check that we're as expected
745 assert (
746 obj.notify(body="body", notify_type=notify_type)
747 == notify_response
748 )
749
750 else:
751 for exception in self.req_exceptions:
752 mock_post.side_effect = exception
753 mock_del.side_effect = exception
754 mock_put.side_effect = exception
755 mock_head.side_effect = exception
756 mock_get.side_effect = exception
757 mock_patch.side_effect = exception
758 mock_request.side_effect = exception
759
760 try:
761 assert (
762 obj.notify(body=self.body, notify_type=notify_type)
763 is False
764 )
765
766 except AssertionError:
767 # Don't mess with these entries
768 raise
769
770 except Exception:
771 # We can't handle this exception type
772 raise
773
774 except AssertionError:
775 # Don't mess with these entries
776 raise
777
778 except Exception as e:
779 # Check that we were expecting this exception to happen
780 if not isinstance(e, response):
781 raise e
782
783 return True