Debian Codegraph @

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