Debian Codegraph @

tests/test_plugin_chime.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 from json import loads
30 import logging
31 from unittest import mock
32
33 from helpers import AppriseURLTester
34 import pytest
35 import requests
36
37 from apprise import Apprise, NotifyFormat
38 from apprise.plugins.chime import NotifyChime
39
40 logging.disable(logging.CRITICAL)
41
42 # Fake but realistic-looking credentials
43 TEST_WEBHOOK_ID = "aabbccdd-1234-5678-abcd-ef1234567890"
44 TEST_TOKEN = "AaBbCcDdEeFf1234567890=="
45
46
47 # Our Testing URLs
48 apprise_url_tests = (
49 (
50 # No webhook_id or token
51 "chime://",
52 {
53 "instance": TypeError,
54 },
55 ),
56 (
57 # Empty URL
58 "chime://:@/",
59 {
60 "instance": TypeError,
61 },
62 ),
63 (
64 # Webhook ID supplied but no token
65 "chime://aabbccdd-1234-5678-abcd-ef1234567890",
66 {
67 "instance": TypeError,
68 },
69 ),
70 (
71 # Valid webhook_id + token in path (token has base64 padding)
72 "chime://aabbccdd-1234-5678-abcd-ef1234567890/AaBbCcDd1234%3D%3D",
73 {
74 "instance": NotifyChime,
75 # Expected privacy URL prefix; pprint shows the decoded token
76 # character, so the trailing = of AaBbCcDd1234== appears as =
77 "privacy_url": "chime://a...0/A...=/",
78 },
79 ),
80 (
81 # Webhook token supplied via query string
82 "chime://aabbccdd-1234-5678-abcd-ef1234567890"
83 "?token=AaBbCcDd1234%3D%3D",
84 {
85 "instance": NotifyChime,
86 },
87 ),
88 (
89 # Webhook ID supplied via query string
90 "chime://?webhook_id=aabbccdd-1234-5678-abcd-ef1234567890"
91 "&token=AaBbCcDd1234%3D%3D",
92 {
93 "instance": NotifyChime,
94 },
95 ),
96 (
97 # Valid credentials; HTTP 500 response
98 "chime://aabbccdd-1234-5678-abcd-ef1234567890/AaBbCcDd1234%3D%3D",
99 {
100 "instance": NotifyChime,
101 "response": False,
102 "requests_response_code": (requests.codes.internal_server_error),
103 },
104 ),
105 (
106 # Valid credentials; unknown response code
107 "chime://aabbccdd-1234-5678-abcd-ef1234567890/AaBbCcDd1234%3D%3D",
108 {
109 "instance": NotifyChime,
110 # throw a bizarre code forcing us to fail to look it up
111 "response": False,
112 "requests_response_code": 999,
113 },
114 ),
115 (
116 # Valid credentials; request exceptions
117 "chime://aabbccdd-1234-5678-abcd-ef1234567890/AaBbCcDd1234%3D%3D",
118 {
119 "instance": NotifyChime,
120 # Throws a series of i/o exceptions with this flag set
121 # and tests that we gracefully handle them
122 "test_requests_exceptions": True,
123 },
124 ),
125 (
126 # Native Chime webhook URL
127 "https://hooks.chime.aws/incomingwebhooks/"
128 "aabbccdd-1234-5678-abcd-ef1234567890"
129 "?token=AaBbCcDd1234%3D%3D",
130 {
131 "instance": NotifyChime,
132 },
133 ),
134 )
135
136
137 def test_plugin_chime_urls():
138 """NotifyChime() Apprise URLs."""
139
140 # Run our general tests
141 AppriseURLTester(tests=apprise_url_tests).run_all()
142
143
144 @mock.patch("requests.post")
145 def test_plugin_chime_init(mock_post):
146 """NotifyChime() Initialization Checks."""
147
148 # Prepare a valid mock response
149 mock_post.return_value = requests.Request()
150 mock_post.return_value.status_code = requests.codes.ok
151
152 # Missing webhook_id raises TypeError
153 with pytest.raises(TypeError):
154 NotifyChime(webhook_id=None, token=TEST_TOKEN)
155
156 # Blank webhook_id raises TypeError
157 with pytest.raises(TypeError):
158 NotifyChime(webhook_id=" ", token=TEST_TOKEN)
159
160 # Missing token raises TypeError
161 with pytest.raises(TypeError):
162 NotifyChime(webhook_id=TEST_WEBHOOK_ID, token=None)
163
164 # Blank token raises TypeError
165 with pytest.raises(TypeError):
166 NotifyChime(webhook_id=TEST_WEBHOOK_ID, token=" ")
167
168 # Valid object instantiates without error
169 obj = NotifyChime(webhook_id=TEST_WEBHOOK_ID, token=TEST_TOKEN)
170 assert isinstance(obj, NotifyChime)
171
172 # Confirm the webhook_id and token are stored correctly
173 assert obj.webhook_id == TEST_WEBHOOK_ID
174 assert obj.token == TEST_TOKEN
175
176
177 @mock.patch("requests.post")
178 def test_plugin_chime_send(mock_post):
179 """NotifyChime() Send Checks."""
180
181 def _mk_resp(code):
182 """Build a minimal mock response with the given status code."""
183 resp = requests.Request()
184 resp.status_code = code
185 # content is accessed in error-path debug logging
186 resp.content = b""
187 return resp
188
189 # Prepare a successful mock response
190 mock_post.return_value = _mk_resp(requests.codes.ok)
191
192 # Instantiate a valid object
193 obj = NotifyChime(webhook_id=TEST_WEBHOOK_ID, token=TEST_TOKEN)
194 assert isinstance(obj, NotifyChime)
195
196 # Perform a successful send
197 assert obj.notify(body="Test body", title="Test title") is True
198
199 # Verify the POST was made exactly once
200 assert mock_post.call_count == 1
201
202 # Confirm the URL used matches the expected Chime webhook URL pattern
203 call_url = mock_post.call_args_list[0][0][0]
204 assert "hooks.chime.aws/incomingwebhooks/" in call_url
205 assert TEST_WEBHOOK_ID in call_url
206 # The token is URL-encoded in the query string
207 assert "token=" in call_url
208
209 mock_post.reset_mock()
210
211 # A 401 response returns False
212 mock_post.return_value = _mk_resp(requests.codes.unauthorized)
213 assert obj.notify(body="Test body") is False
214
215 mock_post.reset_mock()
216
217 # A 403 response returns False
218 mock_post.return_value = _mk_resp(requests.codes.forbidden)
219 assert obj.notify(body="Test body") is False
220
221 mock_post.reset_mock()
222
223 # A 404 response returns False
224 mock_post.return_value = _mk_resp(requests.codes.not_found)
225 assert obj.notify(body="Test body") is False
226
227 mock_post.reset_mock()
228
229 # A 429 too-many-requests response returns False
230 mock_post.return_value = _mk_resp(429)
231 assert obj.notify(body="Test body") is False
232
233 mock_post.reset_mock()
234
235 # A 500 response returns False
236 mock_post.return_value = _mk_resp(requests.codes.internal_server_error)
237 assert obj.notify(body="Test body") is False
238
239 mock_post.reset_mock()
240
241 # An unknown response code returns False
242 mock_post.return_value = _mk_resp(999)
243 assert obj.notify(body="Test body") is False
244
245 mock_post.reset_mock()
246
247 # A RequestException returns False
248 mock_post.side_effect = requests.RequestException("Network error")
249 assert obj.notify(body="Test body") is False
250
251
252 @mock.patch("requests.post")
253 def test_plugin_chime_url_roundtrip(mock_post):
254 """NotifyChime() URL round-trip invariant."""
255
256 # Prepare our mock response
257 mock_post.return_value = requests.Request()
258 mock_post.return_value.status_code = requests.codes.ok
259
260 # Build a simple token that contains base64 padding (=)
261 token_with_padding = "AaBbCcDd1234=="
262
263 obj = NotifyChime(
264 webhook_id=TEST_WEBHOOK_ID,
265 token=token_with_padding,
266 )
267 assert isinstance(obj, NotifyChime)
268
269 # Generate a URL and parse it back
270 generated_url = obj.url()
271 results = NotifyChime.parse_url(generated_url)
272 assert results is not None
273
274 # Reconstruct from parsed results
275 obj2 = NotifyChime(**results)
276 assert isinstance(obj2, NotifyChime)
277
278 # The connection identity must be identical
279 assert obj.url_identifier == obj2.url_identifier
280
281 # Token must survive the round-trip (including = padding)
282 assert obj.token == obj2.token
283 assert obj.webhook_id == obj2.webhook_id
284
285
286 @mock.patch("requests.post")
287 def test_plugin_chime_url_parsing(mock_post):
288 """NotifyChime() URL Parsing Checks."""
289
290 # Prepare our mock response
291 mock_post.return_value = requests.Request()
292 mock_post.return_value.status_code = requests.codes.ok
293
294 # Parse a standard Apprise URL
295 results = NotifyChime.parse_url(
296 "chime://{}/{}".format(TEST_WEBHOOK_ID, TEST_TOKEN)
297 )
298 assert results is not None
299 assert results["webhook_id"] == TEST_WEBHOOK_ID
300 assert results["token"] == TEST_TOKEN
301
302 # ?token= query parameter overrides path-supplied token
303 results = NotifyChime.parse_url(
304 "chime://{}/ignored-token?token={}".format(TEST_WEBHOOK_ID, TEST_TOKEN)
305 )
306 assert results is not None
307 assert results["token"] == TEST_TOKEN
308
309 # ?webhook_id= query parameter overrides host-supplied ID
310 results = NotifyChime.parse_url(
311 "chime://ignored-id/{}?webhook_id={}".format(
312 TEST_TOKEN, TEST_WEBHOOK_ID
313 )
314 )
315 assert results is not None
316 assert results["webhook_id"] == TEST_WEBHOOK_ID
317
318 # None is returned for an invalid URL
319 assert NotifyChime.parse_url(None) is None
320
321 # Missing token returns a result dict with no token
322 results = NotifyChime.parse_url("chime://{}".format(TEST_WEBHOOK_ID))
323 # split_path on an empty fullpath returns no entries
324 assert results is not None
325 assert not results.get("token")
326
327
328 @mock.patch("requests.post")
329 def test_plugin_chime_native_url(mock_post):
330 """NotifyChime() Native URL Parsing."""
331
332 # Prepare our mock response
333 mock_post.return_value = requests.Request()
334 mock_post.return_value.status_code = requests.codes.ok
335
336 # A native URL with a URL-encoded token
337 native_url = (
338 "https://hooks.chime.aws/incomingwebhooks/"
339 "{webhook_id}?token={token}".format(
340 webhook_id=TEST_WEBHOOK_ID,
341 # URL-encode the token as it would appear in a real Chime URL
342 token=NotifyChime.quote(TEST_TOKEN, safe=""),
343 )
344 )
345
346 results = NotifyChime.parse_native_url(native_url)
347 assert results is not None
348 assert results["webhook_id"] == TEST_WEBHOOK_ID
349 assert results["token"] == TEST_TOKEN
350
351 # The constructed object must be functional
352 obj = NotifyChime(**results)
353 assert isinstance(obj, NotifyChime)
354 assert obj.notify(body="Native URL test") is True
355
356 # A non-matching URL returns None
357 assert (
358 NotifyChime.parse_native_url("https://example.com/not-a-chime-url")
359 is None
360 )
361
362
363 @mock.patch("requests.post")
364 def test_plugin_chime_privacy_url(mock_post):
365 """NotifyChime() Privacy URL."""
366
367 # Prepare our mock response
368 mock_post.return_value = requests.Request()
369 mock_post.return_value.status_code = requests.codes.ok
370
371 obj = NotifyChime(webhook_id=TEST_WEBHOOK_ID, token=TEST_TOKEN)
372 assert isinstance(obj, NotifyChime)
373
374 # Privacy URL must mask credentials
375 privacy = obj.url(privacy=True)
376 assert TEST_TOKEN not in privacy
377 assert TEST_WEBHOOK_ID not in privacy
378 # Scheme must still be present
379 assert privacy.startswith("chime://")
380
381
382 @mock.patch("requests.post")
383 def test_plugin_chime_apprise_integration(mock_post):
384 """NotifyChime() Apprise integration."""
385
386 # Prepare a valid mock response
387 mock_post.return_value = requests.Request()
388 mock_post.return_value.status_code = requests.codes.ok
389
390 # Test loading via Apprise URL
391 a = Apprise()
392 url = "chime://{}/{}".format(TEST_WEBHOOK_ID, TEST_TOKEN)
393 assert a.add(url) is True
394 assert len(a) == 1
395 assert isinstance(a[0], NotifyChime)
396
397 # Notify succeeds
398 assert a.notify(body="Test", title="Title") is True
399 assert mock_post.call_count == 1
400
401 mock_post.reset_mock()
402
403 # Test failure response
404 mock_post.return_value.status_code = requests.codes.internal_server_error
405 assert a.notify(body="Test", title="Title") is False
406
407 mock_post.reset_mock()
408
409 # Test with native URL
410 a2 = Apprise()
411 native = (
412 "https://hooks.chime.aws/incomingwebhooks/"
413 "{webhook_id}?token={token}".format(
414 webhook_id=TEST_WEBHOOK_ID,
415 token=NotifyChime.quote(TEST_TOKEN, safe=""),
416 )
417 )
418 assert a2.add(native) is True
419 assert len(a2) == 1
420 assert isinstance(a2[0], NotifyChime)
421
422 mock_post.return_value.status_code = requests.codes.ok
423 assert a2.notify(body="Native test", title="Title") is True
424
425
426 @mock.patch("requests.post")
427 def test_plugin_chime_url_identifier(mock_post):
428 """NotifyChime() url_identifier uniqueness."""
429
430 # Two objects with the same credentials share an identifier
431 obj1 = NotifyChime(webhook_id=TEST_WEBHOOK_ID, token=TEST_TOKEN)
432 obj2 = NotifyChime(webhook_id=TEST_WEBHOOK_ID, token=TEST_TOKEN)
433 assert obj1.url_identifier == obj2.url_identifier
434
435 # Different webhook_id produces a different identifier
436 obj3 = NotifyChime(webhook_id="different-id-abcd", token=TEST_TOKEN)
437 assert obj1.url_identifier != obj3.url_identifier
438
439 # Different token produces a different identifier
440 obj4 = NotifyChime(webhook_id=TEST_WEBHOOK_ID, token="DifferentToken123")
441 assert obj1.url_identifier != obj4.url_identifier
442
443 # Targets must not affect the identifier (no targets for Chime)
444 assert obj1.url_identifier[0] == NotifyChime.secure_protocol
445 assert obj1.url_identifier[1] == TEST_WEBHOOK_ID
446 assert obj1.url_identifier[2] == TEST_TOKEN
447
448
449 @mock.patch("requests.post")
450 def test_plugin_chime_html_to_markdown_format(mock_post):
451 """NotifyChime(): HTML body is converted to Markdown."""
452
453 # Prepare Mock
454 mock_post.return_value = requests.Request()
455 mock_post.return_value.status_code = requests.codes.ok
456
457 # Chime's notify_format is MARKDOWN by default
458 aobj = Apprise()
459 assert aobj.add("chime://{}/{}".format(TEST_WEBHOOK_ID, TEST_TOKEN))
460
461 # Notify with an HTML body; the framework should convert it
462 # to Markdown before dispatching to Chime
463 assert (
464 aobj.notify(
465 body="<b>hello</b> <i>world</i>",
466 body_format=NotifyFormat.HTML,
467 )
468 is True
469 )
470 assert mock_post.call_count == 1
471
472 # The body must arrive as Markdown, not as stripped plain text
473 payload = loads(mock_post.call_args_list[0][1]["data"])
474 assert payload["Content"] == "**hello** *world*"