Debian Codegraph @

tests/test_plugin_twitter.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 datetime import datetime, timezone
29 import json
30 import logging
31 import os
32 from unittest.mock import Mock, patch
33
34 from helpers import AppriseURLTester
35 import pytest
36 import requests
37
38 from apprise import Apprise, AppriseAttachment, NotifyType
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.base import _delivery_tracker
41 from apprise.plugins.twitter import NotifyTwitter
42
43 # Disable logging for a cleaner testing output
44 logging.disable(logging.CRITICAL)
45
46 # Attachment Directory
47 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
48
49 TWITTER_SCREEN_NAME = "apprise"
50
51
52 # Our Testing URLs
53 apprise_url_tests = (
54 ##################################
55 # NotifyTwitter
56 ##################################
57 (
58 "twitter://",
59 {
60 # Missing Consumer API Key
61 "instance": AppriseImproperlyConfigured,
62 },
63 ),
64 (
65 "twitter://:@/",
66 {
67 "instance": AppriseImproperlyConfigured,
68 },
69 ),
70 (
71 "twitter://consumer_key",
72 {
73 # Missing Keys
74 "instance": AppriseImproperlyConfigured,
75 },
76 ),
77 (
78 "twitter://consumer_key/consumer_secret/",
79 {
80 # Missing Keys
81 "instance": AppriseImproperlyConfigured,
82 },
83 ),
84 (
85 "twitter://consumer_key/consumer_secret/atoken1/",
86 {
87 # Missing Access Secret
88 "instance": AppriseImproperlyConfigured,
89 },
90 ),
91 (
92 "twitter://consumer_key/consumer_secret/atoken2/access_secret",
93 {
94 # No user mean's we message ourselves
95 "instance": NotifyTwitter,
96 # Expected notify() response False (because we won't be able
97 # to detect our user); default mock has no v2 data key
98 "notify_response": False,
99 # Our expected url(privacy=True) startswith() response:
100 "privacy_url": "x://c...y/****/a...2/****",
101 },
102 ),
103 (
104 (
105 "twitter://consumer_key/consumer_secret/atoken3/access_secret"
106 "?cache=no"
107 ),
108 {
109 # No user mean's we message ourselves
110 "instance": NotifyTwitter,
111 # v2 whoami format: {"data": {"id": "...", "username": "..."}}
112 "requests_response_text": {
113 "data": {"id": "12345", "username": "test"},
114 "media_id": 123,
115 },
116 },
117 ),
118 (
119 "twitter://consumer_key/consumer_secret/atoken4/access_secret",
120 {
121 # No user mean's we message ourselves
122 "instance": NotifyTwitter,
123 # v2 whoami format
124 "requests_response_text": {
125 "data": {"id": "12345", "username": "test"},
126 "media_id": 123,
127 },
128 },
129 ),
130 # A duplicate of the entry above, this will cause cache to be referenced
131 (
132 "twitter://consumer_key/consumer_secret/atoken5/access_secret",
133 {
134 # No user mean's we message ourselves
135 "instance": NotifyTwitter,
136 # v2 whoami format
137 "requests_response_text": {
138 "data": {"id": "12345", "username": "test"},
139 "media_id": 123,
140 },
141 },
142 ),
143 # handle cases where the screen_name is missing from the response causing
144 # an exception during parsing
145 (
146 "twitter://consumer_key/consumer_secret2/atoken6/access_secret",
147 {
148 # No user mean's we message ourselves
149 "instance": NotifyTwitter,
150 # v1.1-format response (missing "data" key) causes _whoami to fail
151 "requests_response_text": {
152 "id": 12345,
153 "media_id": 123,
154 },
155 # due to a mangled response_text we'll fail
156 "notify_response": False,
157 },
158 ),
159 (
160 "twitter://user@consumer_key/csecret2/atoken7/access_secret/-/%/",
161 {
162 # One Invalid User
163 "instance": NotifyTwitter,
164 # Expected notify() response False (because we won't be able
165 # to detect our user)
166 "notify_response": False,
167 },
168 ),
169 (
170 (
171 "twitter://user@consumer_key/csecret/atoken8/access_secret"
172 "?cache=No&batch=No"
173 ),
174 {
175 # No Cache & No Batch
176 "instance": NotifyTwitter,
177 # v2 user lookup format
178 "requests_response_text": {
179 "data": [{"id": "12345", "username": "user"}]
180 },
181 },
182 ),
183 (
184 "twitter://user@consumer_key/csecret/atoken9/access_secret",
185 {
186 # We're good!
187 "instance": NotifyTwitter,
188 # v2 user lookup format
189 "requests_response_text": {
190 "data": [{"id": "12345", "username": "user"}]
191 },
192 },
193 ),
194 (
195 "twitter://user@consumer_key/csecret/atoken11/access_secret",
196 {
197 # We're identifying the same user we already sent to
198 "instance": NotifyTwitter,
199 "notify_response": False,
200 },
201 ),
202 (
203 "tweet://ckey/csecret/atoken12/access_secret",
204 {
205 # A Public Tweet
206 "instance": NotifyTwitter,
207 },
208 ),
209 (
210 "twitter://user@ckey/csecret/atoken13/access_secret?mode=invalid",
211 {
212 # An invalid mode
213 "instance": AppriseImproperlyConfigured,
214 },
215 ),
216 (
217 (
218 "twitter://usera@consumer_key/consumer_secret/atoken14/"
219 "access_secret/user/?to=userb"
220 ),
221 {
222 # We're good!
223 "instance": NotifyTwitter,
224 # v2 user lookup format with multiple entries and a garbage entry
225 # to test exception handling
226 "requests_response_text": {
227 "data": [
228 {"id": "12345", "username": "usera"},
229 {"id": "12346", "username": "userb"},
230 {
231 # A garbage entry we can test exception handling on
232 },
233 ]
234 },
235 },
236 ),
237 (
238 "twitter://ckey/csecret/atoken15/access_secret",
239 {
240 "instance": NotifyTwitter,
241 # throw a bizarre code forcing us to fail to look it up
242 "response": False,
243 "requests_response_code": 999,
244 },
245 ),
246 (
247 "twitter://ckey/csecret/atoken16/access_secret",
248 {
249 "instance": NotifyTwitter,
250 # Throws a series of i/o exceptions with this flag
251 # is set and tests that we gracefully handle them
252 "test_requests_exceptions": True,
253 },
254 ),
255 (
256 "twitter://ckey/csecret/atoken17/access_secret?mode=tweet",
257 {
258 "instance": NotifyTwitter,
259 # Throws a series of i/o exceptions with this flag
260 # is set and tests that we gracefully handle them
261 "test_requests_exceptions": True,
262 },
263 ),
264 )
265
266
267 def good_response(data):
268 """Prepare a good response."""
269 response = Mock()
270 response.content = json.dumps(data)
271 response.status_code = requests.codes.ok
272 return response
273
274
275 def bad_response(data):
276 """Prepare a bad response."""
277 response = Mock()
278 response.content = json.dumps(data)
279 response.status_code = requests.codes.internal_server_error
280 return response
281
282
283 @pytest.fixture
284 def twitter_url():
285 ckey = "ckey"
286 csecret = "csecret"
287 akey = "akey"
288 asecret = "asecret"
289 url = f"twitter://{ckey}/{csecret}/{akey}/{asecret}"
290 return url
291
292
293 @pytest.fixture
294 def good_message_response():
295 """Prepare a good v2 whoami response."""
296 # v2 /users/me format: {"data": {"id": "...", "username": "..."}}
297 response = good_response(
298 {
299 "data": {
300 "id": "9876",
301 "username": TWITTER_SCREEN_NAME,
302 }
303 }
304 )
305 return response
306
307
308 @pytest.fixture
309 def bad_message_response():
310 """Prepare a bad message response."""
311 response = bad_response(
312 {
313 "errors": [
314 {
315 "code": 999,
316 "message": "Something failed",
317 }
318 ]
319 }
320 )
321 return response
322
323
324 @pytest.fixture
325 def good_media_response():
326 """Prepare a good v2 media upload response."""
327 # v2 /2/media/upload format: {"data": {"id": "...", ...}}
328 response = Mock()
329 response.content = json.dumps(
330 {
331 "data": {
332 "id": "710511363345354753",
333 "media_key": "3_710511363345354753",
334 "expires_after_secs": 86400,
335 "size": 11065,
336 }
337 }
338 )
339 response.status_code = requests.codes.ok
340 return response
341
342
343 @pytest.fixture
344 def bad_media_response():
345 """Prepare a bad media response."""
346 response = bad_response(
347 {
348 "errors": [
349 {
350 "code": 93,
351 "message": (
352 "This application is not allowed to access or "
353 "delete your direct messages."
354 ),
355 }
356 ]
357 }
358 )
359 return response
360
361
362 @pytest.fixture(autouse=True)
363 def ensure_whoami_is_mocked(mocker, good_message_response):
364 """
365 Make sure requests to https://api.twitter.com/2/users/me
366 do not escape the test harness, for all test case functions.
367 """
368 mock_get = mocker.patch("requests.get")
369 mock_get.return_value = good_message_response
370
371
372 def test_plugin_twitter_urls():
373 """NotifyTwitter() Apprise URLs."""
374
375 # Run our general tests
376 AppriseURLTester(tests=apprise_url_tests).run_all()
377
378
379 def test_plugin_twitter_general(mocker):
380 """NotifyTwitter() General Tests."""
381
382 mock_get = mocker.patch("requests.get")
383 mock_post = mocker.patch("requests.post")
384
385 ckey = "ckey"
386 csecret = "csecret"
387 akey = "akey"
388 asecret = "asecret"
389
390 # v2 user lookup response: {"data": [{"id": "...", "username": "..."}]}
391 user_lookup_obj = {
392 "data": [
393 {
394 "username": TWITTER_SCREEN_NAME,
395 "id": "9876",
396 }
397 ]
398 }
399
400 # Epoch time:
401 epoch = datetime.fromtimestamp(0, timezone.utc)
402
403 request = Mock()
404 request.content = json.dumps(user_lookup_obj)
405 request.status_code = requests.codes.ok
406 request.headers = {
407 "x-rate-limit-reset": (
408 (datetime.now(timezone.utc) - epoch).total_seconds()
409 ),
410 "x-rate-limit-remaining": 1,
411 }
412
413 # Prepare Mock
414 mock_get.return_value = request
415 mock_post.return_value = request
416
417 # Variation Initializations
418 obj = NotifyTwitter(
419 ckey=ckey,
420 csecret=csecret,
421 akey=akey,
422 asecret=asecret,
423 targets=TWITTER_SCREEN_NAME,
424 )
425
426 assert isinstance(obj, NotifyTwitter) is True
427 assert isinstance(obj.url(), str) is True
428
429 # apprise room was found
430 assert obj.send(body="test") is True
431
432 # Change our status code and try again
433 request.status_code = 403
434 assert obj.send(body="test") is False
435 assert obj.ratelimit_remaining == 1
436
437 # Return the status
438 request.status_code = requests.codes.ok
439 # Force a reset
440 request.headers["x-rate-limit-remaining"] = 0
441 # behind the scenes, it should cause us to update our rate limit
442 assert obj.send(body="test") is True
443 assert obj.ratelimit_remaining == 0
444
445 # This should cause us to block
446 request.headers["x-rate-limit-remaining"] = 10
447 assert obj.send(body="test") is True
448 assert obj.ratelimit_remaining == 10
449
450 # Handle cases where we simply couldn't get this field
451 del request.headers["x-rate-limit-remaining"]
452 assert obj.send(body="test") is True
453 # It remains set to the last value
454 assert obj.ratelimit_remaining == 10
455
456 # Reset our variable back to 1
457 request.headers["x-rate-limit-remaining"] = 1
458
459 # Handle cases where our epoch time is wrong
460 del request.headers["x-rate-limit-reset"]
461 assert obj.send(body="test") is True
462
463 # Return our object, but place it in the future forcing us to block
464 request.headers["x-rate-limit-reset"] = (
465 datetime.now(timezone.utc) - epoch
466 ).total_seconds() + 1
467 request.headers["x-rate-limit-remaining"] = 0
468 obj.ratelimit_remaining = 0
469 assert obj.send(body="test") is True
470
471 # Return our object, but place it in the future forcing us to block
472 request.headers["x-rate-limit-reset"] = (
473 datetime.now(timezone.utc) - epoch
474 ).total_seconds() - 1
475 request.headers["x-rate-limit-remaining"] = 0
476 obj.ratelimit_remaining = 0
477 assert obj.send(body="test") is True
478
479 # Return our limits to always work
480 request.headers["x-rate-limit-reset"] = (
481 datetime.now(timezone.utc) - epoch
482 ).total_seconds()
483 request.headers["x-rate-limit-remaining"] = 1
484 obj.ratelimit_remaining = 1
485
486 # Alter pending targets
487 obj.targets.append("usera")
488 # Response still in v2 user_lookup format from above
489 request.content = json.dumps(user_lookup_obj)
490
491 assert obj.send(body="test") is True
492
493 # Flush our cache forcing it is re-creating
494 obj._user_cache = {}
495 assert obj.send(body="test") is True
496
497 # Cause content response to be None
498 request.content = None
499 assert obj.send(body="test") is True
500
501 # Invalid JSON
502 request.content = "{"
503 assert obj.send(body="test") is True
504
505 # Return it to a parseable string
506 request.content = "{}"
507
508 results = NotifyTwitter.parse_url(
509 f"twitter://{ckey}/{csecret}/{akey}/{asecret}?to={TWITTER_SCREEN_NAME}"
510 )
511 assert isinstance(results, dict) is True
512 assert TWITTER_SCREEN_NAME in results["targets"]
513
514 # Valid JSON response; send succeeds
515 assert obj.send(body="test") is True
516
517 # Set ourselves up to handle whoami calls
518
519 # Flush out our cache
520 obj._user_cache = {}
521
522 # v2 whoami response: {"data": {"id": "...", "username": "..."}}
523 whoami_obj = {
524 "data": {
525 "username": TWITTER_SCREEN_NAME,
526 "id": "9876",
527 }
528 }
529 request.content = json.dumps(whoami_obj)
530
531 obj = NotifyTwitter(ckey=ckey, csecret=csecret, akey=akey, asecret=asecret)
532
533 assert obj.send(body="test") is True
534
535 # Alter the key forcing us to look up a new value of ourselves again
536 obj._user_cache = {}
537 obj._whoami_cache = None
538 obj.ckey = "different.then.it.was"
539 assert obj.send(body="test") is True
540
541 obj._whoami_cache = None
542 obj.ckey = "different.again"
543 assert obj.send(body="test") is True
544
545
546 def test_plugin_twitter_garbage_responses(mocker):
547 """Verify garbage/invalid server responses are handled gracefully."""
548
549 mock_get = mocker.patch("requests.get")
550 mock_post = mocker.patch("requests.post")
551
552 ckey = "ckey"
553 csecret = "csecret"
554 akey = "akey"
555 asecret = "asecret"
556
557 # Base request mock returning HTTP 200
558 request = Mock()
559 request.status_code = requests.codes.ok
560 request.headers = {}
561
562 mock_get.return_value = request
563 mock_post.return_value = request
564
565 # No targets -> _send_dm calls _whoami
566 obj = NotifyTwitter(ckey=ckey, csecret=csecret, akey=akey, asecret=asecret)
567
568 # _whoami: None content -> TypeError in loads() -> content = {}
569 # -> no "data" key in {} -> KeyError caught -> _whoami returns {}
570 request.content = None
571 assert obj.send(body="test") is False
572
573 # _whoami: malformed JSON -> ValueError in loads() -> content = {}
574 # -> same path as above
575 obj._whoami_cache = None
576 request.content = "{"
577 assert obj.send(body="test") is False
578
579 # _whoami: valid JSON but v1.1-style response (missing "data" key)
580 # -> KeyError in _whoami -> caught -> returns {}
581 obj._whoami_cache = None
582 request.content = json.dumps({"screen_name": "apprise", "id": 9876})
583 assert obj.send(body="test") is False
584
585 # Has targets -> _send_dm calls _user_lookup
586 obj2 = NotifyTwitter(
587 ckey=ckey,
588 csecret=csecret,
589 akey=akey,
590 asecret=asecret,
591 targets=TWITTER_SCREEN_NAME,
592 )
593
594 # _user_lookup: response is a list, not a dict
595 # -> isinstance(response, dict) is False -> continue -> no results
596 request.content = json.dumps(
597 [{"id": "9876", "username": TWITTER_SCREEN_NAME}]
598 )
599 assert obj2.send(body="test") is False
600
601 # _fetch: json=False with a non-None payload -> raw body path
602 request.content = json.dumps({})
603 postokay, _ = obj._fetch(
604 "https://api.twitter.com/2/tweets",
605 payload="raw=data",
606 json=False,
607 )
608 assert postokay is True
609
610 # _fetch: HTTP 201 Created is treated as success (v2 POST endpoints)
611 request.status_code = requests.codes.created
612 request.content = json.dumps({"data": {"id": "1"}})
613 postokay, _response = obj._fetch(
614 "https://api.twitter.com/2/tweets",
615 payload={"text": "hi"},
616 )
617 assert postokay is True
618
619
620 def test_plugin_twitter_edge_cases():
621 """NotifyTwitter() Edge Cases."""
622
623 with pytest.raises(AppriseImproperlyConfigured):
624 NotifyTwitter(ckey=None, csecret=None, akey=None, asecret=None)
625
626 with pytest.raises(AppriseImproperlyConfigured):
627 NotifyTwitter(ckey="value", csecret=None, akey=None, asecret=None)
628
629 with pytest.raises(AppriseImproperlyConfigured):
630 NotifyTwitter(ckey="value", csecret="value", akey=None, asecret=None)
631
632 with pytest.raises(AppriseImproperlyConfigured):
633 NotifyTwitter(
634 ckey="value", csecret="value", akey="value", asecret=None
635 )
636
637 assert isinstance(
638 NotifyTwitter(
639 ckey="value", csecret="value", akey="value", asecret="value"
640 ),
641 NotifyTwitter,
642 )
643
644 assert isinstance(
645 NotifyTwitter(
646 ckey="value",
647 csecret="value",
648 akey="value",
649 asecret="value",
650 user="l2gnux",
651 ),
652 NotifyTwitter,
653 )
654
655 # Invalid Target User
656 obj = NotifyTwitter(
657 ckey="value",
658 csecret="value",
659 akey="value",
660 asecret="value",
661 targets="%G@rB@g3",
662 )
663
664 assert (
665 bool(
666 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
667 )
668 is False
669 )
670
671
672 def test_plugin_twitter_dm_caching(
673 mocker, twitter_url, good_message_response, good_media_response
674 ):
675 """Verify that the `NotifyTwitter.{_user_cache,_whoami_cache}` caches work
676 as intended."""
677
678 # This is the request to `https://api.twitter.com/2/users/me`.
679 # Explicitly mock it here so the calls to it can be evaluated.
680 mock_get = mocker.patch("requests.get")
681 mock_get.return_value = good_message_response
682
683 # This test case submits two notifications, so make sure to provide two
684 # mocked responses.
685 mock_post = mocker.patch("requests.post")
686 mock_post.side_effect = [good_message_response, good_message_response]
687
688 # Make sure to start with empty caches.
689 if hasattr(NotifyTwitter, "_user_cache"):
690 NotifyTwitter._user_cache = {}
691 if hasattr(NotifyTwitter, "_whoami_cache"):
692 NotifyTwitter._whoami_cache = {}
693
694 # Create application objects.
695 obj = Apprise.instantiate(twitter_url)
696
697 # Send the first notification.
698 assert (
699 bool(
700 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
701 )
702 is True
703 )
704
705 # Test call counts.
706 assert mock_get.call_count == 1
707 assert (
708 # v2 current-user endpoint replaced v1.1 verify_credentials
709 mock_get.call_args_list[0][0][0]
710 == "https://api.twitter.com/2/users/me"
711 )
712
713 assert mock_post.call_count == 1
714 # v2 DM endpoint; user id "9876" comes from good_message_response
715 assert (
716 mock_post.call_args_list[0][0][0]
717 == "https://api.twitter.com/2/dm_conversations/with/9876/messages"
718 )
719
720 # Reset the mocks to start counting calls from scratch.
721 mock_get.reset_mock()
722 mock_post.reset_mock()
723
724 # Send another notification.
725 assert (
726 bool(
727 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
728 )
729 is True
730 )
731
732 # Calls to `users/me` will get cached by `NotifyTwitter`.
733 # So, the `GET` request to `users/me` should only have been
734 # issued once.
735 assert mock_get.call_count == 0
736 assert mock_post.call_count == 1
737
738
739 def test_plugin_twitter_dm_attachments_basic(
740 mocker, twitter_url, good_message_response, good_media_response
741 ):
742 """
743 NotifyTwitter() DM Attachment Checks - Basic
744 """
745
746 mock_get = mocker.patch("requests.get")
747 mock_post = mocker.patch("requests.post")
748
749 # Epoch time:
750 epoch = datetime.fromtimestamp(0, timezone.utc)
751 mock_get.return_value = good_message_response
752 mock_post.return_value.headers = {
753 "x-rate-limit-reset": (
754 (datetime.now(timezone.utc) - epoch).total_seconds()
755 ),
756 "x-rate-limit-remaining": 1,
757 }
758
759 # The first response is for uploading the attachment,
760 # the second one for posting the actual message.
761 mock_post.side_effect = [good_media_response, good_message_response]
762
763 # Create application objects.
764 obj = Apprise.instantiate(twitter_url)
765 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
766
767 # Send our notification.
768 tracker_token = _delivery_tracker.set(set())
769 try:
770 assert (
771 bool(
772 obj.notify(
773 body="body",
774 title="title",
775 notify_type=NotifyType.INFO,
776 attach=attach,
777 )
778 )
779 is True
780 )
781 finally:
782 _delivery_tracker.reset(tracker_token)
783
784 # Test call counts.
785 assert mock_get.call_count == 1
786 assert (
787 # v2 whoami endpoint
788 mock_get.call_args_list[0][0][0]
789 == "https://api.twitter.com/2/users/me"
790 )
791
792 assert mock_post.call_count == 2
793 assert (
794 # v2 media upload endpoint (available on all access tiers)
795 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
796 )
797 assert (
798 # v2 DM endpoint; user id "9876" comes from good_message_response
799 mock_post.call_args_list[1][0][0]
800 == "https://api.twitter.com/2/dm_conversations/with/9876/messages"
801 )
802
803
804 def test_plugin_twitter_dm_attachments_message_fails(
805 mocker, twitter_url, good_media_response, bad_message_response
806 ):
807 """Test case with a bad media response."""
808
809 mock_post = mocker.patch("requests.post")
810 mock_post.side_effect = [good_media_response, bad_message_response]
811
812 # Create application objects.
813 obj = Apprise.instantiate(twitter_url)
814 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
815
816 # Send our notification; it will fail because of the message response.
817 assert (
818 bool(
819 obj.notify(
820 body="body",
821 title="title",
822 notify_type=NotifyType.INFO,
823 attach=attach,
824 )
825 )
826 is False
827 )
828
829 assert mock_post.call_count == 2
830 assert (
831 # v2 media upload endpoint (available on all access tiers)
832 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
833 )
834 assert (
835 # v2 DM endpoint; user id "9876" comes from good_message_response
836 mock_post.call_args_list[1][0][0]
837 == "https://api.twitter.com/2/dm_conversations/with/9876/messages"
838 )
839
840
841 def test_plugin_twitter_dm_attachments_upload_fails(
842 mocker, twitter_url, good_message_response, bad_media_response
843 ):
844 """Test case where upload fails."""
845
846 mock_post = mocker.patch("requests.post")
847 mock_post.side_effect = [bad_media_response, good_message_response]
848
849 # Create application objects.
850 obj = Apprise.instantiate(twitter_url)
851 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
852
853 # Send our notification; it will fail because of the media response.
854 assert (
855 bool(
856 obj.notify(
857 body="body",
858 title="title",
859 notify_type=NotifyType.INFO,
860 attach=attach,
861 )
862 )
863 is False
864 )
865
866 # Test call counts.
867 assert mock_post.call_count == 1
868 assert (
869 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
870 )
871
872
873 def test_plugin_twitter_dm_attachments_invalid_attachment(
874 mocker, twitter_url, good_message_response
875 ):
876 """Test case with an invalid attachment."""
877
878 mock_post: Mock = mocker.patch("requests.post")
879 mock_post.side_effect = [good_media_response, good_message_response]
880
881 # Create application objects.
882 # An invalid attachment will cause a failure.
883 obj = Apprise.instantiate(twitter_url)
884 attach = AppriseAttachment(
885 os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
886 )
887
888 assert (
889 bool(
890 obj.notify(
891 body="body",
892 title="title",
893 notify_type=NotifyType.INFO,
894 attach=attach,
895 )
896 )
897 is False
898 )
899
900 # Verify no post requests have been issued, because attachment is not good.
901 assert mock_post.mock_calls == []
902
903
904 def test_plugin_twitter_dm_attachments_multiple(
905 mocker, twitter_url, good_message_response, good_media_response
906 ):
907 """Verify multiple attachments are included with a direct message."""
908
909 mock_post = mocker.patch("requests.post")
910
911 mock_post.side_effect = [
912 good_media_response,
913 good_media_response,
914 good_media_response,
915 good_media_response,
916 good_message_response,
917 good_message_response,
918 good_message_response,
919 good_message_response,
920 ]
921
922 # 4 images are produced
923 attach = [
924 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
925 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
926 os.path.join(TEST_VAR_DIR, "apprise-test.jpeg"),
927 os.path.join(TEST_VAR_DIR, "apprise-test.png"),
928 # This one is not supported, so it's ignored gracefully
929 os.path.join(TEST_VAR_DIR, "apprise-test.mp4"),
930 ]
931
932 # Create application objects.
933 obj = Apprise.instantiate(twitter_url)
934
935 tracker_token = _delivery_tracker.set(set())
936 try:
937 assert (
938 bool(
939 obj.notify(
940 body="body",
941 title="title",
942 notify_type=NotifyType.INFO,
943 attach=attach,
944 )
945 )
946 is True
947 )
948 finally:
949 _delivery_tracker.reset(tracker_token)
950
951 assert mock_post.call_count == 8
952 # First 4 calls are v2 media uploads
953 assert (
954 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
955 )
956 assert (
957 mock_post.call_args_list[1][0][0] == "https://api.x.com/2/media/upload"
958 )
959 assert (
960 mock_post.call_args_list[2][0][0] == "https://api.x.com/2/media/upload"
961 )
962 assert (
963 mock_post.call_args_list[3][0][0] == "https://api.x.com/2/media/upload"
964 )
965 # Last 4 calls are DM sends via v2 endpoint; user id "9876" from
966 # good_message_response
967 assert (
968 mock_post.call_args_list[4][0][0]
969 == "https://api.twitter.com/2/dm_conversations/with/9876/messages"
970 )
971 assert (
972 mock_post.call_args_list[5][0][0]
973 == "https://api.twitter.com/2/dm_conversations/with/9876/messages"
974 )
975 assert (
976 mock_post.call_args_list[6][0][0]
977 == "https://api.twitter.com/2/dm_conversations/with/9876/messages"
978 )
979 assert (
980 mock_post.call_args_list[7][0][0]
981 == "https://api.twitter.com/2/dm_conversations/with/9876/messages"
982 )
983
984
985 def test_plugin_twitter_dm_attachments_multiple_oserror(
986 mocker, twitter_url, good_message_response, good_media_response
987 ):
988 """Verify a file error during multi-attachment DM delivery is handled."""
989
990 # Inject an `OSError` into the middle of the operation.
991 mock_post = mocker.patch("requests.post")
992 mock_post.side_effect = [good_media_response, OSError()]
993
994 # 2 images are produced
995 attach = [
996 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
997 os.path.join(TEST_VAR_DIR, "apprise-test.png"),
998 # This one is not supported, so it's ignored gracefully
999 os.path.join(TEST_VAR_DIR, "apprise-test.mp4"),
1000 ]
1001
1002 # Create application objects.
1003 obj = Apprise.instantiate(twitter_url)
1004
1005 # We'll fail to send this time
1006 assert (
1007 bool(
1008 obj.notify(
1009 body="body",
1010 title="title",
1011 notify_type=NotifyType.INFO,
1012 attach=attach,
1013 )
1014 )
1015 is False
1016 )
1017
1018 assert mock_post.call_count == 2
1019 assert (
1020 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1021 )
1022 assert (
1023 mock_post.call_args_list[1][0][0] == "https://api.x.com/2/media/upload"
1024 )
1025
1026
1027 @patch("requests.post")
1028 def test_plugin_twitter_tweet_attachments_basic(
1029 mock_post, twitter_url, good_message_response, good_media_response
1030 ):
1031 """
1032 NotifyTwitter() Tweet Attachment Checks - Basic
1033 """
1034
1035 mock_post.side_effect = [good_media_response, good_message_response]
1036
1037 # Create application objects.
1038 twitter_url += "?mode=tweet"
1039 obj = Apprise.instantiate(twitter_url)
1040 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1041
1042 # Send our notification
1043 assert (
1044 bool(
1045 obj.notify(
1046 body="body",
1047 title="title",
1048 notify_type=NotifyType.INFO,
1049 attach=attach,
1050 )
1051 )
1052 is True
1053 )
1054
1055 # Verify API calls.
1056 assert mock_post.call_count == 2
1057 assert (
1058 # v2 media upload endpoint (available on all access tiers)
1059 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1060 )
1061 assert (
1062 # v2 tweet endpoint
1063 mock_post.call_args_list[1][0][0] == "https://api.twitter.com/2/tweets"
1064 )
1065
1066
1067 @patch("requests.post")
1068 def test_plugin_twitter_tweet_attachments_more_logging(
1069 mock_post, twitter_url, good_media_response
1070 ):
1071 """
1072 NotifyTwitter() Tweet Attachment Checks - More logging
1073 """
1074
1075 # v2 tweet response: {"data": {"id": "...", "text": "..."}}
1076 good_tweet_response = good_response(
1077 {
1078 "data": {
1079 "id": "12345",
1080 "text": "body",
1081 },
1082 }
1083 )
1084
1085 mock_post.side_effect = [good_media_response, good_tweet_response]
1086
1087 # Create application objects.
1088 twitter_url += "?mode=tweet"
1089 obj = Apprise.instantiate(twitter_url)
1090 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1091
1092 # Send our notification
1093 assert (
1094 bool(
1095 obj.notify(
1096 body="body",
1097 title="title",
1098 notify_type=NotifyType.INFO,
1099 attach=attach,
1100 )
1101 )
1102 is True
1103 )
1104
1105 # Verify API calls.
1106 assert mock_post.call_count == 2
1107 assert (
1108 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1109 )
1110 assert (
1111 mock_post.call_args_list[1][0][0] == "https://api.twitter.com/2/tweets"
1112 )
1113
1114
1115 @patch("requests.post")
1116 def test_plugin_twitter_tweet_attachments_bad_message_response(
1117 mock_post, twitter_url, good_media_response, bad_message_response
1118 ):
1119 """Verify a failed tweet response fails attachment delivery."""
1120
1121 mock_post.side_effect = [good_media_response, bad_message_response]
1122
1123 # Create application objects.
1124 twitter_url += "?mode=tweet"
1125 obj = Apprise.instantiate(twitter_url)
1126 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1127
1128 # Our notification will fail now since our tweet will error out.
1129 assert (
1130 bool(
1131 obj.notify(
1132 body="body",
1133 title="title",
1134 notify_type=NotifyType.INFO,
1135 attach=attach,
1136 )
1137 )
1138 is False
1139 )
1140
1141 # Verify API calls.
1142 assert mock_post.call_count == 2
1143 assert (
1144 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1145 )
1146 assert (
1147 mock_post.call_args_list[1][0][0] == "https://api.twitter.com/2/tweets"
1148 )
1149
1150
1151 @patch("requests.post")
1152 def test_plugin_twitter_unparseable_attachment_error(
1153 mock_post, twitter_url, good_media_response
1154 ):
1155 """Verify an unparseable tweet failure response is handled."""
1156
1157 bad_message_response = bad_response("")
1158 mock_post.side_effect = [good_media_response, bad_message_response]
1159
1160 # Create application objects.
1161 twitter_url += "?mode=tweet"
1162 obj = Apprise.instantiate(twitter_url)
1163 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1164
1165 # The notification will fail now since the tweet will error out.
1166 # This is the same test as above, except that the error response is not
1167 # parseable.
1168 assert (
1169 bool(
1170 obj.notify(
1171 body="body",
1172 title="title",
1173 notify_type=NotifyType.INFO,
1174 attach=attach,
1175 )
1176 )
1177 is False
1178 )
1179
1180 # Verify API calls.
1181 assert mock_post.call_count == 2
1182 assert (
1183 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1184 )
1185 assert (
1186 mock_post.call_args_list[1][0][0] == "https://api.twitter.com/2/tweets"
1187 )
1188
1189
1190 @patch("requests.post")
1191 def test_plugin_twitter_tweet_attachments_upload_fails(
1192 mock_post, twitter_url, good_media_response
1193 ):
1194 """Verify a failed media upload prevents tweet delivery."""
1195
1196 # Prepare a bad tweet response.
1197 bad_tweet_response = bad_response({})
1198
1199 # Test case where upload fails.
1200 mock_post.side_effect = [good_media_response, bad_tweet_response]
1201
1202 # Create application objects.
1203 twitter_url += "?mode=tweet"
1204 obj = Apprise.instantiate(twitter_url)
1205 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1206
1207 # Send our notification; it will fail because of the message response.
1208 assert (
1209 bool(
1210 obj.notify(
1211 body="body",
1212 title="title",
1213 notify_type=NotifyType.INFO,
1214 attach=attach,
1215 )
1216 )
1217 is False
1218 )
1219
1220 # Verify API calls.
1221 assert mock_post.call_count == 2
1222 assert (
1223 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1224 )
1225 assert (
1226 mock_post.call_args_list[1][0][0] == "https://api.twitter.com/2/tweets"
1227 )
1228
1229
1230 @patch("requests.post")
1231 def test_plugin_twitter_tweet_attachments_invalid_attachment(
1232 mock_post, twitter_url, good_message_response, good_media_response
1233 ):
1234 """Verify an invalid tweet attachment is rejected cleanly."""
1235
1236 mock_post.side_effect = [good_media_response, good_message_response]
1237
1238 # Create application objects.
1239 twitter_url += "?mode=tweet"
1240 obj = Apprise.instantiate(twitter_url)
1241 attach = AppriseAttachment(
1242 os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
1243 )
1244
1245 # An invalid attachment will cause a failure.
1246 assert (
1247 bool(
1248 obj.notify(
1249 body="body",
1250 title="title",
1251 notify_type=NotifyType.INFO,
1252 attach=attach,
1253 )
1254 )
1255 is False
1256 )
1257
1258 # No post request as attachment is not good.
1259 assert mock_post.call_count == 0
1260
1261
1262 @patch("requests.post")
1263 def test_plugin_twitter_tweet_attachments_multiple_batch(
1264 mock_post, twitter_url, good_message_response, good_media_response
1265 ):
1266 """Verify multiple tweet attachments are sent in batch mode."""
1267
1268 mock_post.side_effect = [
1269 good_media_response,
1270 good_media_response,
1271 good_media_response,
1272 good_media_response,
1273 good_message_response,
1274 good_message_response,
1275 good_message_response,
1276 good_message_response,
1277 ]
1278
1279 # instantiate our object
1280 obj = Apprise.instantiate(twitter_url + "?mode=tweet")
1281
1282 # 4 images are produced
1283 attach = [
1284 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
1285 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
1286 os.path.join(TEST_VAR_DIR, "apprise-test.jpeg"),
1287 os.path.join(TEST_VAR_DIR, "apprise-test.png"),
1288 # This one is not supported, so it's ignored gracefully
1289 os.path.join(TEST_VAR_DIR, "apprise-test.mp4"),
1290 ]
1291
1292 assert (
1293 bool(
1294 obj.notify(
1295 body="body",
1296 title="title",
1297 notify_type=NotifyType.INFO,
1298 attach=attach,
1299 )
1300 )
1301 is True
1302 )
1303
1304 assert mock_post.call_count == 7
1305 assert (
1306 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1307 )
1308 assert (
1309 mock_post.call_args_list[1][0][0] == "https://api.x.com/2/media/upload"
1310 )
1311 assert (
1312 mock_post.call_args_list[2][0][0] == "https://api.x.com/2/media/upload"
1313 )
1314 assert (
1315 mock_post.call_args_list[3][0][0] == "https://api.x.com/2/media/upload"
1316 )
1317 # v2 tweet endpoint
1318 assert (
1319 mock_post.call_args_list[4][0][0] == "https://api.twitter.com/2/tweets"
1320 )
1321 assert (
1322 mock_post.call_args_list[5][0][0] == "https://api.twitter.com/2/tweets"
1323 )
1324 # The 2 images are grouped together (batch mode)
1325 assert (
1326 mock_post.call_args_list[6][0][0] == "https://api.twitter.com/2/tweets"
1327 )
1328
1329
1330 @patch("requests.post")
1331 def test_plugin_twitter_tweet_attachments_multiple_nobatch(
1332 mock_post, twitter_url, good_message_response, good_media_response
1333 ):
1334 """Verify multiple tweet attachments are sent without batch mode."""
1335
1336 mock_post.side_effect = [
1337 good_media_response,
1338 good_media_response,
1339 good_media_response,
1340 good_media_response,
1341 good_message_response,
1342 good_message_response,
1343 good_message_response,
1344 good_message_response,
1345 ]
1346
1347 # instantiate our object (without a batch mode)
1348 obj = Apprise.instantiate(twitter_url + "?mode=tweet&batch=no")
1349
1350 # 4 images are produced
1351 attach = [
1352 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
1353 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
1354 os.path.join(TEST_VAR_DIR, "apprise-test.jpeg"),
1355 os.path.join(TEST_VAR_DIR, "apprise-test.png"),
1356 # This one is not supported, so it's ignored gracefully
1357 os.path.join(TEST_VAR_DIR, "apprise-test.mp4"),
1358 ]
1359
1360 assert (
1361 bool(
1362 obj.notify(
1363 body="body",
1364 title="title",
1365 notify_type=NotifyType.INFO,
1366 attach=attach,
1367 )
1368 )
1369 is True
1370 )
1371
1372 assert mock_post.call_count == 8
1373 assert (
1374 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1375 )
1376 assert (
1377 mock_post.call_args_list[1][0][0] == "https://api.x.com/2/media/upload"
1378 )
1379 assert (
1380 mock_post.call_args_list[2][0][0] == "https://api.x.com/2/media/upload"
1381 )
1382 assert (
1383 mock_post.call_args_list[3][0][0] == "https://api.x.com/2/media/upload"
1384 )
1385 # v2 tweet endpoint (one per image, no batching)
1386 assert (
1387 mock_post.call_args_list[4][0][0] == "https://api.twitter.com/2/tweets"
1388 )
1389 assert (
1390 mock_post.call_args_list[5][0][0] == "https://api.twitter.com/2/tweets"
1391 )
1392 assert (
1393 mock_post.call_args_list[6][0][0] == "https://api.twitter.com/2/tweets"
1394 )
1395 assert (
1396 mock_post.call_args_list[7][0][0] == "https://api.twitter.com/2/tweets"
1397 )
1398
1399
1400 @patch("requests.post")
1401 def test_plugin_twitter_tweet_attachments_multiple_oserror(
1402 mock_post, twitter_url, good_media_response
1403 ):
1404 """Verify file errors during multi-attachment tweets are handled."""
1405
1406 # We have an OSError thrown in the middle of our preparation
1407 mock_post.side_effect = [good_media_response, OSError()]
1408
1409 # 2 images are produced
1410 attach = [
1411 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
1412 os.path.join(TEST_VAR_DIR, "apprise-test.png"),
1413 # This one is not supported, so it's ignored gracefully
1414 os.path.join(TEST_VAR_DIR, "apprise-test.mp4"),
1415 ]
1416
1417 # We'll fail to send this time
1418 obj = Apprise.instantiate(twitter_url + "?mode=tweet")
1419 assert (
1420 bool(
1421 obj.notify(
1422 body="body",
1423 title="title",
1424 notify_type=NotifyType.INFO,
1425 attach=attach,
1426 )
1427 )
1428 is False
1429 )
1430
1431 assert mock_post.call_count == 2
1432 assert (
1433 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1434 )
1435 assert (
1436 mock_post.call_args_list[1][0][0] == "https://api.x.com/2/media/upload"
1437 )
1438
1439
1440 @patch("requests.post")
1441 def test_plugin_twitter_tweet_attachments_jpeg_before_gif(
1442 mock_post, twitter_url, good_media_response
1443 ):
1444 """
1445 Verify that when PNG/JPEG attachments precede a GIF in batch mode,
1446 the accumulated PNG/JPEG batch is flushed first, then the GIF is
1447 emitted alone. This exercises the ``if batch:`` flush branch inside
1448 the non-batchable (GIF) path of _send_tweet.
1449 """
1450
1451 # v2 tweet response
1452 good_tweet_response = good_response(
1453 {"data": {"id": "12345", "text": "body"}}
1454 )
1455
1456 # 3 uploads (jpeg, png, gif) + 2 tweet sends = 5 post calls
1457 mock_post.side_effect = [
1458 good_media_response,
1459 good_media_response,
1460 good_media_response,
1461 good_tweet_response,
1462 good_tweet_response,
1463 ]
1464
1465 # instantiate in tweet + batch mode
1466 obj = Apprise.instantiate(twitter_url + "?mode=tweet")
1467
1468 # jpeg and png come first, then gif -- the gif triggers a flush of
1469 # the pending jpeg/png batch before being emitted in its own tweet
1470 attach = [
1471 os.path.join(TEST_VAR_DIR, "apprise-test.jpeg"),
1472 os.path.join(TEST_VAR_DIR, "apprise-test.png"),
1473 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
1474 ]
1475
1476 assert (
1477 bool(
1478 obj.notify(
1479 body="body",
1480 title="title",
1481 notify_type=NotifyType.INFO,
1482 attach=attach,
1483 )
1484 )
1485 is True
1486 )
1487
1488 # 3 media uploads + 2 tweet sends
1489 assert mock_post.call_count == 5
1490 # First 3 are v2 media uploads
1491 assert (
1492 mock_post.call_args_list[0][0][0] == "https://api.x.com/2/media/upload"
1493 )
1494 assert (
1495 mock_post.call_args_list[1][0][0] == "https://api.x.com/2/media/upload"
1496 )
1497 assert (
1498 mock_post.call_args_list[2][0][0] == "https://api.x.com/2/media/upload"
1499 )
1500 # jpeg + png batched into one tweet
1501 assert (
1502 mock_post.call_args_list[3][0][0] == "https://api.twitter.com/2/tweets"
1503 )
1504 # gif emitted alone in its own tweet
1505 assert (
1506 mock_post.call_args_list[4][0][0] == "https://api.twitter.com/2/tweets"
1507 )