Debian Codegraph @

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