Debian Codegraph @

tests/test_plugin_sns.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 # Disable logging for a cleaner testing output
29 import logging
30 from unittest import mock
31
32 from helpers import AppriseURLTester
33 import pytest
34 import requests
35
36 from apprise import Apprise
37 from apprise.plugins.sns import NotifySNS, SNSMode
38
39 logging.disable(logging.CRITICAL)
40
41
42 TEST_ACCESS_KEY_ID = "AHIAJGNT76XIMXDBIJYA"
43 TEST_ACCESS_KEY_SECRET = "bu1dHSdO22pfaaVy/wmNsdljF4C07D3bndi9PQJ9"
44 TEST_REGION = "us-east-2"
45
46 # A realistic-looking (but fake) AWS session token
47 TEST_SESSION_TOKEN = "FwoGZXIvYXdz+SESSION/TOKENABCDEFGHIJKLMNOPQRS="
48
49 # Our Testing URLs
50 apprise_url_tests = (
51 (
52 "sns://",
53 {
54 "instance": TypeError,
55 },
56 ),
57 (
58 "sns://:@/",
59 {
60 "instance": TypeError,
61 },
62 ),
63 (
64 "sns://T1JJ3T3L2",
65 {
66 # Just Token 1 provided
67 "instance": TypeError,
68 },
69 ),
70 (
71 "sns://T1JJ3TD4JD/TIiajkdnlazk7FQ/",
72 {
73 # Missing a region
74 "instance": TypeError,
75 },
76 ),
77 (
78 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/12223334444",
79 {
80 # we have a valid URL and one number to text
81 "instance": NotifySNS,
82 },
83 ),
84 (
85 (
86 "sns://?access=T1JJ3T3L2&secret=A1BRTD4JD/TIiajkdnlazkcevi7FQ"
87 "&region=us-west-2&to=12223334444"
88 ),
89 {
90 # Initialize using get parameters instead
91 "instance": NotifySNS,
92 },
93 ),
94 (
95 "sns://T1JJ3TD4JD/TIiajkdnlazk7FQ/us-west-2/12223334444/12223334445",
96 {
97 # Multi SNS Suppport
98 "instance": NotifySNS,
99 # Our expected url(privacy=True) startswith() response:
100 "privacy_url": "sns://T...D/****/us-west-2",
101 },
102 ),
103 (
104 (
105 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/us-east-1"
106 "?to=12223334444"
107 ),
108 {
109 # Missing a topic and/or phone No
110 "instance": NotifySNS,
111 },
112 ),
113 (
114 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/12223334444",
115 {
116 "instance": NotifySNS,
117 # throw a bizarre code forcing us to fail to look it up
118 "response": False,
119 "requests_response_code": 999,
120 },
121 ),
122 (
123 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/15556667777",
124 {
125 "instance": NotifySNS,
126 # Throws a series of i/o exceptions with this flag
127 # is set and tests that we gracefully handle them
128 "test_requests_exceptions": True,
129 },
130 ),
131 (
132 # Session token in userinfo position (temporary/IAM credentials)
133 "sns://SESSIONTOKEN@T1JJ3T3L2"
134 "/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/12223334444",
135 {
136 "instance": NotifySNS,
137 },
138 ),
139 (
140 # Session token via ?token= query parameter
141 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ"
142 "/us-west-2/12223334444?token=SESSIONTOKEN",
143 {
144 "instance": NotifySNS,
145 },
146 ),
147 (
148 # Access key via ?key= alias
149 "sns://?key=T1JJ3T3L2&secret=A1BRTD4JD/TIiajkdnlazkcevi7FQ"
150 "&region=us-west-2&to=12223334444",
151 {
152 "instance": NotifySNS,
153 },
154 ),
155 (
156 # Session token + HTTP error
157 "sns://SESSIONTOKEN@T1JJ3T3L2"
158 "/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/12223334444",
159 {
160 "instance": NotifySNS,
161 "response": False,
162 "requests_response_code": 999,
163 },
164 ),
165 (
166 # Session token + request exceptions
167 "sns://SESSIONTOKEN@T1JJ3T3L2"
168 "/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/15556667777",
169 {
170 "instance": NotifySNS,
171 "test_requests_exceptions": True,
172 },
173 ),
174 (
175 # Explicit SMS mode
176 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ"
177 "/us-west-2/12223334444?mode=sms",
178 {
179 "instance": NotifySNS,
180 },
181 ),
182 (
183 # Forced topic mode on a phone target
184 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ"
185 "/us-west-2/12223334444?mode=topic",
186 {
187 "instance": NotifySNS,
188 },
189 ),
190 (
191 # Invalid mode raises TypeError
192 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ"
193 "/us-west-2/12223334444?mode=invalid",
194 {
195 "instance": TypeError,
196 },
197 ),
198 )
199
200
201 def test_plugin_sns_urls():
202 """NotifySNS() Apprise URLs."""
203
204 # Run our general tests
205 AppriseURLTester(tests=apprise_url_tests).run_all()
206
207
208 # We initialize a post object just incase a test fails below
209 # we don't want it sending any notifications upstream
210 @mock.patch("requests.post")
211 def test_plugin_sns_edge_cases(mock_post):
212 """NotifySNS() Edge Cases."""
213 target = "+1800555999"
214 # Initializes the plugin with a valid access, but invalid access key
215 with pytest.raises(TypeError):
216 # No access_key_id specified
217 NotifySNS(
218 access_key_id=None,
219 secret_access_key=TEST_ACCESS_KEY_SECRET,
220 region_name=TEST_REGION,
221 targets=target,
222 )
223
224 with pytest.raises(TypeError):
225 # No secret_access_key specified
226 NotifySNS(
227 access_key_id=TEST_ACCESS_KEY_ID,
228 secret_access_key=None,
229 region_name=TEST_REGION,
230 targets=target,
231 )
232
233 with pytest.raises(TypeError):
234 # No region_name specified
235 NotifySNS(
236 access_key_id=TEST_ACCESS_KEY_ID,
237 secret_access_key=TEST_ACCESS_KEY_SECRET,
238 region_name=None,
239 targets=target,
240 )
241
242 # No recipients
243 obj = NotifySNS(
244 access_key_id=TEST_ACCESS_KEY_ID,
245 secret_access_key=TEST_ACCESS_KEY_SECRET,
246 region_name=TEST_REGION,
247 targets=None,
248 )
249
250 # The object initializes properly but would not be able to send anything
251 assert obj.notify(body="test", title="test") is False
252
253 # The phone number is invalid, and without it, there is nothing
254 # to notify
255 obj = NotifySNS(
256 access_key_id=TEST_ACCESS_KEY_ID,
257 secret_access_key=TEST_ACCESS_KEY_SECRET,
258 region_name=TEST_REGION,
259 targets="+1809",
260 )
261
262 # The object initializes properly but would not be able to send anything
263 assert obj.notify(body="test", title="test") is False
264
265 # The phone number is invalid, and without it, there is nothing
266 # to notify; we
267 obj = NotifySNS(
268 access_key_id=TEST_ACCESS_KEY_ID,
269 secret_access_key=TEST_ACCESS_KEY_SECRET,
270 region_name=TEST_REGION,
271 targets="#(invalid-topic-because-of-the-brackets)",
272 )
273
274 # The object initializes properly but would not be able to send anything
275 assert obj.notify(body="test", title="test") is False
276
277
278 def test_plugin_sns_url_parsing():
279 """NotifySNS() URL Parsing."""
280
281 # No recipients
282 results = NotifySNS.parse_url(
283 f"sns://{TEST_ACCESS_KEY_ID}/{TEST_ACCESS_KEY_SECRET}/{TEST_REGION}/"
284 )
285
286 # Confirm that there were no recipients found
287 assert len(results["targets"]) == 0
288 assert "region_name" in results
289 assert results["region_name"] == TEST_REGION
290 assert "access_key_id" in results
291 assert results["access_key_id"] == TEST_ACCESS_KEY_ID
292 assert "secret_access_key" in results
293 assert results["secret_access_key"] == TEST_ACCESS_KEY_SECRET
294
295 target = "+18001234567"
296 topic = "MyTopic"
297
298 # Detect recipients
299 results = NotifySNS.parse_url(
300 f"sns://{TEST_ACCESS_KEY_ID}/"
301 f"{TEST_ACCESS_KEY_SECRET}/"
302 f"{TEST_REGION.upper()}/"
303 f"{target}/"
304 f"{topic}/"
305 )
306
307 # Confirm that our recipients were found
308 assert len(results["targets"]) == 2
309 assert target in results["targets"]
310 assert topic in results["targets"]
311 assert "region_name" in results
312 assert results["region_name"] == TEST_REGION
313 assert "access_key_id" in results
314 assert results["access_key_id"] == TEST_ACCESS_KEY_ID
315 assert "secret_access_key" in results
316 assert results["secret_access_key"] == TEST_ACCESS_KEY_SECRET
317
318
319 def test_plugin_sns_object_parsing():
320 """NotifySNS() Object Parsing."""
321
322 # Create our object
323 a = Apprise()
324
325 # Now test failing variations of our URL
326 assert a.add("sns://") is False
327 assert a.add("sns://nosecret") is False
328 assert a.add("sns://nosecret/noregion/") is False
329
330 # This is valid but without valid recipients; while it's still a valid URL
331 # it won't do much when the user goes to send a notification
332 assert a.add("sns://norecipient/norecipient/us-west-2") is True
333 assert len(a) == 1
334
335 # Parse a good one
336 assert a.add("sns://oh/yeah/us-west-2/abcdtopic/+12223334444") is True
337 assert len(a) == 2
338
339 assert a.add("sns://oh/yeah/us-west-2/12223334444") is True
340 assert len(a) == 3
341
342
343 def test_plugin_sns_aws_response_handling():
344 """NotifySNS() AWS Response Handling."""
345 # Not a string
346 response = NotifySNS.aws_response_to_dict(None)
347 assert response["type"] is None
348 assert response["request_id"] is None
349
350 # Invalid XML
351 response = NotifySNS.aws_response_to_dict(
352 '<Bad Response xmlns="http://sns.amazonaws.com/doc/2010-03-31/">'
353 )
354 assert response["type"] is None
355 assert response["request_id"] is None
356
357 # Single Element in XML
358 response = NotifySNS.aws_response_to_dict(
359 "<SingleElement></SingleElement>"
360 )
361 assert response["type"] == "SingleElement"
362 assert response["request_id"] is None
363
364 # Empty String
365 response = NotifySNS.aws_response_to_dict("")
366 assert response["type"] is None
367 assert response["request_id"] is None
368
369 response = NotifySNS.aws_response_to_dict("""
370 <PublishResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
371 <PublishResult>
372 <MessageId>5e16935a-d1fb-5a31-a716-c7805e5c1d2e</MessageId>
373 </PublishResult>
374 <ResponseMetadata>
375 <RequestId>dc258024-d0e6-56bb-af1b-d4fe5f4181a4</RequestId>
376 </ResponseMetadata>
377 </PublishResponse>
378 """)
379 assert response["type"] == "PublishResponse"
380 assert response["request_id"] == "dc258024-d0e6-56bb-af1b-d4fe5f4181a4"
381 assert response["message_id"] == "5e16935a-d1fb-5a31-a716-c7805e5c1d2e"
382
383 response = NotifySNS.aws_response_to_dict("""
384 <CreateTopicResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
385 <CreateTopicResult>
386 <TopicArn>arn:aws:sns:us-east-1:000000000000:abcd</TopicArn>
387 </CreateTopicResult>
388 <ResponseMetadata>
389 <RequestId>604bef0f-369c-50c5-a7a4-bbd474c83d6a</RequestId>
390 </ResponseMetadata>
391 </CreateTopicResponse>
392 """)
393 assert response["type"] == "CreateTopicResponse"
394 assert response["request_id"] == "604bef0f-369c-50c5-a7a4-bbd474c83d6a"
395 assert response["topic_arn"] == "arn:aws:sns:us-east-1:000000000000:abcd"
396
397 response = NotifySNS.aws_response_to_dict("""
398 <ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
399 <Error>
400 <Type>Sender</Type>
401 <Code>InvalidParameter</Code>
402 <Message>Invalid parameter: TopicArn or TargetArn Reason:
403 no value for required parameter</Message>
404 </Error>
405 <RequestId>b5614883-babe-56ca-93b2-1c592ba6191e</RequestId>
406 </ErrorResponse>
407 """)
408 assert response["type"] == "ErrorResponse"
409 assert response["request_id"] == "b5614883-babe-56ca-93b2-1c592ba6191e"
410 assert response["error_type"] == "Sender"
411 assert response["error_code"] == "InvalidParameter"
412 assert response["error_message"].startswith("Invalid parameter:")
413 assert response["error_message"].endswith("required parameter")
414
415
416 @mock.patch("requests.post")
417 def test_plugin_sns_aws_topic_handling(mock_post):
418 """NotifySNS() AWS Topic Handling."""
419
420 arn_response = """
421 <CreateTopicResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
422 <CreateTopicResult>
423 <TopicArn>arn:aws:sns:us-east-1:000000000000:abcd</TopicArn>
424 </CreateTopicResult>
425 <ResponseMetadata>
426 <RequestId>604bef0f-369c-50c5-a7a4-bbd474c83d6a</RequestId>
427 </ResponseMetadata>
428 </CreateTopicResponse>
429 """
430
431 def post(url, data, **kwargs):
432 """Since Publishing a token requires 2 posts, we need to return our
433 response depending on what step we're on."""
434
435 # A request
436 robj = mock.Mock()
437 robj.text = ""
438 robj.status_code = requests.codes.ok
439
440 if data.find("=CreateTopic") >= 0:
441 # Topic Post Failure
442 robj.status_code = requests.codes.bad_request
443
444 return robj
445
446 # Assign ourselves a new function
447 mock_post.side_effect = post
448
449 # Create our object
450 a = Apprise()
451
452 a.add(
453 [
454 # Single Topic
455 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnl/us-west-2/TopicA",
456 # Multi-Topic
457 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnl/us-east-1/TopicA/TopicB/"
458 # Topic-Mix
459 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkce/us-west-2/"
460 "12223334444/TopicA",
461 ]
462 )
463
464 # CreateTopic fails
465 assert a.notify(title="", body="test") is False
466
467 def post(url, data, **kwargs):
468 """Since Publishing a token requires 2 posts, we need to return our
469 response depending on what step we're on."""
470
471 # A request
472 robj = mock.Mock()
473 robj.text = ""
474 robj.status_code = requests.codes.ok
475
476 if data.find("=CreateTopic") >= 0:
477 robj.text = arn_response
478
479 # Manipulate Topic Publishing only (not phone)
480 elif data.find("=Publish") >= 0 and data.find("TopicArn=") >= 0:
481 # Topic Post Failure
482 robj.status_code = requests.codes.bad_request
483
484 return robj
485
486 # Assign ourselves a new function
487 mock_post.side_effect = post
488
489 # Publish fails
490 assert a.notify(title="", body="test") is False
491
492 # Disable our side effect
493 mock_post.side_effect = None
494
495 # Handle case where TopicArn is missing:
496 robj = mock.Mock()
497 robj.text = "<CreateTopicResponse></CreateTopicResponse>"
498 robj.status_code = requests.codes.ok
499
500 # Assign ourselves a new function
501 mock_post.return_value = robj
502 assert a.notify(title="", body="test") is False
503
504 # Handle case where we fails get a bad response
505 robj = mock.Mock()
506 robj.text = ""
507 robj.status_code = requests.codes.bad_request
508 mock_post.return_value = robj
509 assert a.notify(title="", body="test") is False
510
511 # Handle case where we get a valid response and TopicARN
512 robj = mock.Mock()
513 robj.text = arn_response
514 robj.status_code = requests.codes.ok
515 mock_post.return_value = robj
516 # We would have failed to make Post
517 assert a.notify(title="", body="test") is True
518
519
520 @mock.patch("requests.post")
521 def test_plugin_sns_session_token(mock_post):
522 """NotifySNS() session token for temporary/IAM credentials."""
523
524 response = mock.MagicMock()
525 response.status_code = requests.codes.ok
526 response.text = ""
527 mock_post.return_value = response
528
529 # Init with session token
530 obj = NotifySNS(
531 access_key_id=TEST_ACCESS_KEY_ID,
532 secret_access_key=TEST_ACCESS_KEY_SECRET,
533 region_name=TEST_REGION,
534 targets="+18001234567",
535 session_token=TEST_SESSION_TOKEN,
536 )
537 assert obj.aws_session_token == TEST_SESSION_TOKEN
538
539 # send() must include X-Amz-Security-Token in request headers
540 assert obj.notify(body="test") is True
541 call_kwargs = mock_post.call_args[1]
542 assert "X-Amz-Security-Token" in call_kwargs["headers"]
543 assert call_kwargs["headers"]["X-Amz-Security-Token"] == TEST_SESSION_TOKEN
544
545 # x-amz-security-token must also appear in the Authorization header
546 # (it is listed in SignedHeaders)
547 auth = call_kwargs["headers"]["Authorization"]
548 assert "x-amz-security-token" in auth
549
550 # URL round-trip via userinfo position; + and = stay unencoded
551 # (safe in userinfo); / is encoded since it terminates the netloc
552 url = obj.url()
553 assert "@" in url
554 assert NotifySNS.quote(TEST_SESSION_TOKEN, safe="+=") in url
555
556 results = NotifySNS.parse_url(url)
557 assert results["session_token"] == TEST_SESSION_TOKEN
558 assert results["access_key_id"] == TEST_ACCESS_KEY_ID
559
560 obj2 = NotifySNS(**results)
561 assert obj2.aws_session_token == TEST_SESSION_TOKEN
562 assert obj2.url_identifier == obj.url_identifier
563
564 # Privacy URL must mask the token but keep the @ separator
565 priv_url = obj.url(privacy=True)
566 assert TEST_SESSION_TOKEN not in priv_url
567 assert "@" in priv_url
568
569 # Without a session token no X-Amz-Security-Token header is sent
570 mock_post.reset_mock()
571 obj_plain = NotifySNS(
572 access_key_id=TEST_ACCESS_KEY_ID,
573 secret_access_key=TEST_ACCESS_KEY_SECRET,
574 region_name=TEST_REGION,
575 targets="+18001234567",
576 )
577 assert obj_plain.aws_session_token is None
578 assert obj_plain.notify(body="test") is True
579 call_kwargs = mock_post.call_args[1]
580 assert "X-Amz-Security-Token" not in call_kwargs["headers"]
581
582 # url() without token has no @ separator
583 plain_url = obj_plain.url()
584 assert "@" not in plain_url
585
586
587 @mock.patch("requests.post")
588 def test_plugin_sns_session_token_via_kwarg(mock_post):
589 """NotifySNS() session token parsed from ?token= kwarg."""
590
591 response = mock.MagicMock()
592 response.status_code = requests.codes.ok
593 response.text = ""
594 mock_post.return_value = response
595
596 url = (
597 f"sns://{TEST_ACCESS_KEY_ID}/{TEST_ACCESS_KEY_SECRET}"
598 f"/{TEST_REGION}/+18001234567?token={TEST_SESSION_TOKEN}"
599 )
600 results = NotifySNS.parse_url(url)
601 assert results["session_token"] == TEST_SESSION_TOKEN
602
603 obj = NotifySNS(**results)
604 assert obj.aws_session_token == TEST_SESSION_TOKEN
605 assert obj.notify(body="test") is True
606
607 call_kwargs = mock_post.call_args[1]
608 assert call_kwargs["headers"]["X-Amz-Security-Token"] == TEST_SESSION_TOKEN
609
610 # ?token= overrides userinfo when both are present
611 url_both = (
612 f"sns://OTHERTOKEN@{TEST_ACCESS_KEY_ID}/{TEST_ACCESS_KEY_SECRET}"
613 f"/{TEST_REGION}/+18001234567?token={TEST_SESSION_TOKEN}"
614 )
615 results2 = NotifySNS.parse_url(url_both)
616 assert results2["session_token"] == TEST_SESSION_TOKEN
617
618
619 def test_plugin_sns_key_alias():
620 """NotifySNS() ?key= alias for access_key_id."""
621
622 # ?key= resolves to access_key_id
623 url = (
624 f"sns://?key={TEST_ACCESS_KEY_ID}"
625 f"&secret={TEST_ACCESS_KEY_SECRET}"
626 f"&region={TEST_REGION}&to=+18001234567"
627 )
628 results = NotifySNS.parse_url(url)
629 assert results["access_key_id"] == TEST_ACCESS_KEY_ID
630
631 obj = NotifySNS(**results)
632 assert obj.aws_access_key_id == TEST_ACCESS_KEY_ID
633
634 # ?key= takes priority over ?access= when both appear
635 url_both = (
636 f"sns://?key={TEST_ACCESS_KEY_ID}&access=OTHERID"
637 f"&secret={TEST_ACCESS_KEY_SECRET}"
638 f"&region={TEST_REGION}&to=+18001234567"
639 )
640 results2 = NotifySNS.parse_url(url_both)
641 assert results2["access_key_id"] == TEST_ACCESS_KEY_ID
642
643
644 def test_plugin_sns_detailed_failures(mocker):
645 """
646 Test specific failure modes (HTTP 400) for SMS, Topic Creation,
647 and Topic Publishing to ensure error counters are incremented.
648 """
649 from apprise.plugins.sns import NotifySNS
650
651 # Mock requests.post
652 mock_post = mocker.patch("requests.post")
653
654 # --- Scenario 1: SMS (Phone) Failure ---
655 obj_sms = NotifySNS(
656 access_key_id="key",
657 secret_access_key="secret",
658 region_name="us-east-1",
659 targets=["+15555555555"],
660 )
661
662 # Force a 400 Bad Request
663 mock_response_bad = mocker.Mock()
664 mock_response_bad.status_code = 400
665 mock_response_bad.text = (
666 "<ErrorResponse><Error><Message>Fail</Message></Error></ErrorResponse>"
667 )
668
669 mock_response_bad.content = mock_response_bad.text.encode("utf-8")
670 mock_post.return_value = mock_response_bad
671
672 # Should return False because the SMS failed
673 assert obj_sms.notify(body="test") is False
674
675 # --- Scenario 2: Topic Creation Failure ---
676 obj_topic = NotifySNS(
677 access_key_id="key",
678 secret_access_key="secret",
679 region_name="us-east-1",
680 targets=["#MyTopic"],
681 )
682
683 # Force 400 on ANY request (which includes the first one: CreateTopic)
684 mock_post.return_value = mock_response_bad
685
686 # Should return False because CreateTopic failed
687 assert obj_topic.notify(body="test") is False
688
689 # --- Scenario 3: CreateTopic Success, but Publish Failure ---
690 # We need a side_effect to return 200 for the first call (CreateTopic)
691 # and 400 for the second (Publish)
692
693 mock_response_ok = mocker.Mock()
694 mock_response_ok.status_code = 200
695 mock_response_ok.text = """
696 <CreateTopicResponse>
697 <CreateTopicResult>
698 <TopicArn>arn:aws:sns:us-east-1:123456789012:MyTopic</TopicArn>
699 </CreateTopicResult>
700 </CreateTopicResponse>
701 """
702 mock_response_ok.content = mock_response_ok.text.encode("utf-8")
703
704 def side_effect(*args, **kwargs):
705 data = kwargs.get("data", "")
706 if "Action=CreateTopic" in data:
707 return mock_response_ok
708 if "Action=Publish" in data:
709 return mock_response_bad
710 return mock_response_ok
711
712 mock_post.side_effect = side_effect
713
714 # Should return False because Publish failed
715 assert obj_topic.notify(body="test") is False
716
717
718 def test_plugin_sns_mode_detection():
719 """NotifySNS() auto-detects and validates operating mode."""
720
721 # Topic-only targets -> TOPIC mode auto-detected
722 obj = NotifySNS(
723 access_key_id=TEST_ACCESS_KEY_ID,
724 secret_access_key=TEST_ACCESS_KEY_SECRET,
725 region_name=TEST_REGION,
726 targets=["#MyTopic"],
727 )
728 assert obj.mode == SNSMode.TOPIC
729 assert obj.title_maxlen == 100
730 assert obj.body_maxlen == 256000
731
732 # Phone targets -> SMS mode auto-detected
733 obj = NotifySNS(
734 access_key_id=TEST_ACCESS_KEY_ID,
735 secret_access_key=TEST_ACCESS_KEY_SECRET,
736 region_name=TEST_REGION,
737 targets=["+18001234567"],
738 )
739 assert obj.mode == SNSMode.SMS
740 assert obj.title_maxlen == 0
741 assert obj.body_maxlen == 160
742
743 # Mixed targets -> SMS mode (safe default)
744 obj = NotifySNS(
745 access_key_id=TEST_ACCESS_KEY_ID,
746 secret_access_key=TEST_ACCESS_KEY_SECRET,
747 region_name=TEST_REGION,
748 targets=["+18001234567", "#MyTopic"],
749 )
750 assert obj.mode == SNSMode.SMS
751
752 # No targets -> SMS mode (safe default)
753 obj = NotifySNS(
754 access_key_id=TEST_ACCESS_KEY_ID,
755 secret_access_key=TEST_ACCESS_KEY_SECRET,
756 region_name=TEST_REGION,
757 targets=[],
758 )
759 assert obj.mode == SNSMode.SMS
760
761 # Explicit mode=topic overrides auto-detection for phone-only URL
762 obj = NotifySNS(
763 access_key_id=TEST_ACCESS_KEY_ID,
764 secret_access_key=TEST_ACCESS_KEY_SECRET,
765 region_name=TEST_REGION,
766 targets=["+18001234567"],
767 mode=SNSMode.TOPIC,
768 )
769 assert obj.mode == SNSMode.TOPIC
770
771 # Explicit mode=sms overrides auto-detection for topic-only URL
772 obj = NotifySNS(
773 access_key_id=TEST_ACCESS_KEY_ID,
774 secret_access_key=TEST_ACCESS_KEY_SECRET,
775 region_name=TEST_REGION,
776 targets=["#MyTopic"],
777 mode=SNSMode.SMS,
778 )
779 assert obj.mode == SNSMode.SMS
780
781 # Prefix matching: "to" -> "topic"
782 obj = NotifySNS(
783 access_key_id=TEST_ACCESS_KEY_ID,
784 secret_access_key=TEST_ACCESS_KEY_SECRET,
785 region_name=TEST_REGION,
786 targets=["#MyTopic"],
787 mode="to",
788 )
789 assert obj.mode == SNSMode.TOPIC
790
791 # Invalid mode raises TypeError
792 with pytest.raises(TypeError):
793 NotifySNS(
794 access_key_id=TEST_ACCESS_KEY_ID,
795 secret_access_key=TEST_ACCESS_KEY_SECRET,
796 region_name=TEST_REGION,
797 targets=["#MyTopic"],
798 mode="invalid",
799 )
800
801
802 @mock.patch("requests.post")
803 def test_plugin_sns_topic_mode_send(mock_post):
804 """NotifySNS() TOPIC mode sets Subject field on topic payloads."""
805
806 arn_response = (
807 "<CreateTopicResponse>"
808 "<CreateTopicResult>"
809 "<TopicArn>"
810 "arn:aws:sns:us-east-2:000000000000:MyTopic"
811 "</TopicArn>"
812 "</CreateTopicResult>"
813 "</CreateTopicResponse>"
814 )
815
816 # Capture the most recent Publish payload for inspection
817 publish_data = {}
818
819 def side_effect(url, data, **kwargs):
820 """Return ARN on CreateTopic; record payload on Publish."""
821 robj = mock.Mock()
822 robj.status_code = requests.codes.ok
823 if "Action=CreateTopic" in data:
824 robj.text = arn_response
825 elif "Action=Publish" in data:
826 publish_data["data"] = data
827 robj.text = ""
828 else:
829 robj.text = ""
830 return robj
831
832 mock_post.side_effect = side_effect
833
834 # Topic-only -> TOPIC mode auto-detected; title goes to Subject
835 obj = NotifySNS(
836 access_key_id=TEST_ACCESS_KEY_ID,
837 secret_access_key=TEST_ACCESS_KEY_SECRET,
838 region_name=TEST_REGION,
839 targets=["#MyTopic"],
840 )
841 assert obj.mode == SNSMode.TOPIC
842
843 # With title: Subject must appear in the Publish payload
844 assert obj.notify(title="My Title", body="My Body") is True
845 # urlencode() uses %20 for spaces
846 assert "Subject=My%20Title" in publish_data["data"]
847 assert "Message=My%20Body" in publish_data["data"]
848
849 # With no title: Subject must not appear in the Publish payload
850 publish_data.clear()
851 assert obj.notify(title="", body="My Body") is True
852 assert "Subject=" not in publish_data.get("data", "")
853
854
855 @mock.patch("requests.post")
856 def test_plugin_sns_topic_mode_phone_forced(mock_post):
857 """NotifySNS() TOPIC mode forced on phone target prepends title."""
858
859 response = mock.MagicMock()
860 response.status_code = requests.codes.ok
861 response.text = ""
862 mock_post.return_value = response
863
864 # Force TOPIC mode on a phone target
865 obj = NotifySNS(
866 access_key_id=TEST_ACCESS_KEY_ID,
867 secret_access_key=TEST_ACCESS_KEY_SECRET,
868 region_name=TEST_REGION,
869 targets=["+18001234567"],
870 mode=SNSMode.TOPIC,
871 )
872 assert obj.mode == SNSMode.TOPIC
873
874 # With a title: it must be prepended to the body in the SMS payload
875 assert obj.notify(title="My Title", body="My Body") is True
876 data = mock_post.call_args[1]["data"]
877 # urlencode() uses %20 for spaces; \r\n becomes %0D%0A
878 assert "My%20Title" in data
879 assert "My%20Body" in data
880
881 # With no title: body is sent as-is without modification
882 mock_post.reset_mock()
883 assert obj.notify(title="", body="My Body") is True
884 data = mock_post.call_args[1]["data"]
885 assert "My%20Body" in data
886
887
888 def test_plugin_sns_mode_url_round_trip():
889 """NotifySNS() mode is preserved through url() and parse_url()."""
890
891 # TOPIC mode round-trip
892 obj = NotifySNS(
893 access_key_id=TEST_ACCESS_KEY_ID,
894 secret_access_key=TEST_ACCESS_KEY_SECRET,
895 region_name=TEST_REGION,
896 targets=["#MyTopic"],
897 mode=SNSMode.TOPIC,
898 )
899 url = obj.url()
900 assert "mode=topic" in url
901
902 results = NotifySNS.parse_url(url)
903 assert results["mode"] == SNSMode.TOPIC
904
905 obj2 = NotifySNS(**results)
906 assert obj2.mode == SNSMode.TOPIC
907 assert obj2.url_identifier == obj.url_identifier
908
909 # SMS mode round-trip
910 obj = NotifySNS(
911 access_key_id=TEST_ACCESS_KEY_ID,
912 secret_access_key=TEST_ACCESS_KEY_SECRET,
913 region_name=TEST_REGION,
914 targets=["+18001234567"],
915 mode=SNSMode.SMS,
916 )
917 url = obj.url()
918 assert "mode=sms" in url
919
920 results = NotifySNS.parse_url(url)
921 assert results["mode"] == SNSMode.SMS
922
923 obj2 = NotifySNS(**results)
924 assert obj2.mode == SNSMode.SMS
925
926 # No mode in URL -> auto-detection runs on re-instantiation
927 url_no_mode = (
928 f"sns://{TEST_ACCESS_KEY_ID}/{TEST_ACCESS_KEY_SECRET}"
929 f"/{TEST_REGION}/+18001234567"
930 )
931 results = NotifySNS.parse_url(url_no_mode)
932 assert results["mode"] is None
933 obj3 = NotifySNS(**results)
934 # Auto-detected from phone target
935 assert obj3.mode == SNSMode.SMS