Debian Codegraph @

tests/test_plugin_mastodon.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, timezone
29 from json import dumps, loads
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import os
34 from unittest import mock
35
36 from helpers import AppriseURLTester
37 import requests
38
39 from apprise import Apprise, AppriseAttachment, NotifyFormat, NotifyType
40 from apprise.plugins.mastodon import NotifyMastodon
41
42 logging.disable(logging.CRITICAL)
43
44 # Attachment Directory
45 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
46
47 # Our Testing URLs
48 apprise_url_tests = (
49 ##################################
50 # NotifyMastodon
51 ##################################
52 (
53 "mastodon://",
54 {
55 # Missing Everything :)
56 "instance": None,
57 },
58 ),
59 (
60 "mastodon://:@/",
61 {
62 "instance": None,
63 },
64 ),
65 (
66 "mastodon://hostname",
67 {
68 # Missing Access Token
69 "instance": TypeError,
70 },
71 ),
72 (
73 "toot://access_token@hostname",
74 {
75 # We're good; it's a simple notification
76 "instance": NotifyMastodon,
77 },
78 ),
79 (
80 "toots://access_token@hostname",
81 {
82 # We're good; it's another simple notification
83 "instance": NotifyMastodon,
84 # Our expected url(privacy=True) startswith() response:
85 "privacy_url": "mastodons://****@hostname/",
86 },
87 ),
88 (
89 "mastodon://access_token@hostname/@user/@user2",
90 {
91 # We're good; it's another simple notification
92 "instance": NotifyMastodon,
93 # Our expected url(privacy=True) startswith() response:
94 "privacy_url": "mastodon://****@hostname/@user/@user2",
95 },
96 ),
97 (
98 "mastodon://hostname/@user/@user2?token=abcd123",
99 {
100 # Our access token can be provided as a token= variable
101 "instance": NotifyMastodon,
102 # Our expected url(privacy=True) startswith() response:
103 "privacy_url": "mastodon://****@hostname/@user/@user2",
104 },
105 ),
106 (
107 "mastodon://access_token@hostname?to=@user, @user2",
108 {
109 # We're good; it's another simple notification
110 "instance": NotifyMastodon,
111 # Our expected url(privacy=True) startswith() response:
112 "privacy_url": "mastodon://****@hostname/@user/@user2",
113 },
114 ),
115 (
116 "mastodon://access_token@hostname/?cache=no",
117 {
118 # disable cache as a test
119 "instance": NotifyMastodon,
120 },
121 ),
122 (
123 "mastodon://access_token@hostname/?spoiler=spoiler%20text",
124 {
125 # a public post
126 "instance": NotifyMastodon,
127 },
128 ),
129 (
130 "mastodon://access_token@hostname/?language=en",
131 {
132 # over-ride our language
133 "instance": NotifyMastodon,
134 },
135 ),
136 (
137 "mastodons://access_token@hostname:8443",
138 {
139 # A custom port specified
140 "instance": NotifyMastodon,
141 },
142 ),
143 (
144 "mastodon://access_token@hostname/?key=My%20Idempotency%20Key",
145 {
146 # Prevent duplicate submissions of the same status. Idempotency
147 # keys are stored for up to 1 hour, and can be any arbitrary
148 # string. Consider using a hash or UUID generated client-side.
149 "instance": NotifyMastodon,
150 },
151 ),
152 (
153 "mastodon://access_token@hostname/-/%/",
154 {
155 # Invalid users specified
156 "instance": TypeError,
157 },
158 ),
159 (
160 "mastodon://access_token@hostname?visibility=invalid",
161 {
162 # An invalid visibility
163 "instance": TypeError,
164 },
165 ),
166 (
167 "mastodon://access_token@hostname?visibility=direct",
168 {
169 # A direct message
170 "instance": NotifyMastodon,
171 # Expected notify() response False (because we won't
172 # get the response we were expecting from the upstream
173 # server
174 "notify_response": False,
175 },
176 ),
177 (
178 "mastodon://access_token@hostname?visibility=direct",
179 {
180 # A direct message
181 "instance": NotifyMastodon,
182 # Provide a response that allows us to look our content up
183 "requests_response_text": {
184 "id": "12345",
185 "username": "test",
186 },
187 },
188 ),
189 (
190 "toots://access_token@hostname",
191 {
192 "instance": NotifyMastodon,
193 # Throws a series of i/o exceptions with this flag
194 # is set and tests that we gracefully handle them
195 "test_requests_exceptions": True,
196 },
197 ),
198 )
199
200
201 def test_plugin_mastodon_urls():
202 """NotifyMastodon() Apprise URLs."""
203
204 # Run our general tests
205 AppriseURLTester(tests=apprise_url_tests).run_all()
206
207
208 @mock.patch("requests.get")
209 @mock.patch("requests.post")
210 def test_plugin_mastodon_general(mock_post, mock_get):
211 """NotifyMastodon() General Tests."""
212 token = "access_key"
213 host = "nuxref.com"
214
215 response_obj = {
216 "username": "caronc",
217 "id": 1234,
218 }
219
220 # Epoch time:
221 epoch = datetime.fromtimestamp(0, timezone.utc)
222
223 request = mock.Mock()
224 request.content = dumps(response_obj)
225 request.status_code = requests.codes.ok
226 request.headers = {
227 "X-RateLimit-Limit": (
228 (datetime.now(timezone.utc) - epoch).total_seconds()
229 ),
230 "X-RateLimit-Remaining": 1,
231 }
232
233 # Prepare Mock
234 mock_get.return_value = request
235 mock_post.return_value = request
236
237 # Instantiate our object
238 obj = NotifyMastodon(token=token, host=host)
239
240 assert isinstance(obj, NotifyMastodon)
241 assert isinstance(obj.url(), str)
242
243 # apprise room was found
244 assert obj.send(body="test") is True
245
246 # Change our status code and try again
247 request.status_code = 403
248 assert obj.send(body="test") is False
249 assert obj.ratelimit_remaining == 1
250
251 # Return the status
252 request.status_code = requests.codes.ok
253 # Force a reset
254 request.headers["X-RateLimit-Remaining"] = 0
255 # behind the scenes, it should cause us to update our rate limit
256 assert obj.send(body="test") is True
257 assert obj.ratelimit_remaining == 0
258
259 # This should cause us to block
260 request.headers["X-RateLimit-Remaining"] = 10
261 assert obj.send(body="test") is True
262 assert obj.ratelimit_remaining == 10
263
264 # Handle cases where we simply couldn't get this field
265 del request.headers["X-RateLimit-Remaining"]
266 assert obj.send(body="test") is True
267 # It remains set to the last value
268 assert obj.ratelimit_remaining == 10
269
270 # Reset our variable back to 1
271 request.headers["X-RateLimit-Remaining"] = 1
272
273 # Handle cases where our epoch time is wrong
274 del request.headers["X-RateLimit-Limit"]
275 assert obj.send(body="test") is True
276
277 # Return our object, but place it in the future forcing us to block
278 request.headers["X-RateLimit-Limit"] = (
279 datetime.now(timezone.utc) - epoch
280 ).total_seconds() + 1
281 request.headers["X-RateLimit-Remaining"] = 0
282 obj.ratelimit_remaining = 0
283 assert obj.send(body="test") is True
284
285 # Return our object, but place it in the future forcing us to block
286 request.headers["X-RateLimit-Limit"] = (
287 datetime.now(timezone.utc) - epoch
288 ).total_seconds() - 1
289 request.headers["X-RateLimit-Remaining"] = 0
290 obj.ratelimit_remaining = 0
291 assert obj.send(body="test") is True
292
293 # Return our limits to always work
294 request.headers["X-RateLimit-Limit"] = (
295 datetime.now(timezone.utc) - epoch
296 ).total_seconds()
297 request.headers["X-RateLimit-Remaining"] = 1
298 obj.ratelimit_remaining = 1
299
300 # Alter pending targets
301 obj.targets.append("usera")
302 request.content = dumps(response_obj)
303 response_obj = {
304 "username": "usera",
305 "id": 4321,
306 }
307
308 # Cause content response to be None
309 request.content = None
310 assert obj.send(body="test") is True
311
312 # Invalid JSON
313 request.content = "{"
314 assert obj.send(body="test") is True
315
316 # Return it to a parseable string
317 request.content = "{}"
318
319 results = NotifyMastodon.parse_url(
320 f"mastodon://{token}@{host}/@user?visbility=direct"
321 )
322 assert isinstance(results, dict)
323 assert "@user" in results["targets"]
324
325 # cause a json parsing issue now
326 response_obj = None
327 assert obj.send(body="test") is True
328
329 response_obj = "{"
330 assert obj.send(body="test") is True
331
332 mock_get.reset_mock()
333 mock_post.reset_mock()
334
335 #
336 # Test our lazy lookups
337 #
338
339 # Prepare a good status response
340 request = mock.Mock()
341 request.content = dumps({"id": "1234", "username": "caronc"})
342 request.status_code = requests.codes.ok
343 mock_get.return_value = request
344
345 mastodon_url = "mastodons://key@host?visibility=direct"
346 obj = Apprise.instantiate(mastodon_url)
347 obj._whoami(lazy=True)
348 assert mock_get.call_count == 1
349 assert (
350 mock_get.call_args_list[0][0][0]
351 == "https://host/api/v1/accounts/verify_credentials"
352 )
353
354 mock_get.reset_mock()
355 obj._whoami(lazy=True)
356 assert mock_get.call_count == 0
357
358 mock_get.reset_mock()
359 obj._whoami(lazy=False)
360 assert mock_get.call_count == 1
361 assert (
362 mock_get.call_args_list[0][0][0]
363 == "https://host/api/v1/accounts/verify_credentials"
364 )
365
366
367 @mock.patch("requests.post")
368 def test_plugin_mastodon_pings(mock_post):
369 """NotifyMastodon() Ping Checks."""
370 token = "access_key"
371 host = "nuxref.com"
372
373 request = mock.Mock()
374 request.content = dumps({})
375 request.status_code = requests.codes.ok
376 request.headers = {}
377
378 mock_post.return_value = request
379
380 body = (
381 "Body **#déjà_vu** and @abc, plus #再会. "
382 "Ignore ##bad, #bad%, #123, email@miss, and duplicate "
383 "@abc #déjà_vu."
384 )
385
386 obj = NotifyMastodon(
387 token=token,
388 host=host,
389 format=NotifyFormat.MARKDOWN,
390 ping="@abc,#déjà_vu,#radarr,radarr,#123,bad%",
391 )
392
393 assert obj.send(body=body) is True
394 assert mock_post.call_count == 1
395
396 payload = loads(mock_post.call_args_list[0][1]["data"])
397
398 # Mentions and hashtags are appended in a plain form Mastodon can resolve.
399 assert payload["status"] == f"{body} @abc #déjà_vu #再会 #radarr"
400
401 mock_post.reset_mock()
402
403 body = "Body with #solo only."
404
405 obj = NotifyMastodon(
406 token=token,
407 host=host,
408 format=NotifyFormat.MARKDOWN,
409 )
410
411 assert obj.send(body=body) is True
412 assert mock_post.call_count == 1
413
414 payload = loads(mock_post.call_args_list[0][1]["data"])
415
416 # Markdown statuses can contribute visible mention and hashtag tokens.
417 assert payload["status"] == f"{body} #solo"
418
419 mock_post.reset_mock()
420
421 body = "<p>No tags in this formatted body.</p>"
422
423 obj = NotifyMastodon(
424 token=token,
425 host=host,
426 format=NotifyFormat.HTML,
427 )
428
429 assert obj.send(body=body) is True
430 assert mock_post.call_count == 1
431
432 payload = loads(mock_post.call_args_list[0][1]["data"])
433
434 # When no valid tag tokens are found, the status is not decorated.
435 assert payload["status"] == body
436
437 mock_post.reset_mock()
438
439 obj = NotifyMastodon(
440 token=token,
441 host=host,
442 ping="@caronc,#apprise,#alerts",
443 )
444
445 assert isinstance(obj.url(), str)
446 assert "ping=" in obj.url()
447
448 results = NotifyMastodon.parse_url(obj.url())
449 assert results["ping"] == "#alerts,#apprise,@caronc"
450
451 assert NotifyMastodon.normalize_ping_token(" ") is None
452 assert NotifyMastodon.normalize_ping_token("alerts") is None
453 assert NotifyMastodon.valid_hashtag("#bad%") is False
454 assert obj.ping_tokens("bad%", normalize=True) == []
455
456 obj = NotifyMastodon(
457 token=token,
458 host=host,
459 targets="#Apprise,#apprise",
460 ping="#Media,#media",
461 )
462 assert obj.hashtags == ["#Apprise"]
463 assert obj.ping == ["#Media"]
464
465 mock_post.reset_mock()
466
467 results = NotifyMastodon.parse_url(
468 f"mastodon://{token}@{host}/#apprise?ping=#apprise,#media"
469 )
470 obj = NotifyMastodon(**results)
471
472 assert obj.send(body="Body") is True
473 assert mock_post.call_count == 1
474
475 payload = loads(mock_post.call_args_list[0][1]["data"])
476
477 # Hashtag path entries and configured pings share de-duplication.
478 assert payload["status"] == "Body #apprise #media"
479
480 rebuilt_url = obj.url()
481 assert "/%23apprise" in rebuilt_url
482 assert "ping=%23apprise%2C%23media" in rebuilt_url
483
484 results = NotifyMastodon.parse_url(rebuilt_url)
485 assert results["targets"] == ["#apprise"]
486 assert results["ping"] == "#apprise,#media"
487
488 mock_post.reset_mock()
489
490 obj = NotifyMastodon(token=token, host=host, ping="#apprise")
491
492 assert obj.send(body="a" * obj.body_maxlen) is True
493 assert mock_post.call_count == 1
494
495 payload = loads(mock_post.call_args_list[0][1]["data"])
496
497 # The effective body limit reserves room for configured status tokens.
498 assert obj.body_maxlen == obj.mastodon_body_maxlen - len(" #apprise")
499 assert len(payload["status"]) == obj.mastodon_body_maxlen
500 assert payload["status"].endswith(" #apprise")
501
502
503 @mock.patch("requests.post")
504 def test_plugin_mastodon_text(mock_post):
505 """NotifyMastodon() Text Checks."""
506 token = "access_key"
507 host = "nuxref.com"
508
509 request = mock.Mock()
510 request.content = dumps({})
511 request.status_code = requests.codes.ok
512 request.headers = {}
513
514 mock_post.return_value = request
515
516 body = "Plain text keeps #déjà_vu and @abc exactly where they are."
517
518 obj = NotifyMastodon(
519 token=token,
520 host=host,
521 format=NotifyFormat.TEXT,
522 )
523
524 assert obj.send(body=body) is True
525 assert mock_post.call_count == 1
526
527 payload = loads(mock_post.call_args_list[0][1]["data"])
528
529 # Plain text is already suitable for Mastodon and is left untouched.
530 assert payload["status"] == body
531
532 mock_post.reset_mock()
533
534 obj = NotifyMastodon(
535 token=token,
536 host=host,
537 format=NotifyFormat.TEXT,
538 targets="@media,#homeassistant",
539 ping="radarr,@media,#homeassistant,#alerts,#123,bad%",
540 )
541
542 assert obj.send(body=body) is True
543 assert mock_post.call_count == 1
544
545 payload = loads(mock_post.call_args_list[0][1]["data"])
546
547 # Explicit path entries and ping values are appended without scanning for
548 # new plain text body tokens.
549 assert payload["status"] == f"{body} #alerts #homeassistant @media"
550
551
552 @mock.patch("requests.get")
553 @mock.patch("requests.post")
554 def test_plugin_mastodon_direct(mock_post, mock_get):
555 """NotifyMastodon() Direct Checks."""
556 token = "access_key"
557 host = "nuxref.com"
558
559 request = mock.Mock()
560 request.content = dumps({})
561 request.status_code = requests.codes.ok
562 request.headers = {}
563
564 mock_post.return_value = request
565
566 body = "Direct body already contains @target."
567
568 obj = NotifyMastodon(
569 token=token,
570 host=host,
571 targets="@target",
572 visibility="direct",
573 )
574
575 assert obj.send(body=body) is True
576 assert mock_post.call_count == 1
577 assert mock_get.call_count == 0
578
579 payload = loads(mock_post.call_args_list[0][1]["data"])
580
581 # Explicit direct targets do not require a lookup for the authenticated
582 # account, and duplicate body mentions are not prepended.
583 assert payload["status"] == body
584
585 mock_post.reset_mock()
586
587 body = "Direct body contains email@target only."
588
589 obj = NotifyMastodon(
590 token=token,
591 host=host,
592 targets="@target",
593 visibility="direct",
594 )
595
596 assert obj.send(body=body) is True
597 assert mock_post.call_count == 1
598 assert mock_get.call_count == 0
599
600 payload = loads(mock_post.call_args_list[0][1]["data"])
601
602 # Email-like text is not treated as a delivered direct-message mention.
603 assert payload["status"] == f"@target {body}"
604
605
606 @mock.patch("requests.post")
607 @mock.patch("requests.get")
608 def test_plugin_mastodon_attachments(mock_get, mock_post):
609 """NotifyMastodon() Toot Attachment Checks."""
610 akey = "access_key"
611 host = "nuxref.com"
612 username = "caronc"
613
614 # Prepare a good status response
615 good_response_obj = {
616 "id": "1234",
617 }
618
619 good_response = mock.Mock()
620 good_response.content = dumps(good_response_obj)
621 good_response.status_code = requests.codes.ok
622
623 # Prepare a good whoami response
624 good_whoami_response_obj = {
625 "username": username,
626 "id": "9876",
627 }
628
629 good_whoami_response = mock.Mock()
630 good_whoami_response.content = dumps(good_whoami_response_obj)
631 good_whoami_response.status_code = requests.codes.ok
632
633 # Prepare bad response
634 bad_response = mock.Mock()
635 bad_response.content = dumps({})
636 bad_response.status_code = requests.codes.internal_server_error
637
638 # Prepare a good media response
639 good_media_response = mock.Mock()
640 good_media_response.content = dumps(
641 {
642 "id": "710511363345354753",
643 "file_mime": "image/jpeg",
644 }
645 )
646 good_media_response.status_code = requests.codes.ok
647
648 #
649 # Start testing using fixtures above
650 #
651 mock_post.side_effect = [good_media_response, good_response]
652 mock_get.return_value = good_whoami_response
653
654 mastodon_url = f"mastodon://{akey}@{host}"
655
656 # attach our content
657 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
658
659 # instantiate our object
660 obj = Apprise.instantiate(mastodon_url)
661
662 # Send our notification
663 assert (
664 obj.notify(
665 body="body",
666 title="title",
667 notify_type=NotifyType.INFO,
668 attach=attach,
669 )
670 is True
671 )
672
673 # Test our call count
674 assert mock_get.call_count == 0
675 assert mock_post.call_count == 2
676 assert (
677 mock_post.call_args_list[0][0][0] == "http://nuxref.com/api/v1/media"
678 )
679 assert (
680 mock_post.call_args_list[1][0][0]
681 == "http://nuxref.com/api/v1/statuses"
682 )
683
684 # Test our media payload
685 assert "files" in mock_post.call_args_list[0][1]
686 assert "file" in mock_post.call_args_list[0][1]["files"]
687 assert (
688 mock_post.call_args_list[0][1]["files"]["file"][0]
689 == "apprise-test.gif"
690 )
691
692 # Test our status payload
693 payload = loads(mock_post.call_args_list[1][1]["data"])
694 assert "status" in payload
695 assert payload["status"] == "title\r\nbody"
696 assert "sensitive" in payload
697 assert payload["sensitive"] is False
698 assert "media_ids" in payload
699 assert isinstance(payload["media_ids"], list)
700 assert len(payload["media_ids"]) == 1
701 assert payload["media_ids"][0] == "710511363345354753"
702
703 # Verify we don't set incorrect keys not otherwise specified
704 assert "spoiler_text" not in payload
705
706 mock_get.reset_mock()
707 mock_post.reset_mock()
708
709 #
710 # Handle the query again, but this time perform a direct message
711 # requiring us to look up who we are
712 #
713 mock_post.side_effect = [good_media_response, good_response]
714 mock_get.return_value = good_whoami_response
715
716 mastodon_url = f"mastodon://{akey}@{host}?visibility=direct"
717
718 # attach our content
719 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
720
721 # instantiate our object
722 obj = Apprise.instantiate(mastodon_url)
723
724 # Send our notification
725 assert (
726 obj.notify(
727 body="body",
728 title="title",
729 notify_type=NotifyType.INFO,
730 attach=attach,
731 )
732 is True
733 )
734
735 # Test our call count
736 assert mock_get.call_count == 1
737 assert mock_post.call_count == 2
738 assert (
739 mock_get.call_args_list[0][0][0]
740 == "http://nuxref.com/api/v1/accounts/verify_credentials"
741 )
742 assert (
743 mock_post.call_args_list[0][0][0] == "http://nuxref.com/api/v1/media"
744 )
745 assert (
746 mock_post.call_args_list[1][0][0]
747 == "http://nuxref.com/api/v1/statuses"
748 )
749
750 # Test our status payload
751 payload = loads(mock_post.call_args_list[1][1]["data"])
752 assert "status" in payload
753 # Our ID was added into the payload
754 assert payload["status"] == "@caronc title\r\nbody"
755 assert "sensitive" in payload
756 assert payload["sensitive"] is False
757 assert "media_ids" in payload
758 assert isinstance(payload["media_ids"], list)
759 assert len(payload["media_ids"]) == 1
760 assert payload["media_ids"][0] == "710511363345354753"
761
762 mock_get.reset_mock()
763 mock_post.reset_mock()
764
765 # Store 3 attachments
766 attach = (
767 AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif")),
768 AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png")),
769 AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.jpeg")),
770 )
771
772 # Prepare a good media response
773 mr1 = mock.Mock()
774 mr1.content = dumps(
775 {
776 "id": "1",
777 "file_mime": "image/gif",
778 }
779 )
780 mr1.status_code = requests.codes.ok
781
782 mr2 = mock.Mock()
783 mr2.content = dumps(
784 {
785 "id": "2",
786 "file_mime": "image/png",
787 }
788 )
789 mr2.status_code = requests.codes.ok
790
791 mr3 = mock.Mock()
792 mr3.content = dumps(
793 {
794 "id": "3",
795 "file_mime": "image/jpeg",
796 }
797 )
798 mr3.status_code = requests.codes.ok
799
800 # Return 3 good uploads and a good status response
801 mock_post.side_effect = [mr1, mr2, mr3, good_response, good_response]
802 mock_get.return_value = good_whoami_response
803
804 # instantiate our object
805 mastodon_url = (
806 f"mastodons://{akey}@{host}?visibility=direct&sensitive=yes&key=abcd"
807 )
808 obj = Apprise.instantiate(mastodon_url)
809
810 # Send ourselves a direct message where our ID was already found
811 # in the body. This smart detection method will prevent us from
812 # adding the @caronc to the begining of the same message (since it's a
813 # direct message)
814 assert (
815 obj.notify(
816 body="Check this out @caronc",
817 title="Apprise",
818 notify_type=NotifyType.INFO,
819 attach=attach,
820 )
821 is True
822 )
823
824 # Test our call count
825 assert mock_get.call_count == 1
826 assert mock_post.call_count == 5
827 assert (
828 mock_post.call_args_list[0][0][0] == "https://nuxref.com/api/v1/media"
829 )
830 assert (
831 mock_post.call_args_list[1][0][0] == "https://nuxref.com/api/v1/media"
832 )
833 assert (
834 mock_post.call_args_list[2][0][0] == "https://nuxref.com/api/v1/media"
835 )
836 # Our status's will batch up and send the last 2 images in one
837 # and our animated gif in one.
838 assert (
839 mock_post.call_args_list[3][0][0]
840 == "https://nuxref.com/api/v1/statuses"
841 )
842 assert (
843 mock_post.call_args_list[4][0][0]
844 == "https://nuxref.com/api/v1/statuses"
845 )
846 assert (
847 mock_get.call_args_list[0][0][0]
848 == "https://nuxref.com/api/v1/accounts/verify_credentials"
849 )
850
851 # Test our status payload
852 payload = loads(mock_post.call_args_list[3][1]["data"])
853 assert "status" in payload
854 assert payload["status"] == "Apprise\r\nCheck this out @caronc"
855 assert "sensitive" in payload
856 assert payload["sensitive"] is True
857 assert "language" not in payload
858 assert "Idempotency-Key" in payload
859 assert payload["Idempotency-Key"] == "abcd"
860 assert "media_ids" in payload
861 assert isinstance(payload["media_ids"], list)
862 assert len(payload["media_ids"]) == 1
863 assert payload["media_ids"][0] == "1"
864
865 payload = loads(mock_post.call_args_list[4][1]["data"])
866 assert "status" in payload
867 assert payload["status"] == "02/02"
868 assert "sensitive" in payload
869 assert payload["sensitive"] is False
870 assert "language" not in payload
871 assert "Idempotency-Key" in payload
872 assert payload["Idempotency-Key"] == "abcd-part01"
873 assert "media_ids" in payload
874 assert isinstance(payload["media_ids"], list)
875 assert len(payload["media_ids"]) == 2
876 assert "2" in payload["media_ids"]
877 assert "3" in payload["media_ids"]
878
879 # A second call does not cause us to look up our ID as we already know it
880 mock_get.reset_mock()
881 mock_post.reset_mock()
882 mock_post.side_effect = [mr1, mr2, mr3, good_response, good_response]
883 mock_get.return_value = good_whoami_response
884 assert (
885 obj.notify(
886 body="Check this out @caronc",
887 title="Apprise",
888 notify_type=NotifyType.INFO,
889 attach=attach,
890 )
891 is True
892 )
893
894 # Same number of posts
895 assert mock_post.call_count == 5
896 # But no lookup was made
897 assert mock_get.call_count == 0
898
899 mock_get.reset_mock()
900 mock_post.reset_mock()
901
902 # Prepare an attach list
903 attach = (
904 os.path.join(TEST_VAR_DIR, "apprise-test.png"),
905 os.path.join(TEST_VAR_DIR, "apprise-test.jpeg"),
906 )
907
908 mock_post.side_effect = [mr2, mr3, good_response, good_response]
909 mock_get.return_value = good_whoami_response
910
911 # instantiate our object (but turn off the batch mode)
912 mastodon_url = f"mastodons://{akey}@{host}?batch=no"
913 obj = Apprise.instantiate(mastodon_url)
914
915 assert (
916 obj.notify(
917 body="Check this out @caronc",
918 title="Apprise",
919 notify_type=NotifyType.INFO,
920 attach=attach,
921 )
922 is True
923 )
924
925 # 2 attachments + 2 different status messages
926 assert mock_post.call_count == 4
927
928 # But no lookup was made
929 assert mock_get.call_count == 0
930
931 assert (
932 mock_post.call_args_list[0][0][0] == "https://nuxref.com/api/v1/media"
933 )
934 assert (
935 mock_post.call_args_list[1][0][0] == "https://nuxref.com/api/v1/media"
936 )
937 assert (
938 mock_post.call_args_list[2][0][0]
939 == "https://nuxref.com/api/v1/statuses"
940 )
941 assert (
942 mock_post.call_args_list[3][0][0]
943 == "https://nuxref.com/api/v1/statuses"
944 )
945
946 mock_get.reset_mock()
947 mock_post.reset_mock()
948
949 # Prepare a bad media response
950 bad_response = mock.Mock()
951 bad_response.status_code = requests.codes.internal_server_error
952
953 bad_responses = (
954 dumps({"error": "authorized scopes"}),
955 "",
956 )
957
958 #
959 # Test our Media failures
960 #
961
962 # Try several bad responses so we can capture the block of code where
963 # we try to help the end user to remind them what scope they're missing
964 for response in bad_responses:
965 mock_post.side_effect = [good_media_response, bad_response]
966 bad_response.content = response
967
968 # instantiate our object
969 mastodon_url = (
970 f"mastodons://{akey}@{host}?visibility=public&spoiler=uhoh"
971 )
972 obj = Apprise.instantiate(mastodon_url)
973
974 # Our notification will fail now since our toot will error out
975 # This is the same test as above, except our error response isn't
976 # parseable
977 assert (
978 obj.notify(
979 body="body",
980 title="title",
981 notify_type=NotifyType.INFO,
982 attach=attach,
983 )
984 is False
985 )
986
987 # Test our call count
988 assert mock_get.call_count == 0
989 assert mock_post.call_count == 2
990 assert (
991 mock_post.call_args_list[0][0][0]
992 == "https://nuxref.com/api/v1/media"
993 )
994 assert (
995 mock_post.call_args_list[1][0][0]
996 == "https://nuxref.com/api/v1/media"
997 )
998
999 mock_get.reset_mock()
1000 mock_post.reset_mock()
1001
1002 #
1003 # Test our Status failures
1004 #
1005
1006 # Try several bad responses so we can capture the block of code where
1007 # we try to help the end user to remind them what scope they're missing
1008 for response in bad_responses:
1009 mock_post.side_effect = [bad_response]
1010 bad_response.content = response
1011
1012 # instantiate our object
1013 mastodon_url = f"mastodons://{akey}@{host}"
1014 obj = Apprise.instantiate(mastodon_url)
1015
1016 # Our notification will fail now since our toot will error out
1017 # This is the same test as above, except our error response isn't
1018 # parseable
1019 assert (
1020 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1021 is False
1022 )
1023
1024 # Test our call count
1025 assert mock_get.call_count == 0
1026 assert mock_post.call_count == 1
1027 assert (
1028 mock_post.call_args_list[0][0][0]
1029 == "https://nuxref.com/api/v1/statuses"
1030 )
1031
1032 mock_get.reset_mock()
1033 mock_post.reset_mock()
1034
1035 #
1036 # Test our whoami failures
1037 #
1038
1039 # Try several bad responses so we can capture the block of code where
1040 # we try to help the end user to remind them what scope they're missing
1041 for response in bad_responses:
1042 mock_get.side_effect = [bad_response]
1043 bad_response.content = response
1044
1045 # instantiate our object
1046 mastodon_url = f"mastodons://{akey}@{host}?visibility=direct"
1047 obj = Apprise.instantiate(mastodon_url)
1048
1049 # Our notification will fail now since our toot will error out
1050 # This is the same test as above, except our error response isn't
1051 # parseable
1052 assert (
1053 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1054 is False
1055 )
1056
1057 # Test our call count
1058 assert mock_get.call_count == 1
1059 assert mock_post.call_count == 0
1060 assert (
1061 mock_get.call_args_list[0][0][0]
1062 == "https://nuxref.com/api/v1/accounts/verify_credentials"
1063 )
1064
1065 mock_get.reset_mock()
1066 mock_post.reset_mock()
1067
1068 mock_post.side_effect = [mr1, mr2, mr3, good_response, good_response]
1069 mock_get.return_value = None
1070
1071 # instantiate our object
1072 mastodon_url = f"mastodons://{akey}@{host}"
1073 obj = Apprise.instantiate(mastodon_url)
1074
1075 # An invalid attachment will cause a failure
1076 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
1077 assert (
1078 obj.notify(
1079 body="body",
1080 title="title",
1081 notify_type=NotifyType.INFO,
1082 attach=path,
1083 )
1084 is False
1085 )
1086
1087 # No get requests are made
1088 assert mock_get.call_count == 0
1089
1090 # No post request as attachment is no good anyway
1091 assert mock_post.call_count == 0
1092
1093 mock_get.reset_mock()
1094 mock_post.reset_mock()
1095
1096 # We have an OSError thrown in the middle of our preparation
1097 mock_post.side_effect = [
1098 good_media_response,
1099 OSError(),
1100 good_media_response,
1101 ]
1102 mock_get.return_value = good_response
1103
1104 # 3 images are produced
1105 attach = [
1106 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
1107 # This one is not supported, so it's ignored gracefully
1108 os.path.join(TEST_VAR_DIR, "apprise-archive.zip"),
1109 # A supported video file
1110 os.path.join(TEST_VAR_DIR, "apprise-test.mp4"),
1111 ]
1112
1113 # We'll fail to send this time
1114 assert (
1115 obj.notify(
1116 body="body",
1117 title="title",
1118 notify_type=NotifyType.INFO,
1119 attach=attach,
1120 )
1121 is False
1122 )
1123
1124 assert mock_get.call_count == 0
1125 # No get request as cached response is used
1126 assert mock_post.call_count == 2
1127 assert (
1128 mock_post.call_args_list[0][0][0] == "https://nuxref.com/api/v1/media"
1129 )
1130 assert (
1131 mock_post.call_args_list[1][0][0] == "https://nuxref.com/api/v1/media"
1132 )
1133
1134
1135 @mock.patch("requests.post")
1136 def test_plugin_mastodon_apprise_tags(mock_post):
1137 """NotifyMastodon() - Apprise tag filter must not corrupt URLBase.tags.
1138
1139 Regression test for a bug where self.hashtags = [] in __init__ was
1140 mistakenly named self.tags, overwriting the set() that URLBase stores for
1141 Apprise's own notification-tag system. Any call to Apprise.find() or a
1142 tag-filtered Apprise.notify() would crash with:
1143 AttributeError: 'list' object has no attribute 'union'
1144 """
1145 akey = "access_key"
1146 host = "mastodon.social"
1147
1148 # Prepare a good response
1149 good_response = mock.Mock()
1150 good_response.content = b"{}"
1151 good_response.status_code = requests.codes.ok
1152
1153 mock_post.return_value = good_response
1154
1155 # Load a Mastodon URL that carries Mastodon hashtag targets into an Apprise
1156 # instance that also has Apprise notification tags assigned. The Mastodon
1157 # #hashtag and the Apprise tag are distinct concepts and must not collide.
1158 a = Apprise()
1159 assert (
1160 a.add(
1161 f"mastodon://{akey}@{host}/%23apprise",
1162 tag="prod",
1163 )
1164 is True
1165 )
1166
1167 # Confirm the plugin loaded and its Apprise tag set is a proper set (not a
1168 # list), which is what caused the AttributeError before the fix.
1169 plugins = list(a)
1170 assert len(plugins) == 1
1171 assert isinstance(plugins[0].tags, set)
1172 assert "prod" in plugins[0].tags
1173
1174 # Confirm the Mastodon hashtag target was stored under hashtags, not tags
1175 assert plugins[0].hashtags == ["#apprise"]
1176
1177 # Exercising Apprise.find() is the exact path that crashed before the fix;
1178 # it calls is_exclusive_match(data=notification.tags, ...) which requires
1179 # notification.tags to support .union().
1180 found = list(a.find("prod"))
1181 assert len(found) == 1
1182
1183 # A tag-filtered notify() follows the same code path
1184 assert a.notify(body="test", tag="prod") is True
1185 assert mock_post.call_count == 1