Debian Codegraph @

tests/test_plugin_twist.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 json import dumps
29
30 # Disable logging for a cleaner testing output
31 import logging
32 from unittest import mock
33
34 from helpers import AppriseURLTester
35 import pytest
36 import requests
37
38 from apprise import Apprise, NotifyFormat
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.twist import NotifyTwist
41
42 logging.disable(logging.CRITICAL)
43
44 # Our Testing URLs
45 apprise_url_tests = (
46 (
47 "twist://",
48 {
49 # Missing Email and Login
50 "instance": None,
51 },
52 ),
53 (
54 "twist://:@/",
55 {
56 "instance": None,
57 },
58 ),
59 (
60 "twist://[email protected]/",
61 {
62 # No password
63 "instance": None,
64 },
65 ),
66 (
67 "twist://[email protected]/password",
68 {
69 # Password acceptable as first entry in path
70 "instance": NotifyTwist,
71 # Expected notify() response is False because internally we would
72 # have failed to login
73 "notify_response": False,
74 },
75 ),
76 (
77 "twist://password:[email protected]",
78 {
79 # password:login acceptable
80 "instance": NotifyTwist,
81 # Expected notify() response is False because internally we would
82 # have failed to login
83 "notify_response": False,
84 # Our expected url(privacy=True) startswith() response:
85 "privacy_url": "twist://****:[email protected]",
86 },
87 ),
88 (
89 "twist://password:[email protected]",
90 {
91 # password:login acceptable
92 "instance": NotifyTwist,
93 # Expected notify() response is False because internally we would
94 # have logged in, but we would have failed to look up the #General
95 # channel and workspace.
96 "requests_response_text": {
97 # Login expected response
98 "id": 1234,
99 "default_workspace": 9876,
100 },
101 "notify_response": False,
102 },
103 ),
104 (
105 "twist://password:[email protected]",
106 {
107 "instance": NotifyTwist,
108 # throw a bizarre code forcing us to fail to look it up
109 "response": False,
110 "requests_response_code": 999,
111 },
112 ),
113 (
114 "twist://password:[email protected]",
115 {
116 "instance": NotifyTwist,
117 # Throws a series of i/o exceptions with this flag
118 # is set and tests that we gracefully handle them
119 "test_requests_exceptions": True,
120 },
121 ),
122 )
123
124
125 def test_plugin_twist_urls():
126 """NotifyTwist() Apprise URLs."""
127
128 # Run our general tests
129 AppriseURLTester(tests=apprise_url_tests).run_all()
130
131
132 def test_plugin_twist_init():
133 """NotifyTwist() init()"""
134 with pytest.raises(AppriseImproperlyConfigured):
135 NotifyTwist(email="invalid", targets=None)
136
137 with pytest.raises(AppriseImproperlyConfigured):
138 NotifyTwist(email="user@domain", targets=None)
139
140 # Simple object initialization
141 result = NotifyTwist(
142 password="abc123", email="[email protected]", targets=None
143 )
144 assert result.user == "user"
145 assert result.host == "domain.com"
146 assert result.password == "abc123"
147
148 # Channel Instantiation by name
149 obj = Apprise.instantiate("twist://password:[email protected]/#Channel")
150 assert isinstance(obj, NotifyTwist)
151
152 # Channel Instantiation by id (faster if you know the translation)
153 obj = Apprise.instantiate("twist://password:[email protected]/12345")
154 assert isinstance(obj, NotifyTwist)
155
156 # Invalid Channel - (max characters is 64), the below drops it
157 obj = Apprise.instantiate(
158 "twist://password:[email protected]/{}".format("a" * 65)
159 )
160 assert isinstance(obj, NotifyTwist)
161
162 # No User detect
163 result = NotifyTwist.parse_url("twist://example.com")
164 assert result is None
165
166 # test usage of to=
167 result = NotifyTwist.parse_url(
168 "twist://password:[email protected]?to=#channel"
169 )
170 assert isinstance(result, dict)
171 assert "user" in result
172 assert result["user"] == "user"
173 assert "host" in result
174 assert result["host"] == "example.com"
175 assert "password" in result
176 assert result["password"] == "password"
177 assert "targets" in result
178 assert isinstance(result["targets"], list) is True
179 assert len(result["targets"]) == 1
180 assert "#channel" in result["targets"]
181
182
183 @mock.patch("requests.get")
184 @mock.patch("requests.post")
185 def test_plugin_twist_auth(mock_post, mock_get):
186 """NotifyTwist() login/logout()"""
187
188 # Prepare Mock
189 mock_get.return_value = requests.Request()
190 mock_post.return_value = requests.Request()
191 mock_post.return_value.status_code = requests.codes.ok
192 mock_get.return_value.status_code = requests.codes.ok
193 mock_post.return_value.content = dumps(
194 {
195 "token": "2e82c1e4e8b0091fdaa34ff3972351821406f796",
196 "default_workspace": 12345,
197 }
198 )
199 mock_get.return_value.content = mock_post.return_value.content
200
201 # Instantiate an object
202 obj = Apprise.instantiate("twist://password:[email protected]/#Channel")
203 assert isinstance(obj, NotifyTwist)
204 # not logged in yet
205 obj.logout()
206 assert obj.login() is True
207
208 # Clear our channel listing
209 obj.channels.clear()
210 # No channels mean there is no internal migration/lookups required
211 assert obj._channel_migration() is True
212
213 # Workspace Success
214 mock_post.return_value.content = dumps(
215 [
216 {
217 "name": "TesT",
218 "id": 1,
219 },
220 {
221 "name": "tESt2",
222 "id": 2,
223 },
224 ]
225 )
226 mock_get.return_value.content = mock_post.return_value.content
227
228 results = obj.get_workspaces()
229 assert len(results) == 2
230 assert "test" in results
231 assert results["test"] == 1
232 assert "test2" in results
233 assert results["test2"] == 2
234
235 mock_post.return_value.content = dumps(
236 [
237 {
238 "name": "ChaNNEL1",
239 "id": 1,
240 },
241 {
242 "name": "chaNNel2",
243 "id": 2,
244 },
245 ]
246 )
247 mock_get.return_value.content = mock_post.return_value.content
248 results = obj.get_channels(wid=1)
249 assert len(results) == 2
250 assert "channel1" in results
251 assert results["channel1"] == 1
252 assert "channel2" in results
253 assert results["channel2"] == 2
254
255 # Test result failure response
256 mock_post.return_value.status_code = 403
257 mock_get.return_value.status_code = 403
258 assert obj.get_workspaces() == {}
259
260 # Return things how they were
261 mock_post.return_value.status_code = requests.codes.ok
262 mock_get.return_value.status_code = requests.codes.ok
263
264 # Forces call to logout:
265 del obj
266
267 #
268 # Authentication failures
269 #
270 mock_post.return_value.status_code = 403
271 mock_get.return_value.status_code = 403
272
273 # Instantiate an object
274 obj = Apprise.instantiate("twist://password:[email protected]/#Channel")
275 assert isinstance(obj, NotifyTwist)
276
277 # Authentication failed
278 assert obj.get_workspaces() == {}
279 assert obj.get_channels(wid=1) == {}
280 assert obj._channel_migration() is False
281 assert obj.send("body", "title") is False
282
283 obj = Apprise.instantiate("twist://password:[email protected]/#Channel")
284 assert isinstance(obj, NotifyTwist)
285
286 # Calling logout on an object already logged out
287 obj.logout()
288
289
290 @mock.patch("requests.get")
291 @mock.patch("requests.post")
292 def test_plugin_twist_cache(mock_post, mock_get):
293 """NotifyTwist() Cache Handling."""
294
295 def _response(url, *args, **kwargs):
296
297 # Default configuration
298 request = mock.Mock()
299 request.status_code = requests.codes.ok
300 request.content = "{}"
301
302 if url.endswith("/login"):
303 # Simulate a successful login
304 request.content = dumps(
305 {
306 "token": "2e82c1e4e8b0091fdaa34ff3972351821406f796",
307 "default_workspace": 1,
308 }
309 )
310
311 elif url.endswith("workspaces/get"):
312 request.content = dumps(
313 [
314 {
315 "name": "TeamA",
316 "id": 1,
317 },
318 {
319 "name": "TeamB",
320 "id": 2,
321 },
322 ]
323 )
324
325 elif url.endswith("channels/get"):
326 request.content = dumps(
327 [
328 {
329 "name": "ChanA",
330 "id": 1,
331 },
332 {
333 "name": "ChanB",
334 "id": 2,
335 },
336 ]
337 )
338
339 return request
340
341 mock_get.side_effect = _response
342 mock_post.side_effect = _response
343
344 # Instantiate an object
345 obj = Apprise.instantiate(
346 "twist://password:[email protected]/"
347 "#ChanB/1:1/TeamA:ChanA/Ignore:Chan/3:1"
348 )
349 assert isinstance(obj, NotifyTwist)
350
351 # Will detect channels except Ignore:Chan
352 assert obj._channel_migration() is False
353
354 # Add another channel
355 obj.channels.add("ChanB")
356 assert obj._channel_migration() is True
357
358 # Nothing more to detect the second time around
359 assert obj._channel_migration() is True
360
361 # Send a notification
362 assert obj.send("body", "title") is True
363
364 def _can_not_send_response(url, *args, **kwargs):
365 """Simulate a case where we can't send a notification."""
366 # Force a failure
367 request = mock.Mock()
368 request.status_code = 403
369 request.content = "{}"
370 return request
371
372 mock_get.side_effect = _can_not_send_response
373 mock_post.side_effect = _can_not_send_response
374
375 # Send a notification and fail at it
376 assert obj.send("body", "title") is False
377
378
379 @mock.patch("requests.get")
380 @mock.patch("requests.post")
381 def test_plugin_twist_fetch(mock_post, mock_get):
382 """NotifyTwist() fetch()
383
384 fetch() is a wrapper that handles all kinds of edge cases and even attempts
385 to re-authenticate to the Twist server if our token happens to expire.
386 This tests these edge cases
387 """
388
389 # Track our iteration; by tracing within an object, we can re-reference
390 # it within a function scope.
391 cache = {
392 "first_time": True,
393 }
394
395 def _reauth_response(url, *args, **kwargs):
396 """Tests re-authentication process and then a successful retry."""
397
398 # Default configuration
399 request = mock.Mock()
400 request.status_code = requests.codes.ok
401
402 # Simulate a successful login
403 request.content = dumps(
404 {
405 "token": "2e82c1e4e8b0091fdaa34ff3972351821406f796",
406 "default_workspace": 12345,
407 }
408 )
409
410 if url.endswith("threads/add") and cache["first_time"] is True:
411 # First time iteration; act as if we failed; our second iteration
412 # will not enter this and be successful. This is done by simply
413 # toggling the first_time flag:
414 cache["first_time"] = False
415
416 # otherwise, we set our first-time failure settings
417 request.status_code = 403
418 request.content = dumps(
419 {
420 "error_code": 200,
421 "error_string": "Invalid token",
422 }
423 )
424
425 return request
426
427 mock_get.side_effect = _reauth_response
428 mock_post.side_effect = _reauth_response
429
430 # Instantiate an object
431 obj = Apprise.instantiate("twist://password:[email protected]/#Channel/34")
432 assert isinstance(obj, NotifyTwist)
433
434 # Simulate a re-authentication
435 postokay, response = obj._fetch("threads/add")
436
437 ##########################################################################
438 cache = {
439 "first_time": True,
440 }
441
442 def _reauth_exception_response(url, *args, **kwargs):
443 """Tests exception thrown after re-authentication process."""
444
445 # Default configuration
446 request = mock.Mock()
447 request.status_code = requests.codes.ok
448
449 # Simulate a successful login
450 request.content = dumps(
451 {
452 "token": "2e82c1e4e8b0091fdaa34ff3972351821406f796",
453 "default_workspace": 12345,
454 }
455 )
456
457 if url.endswith("threads/add") and cache["first_time"] is True:
458 # First time iteration; act as if we failed; our second iteration
459 # will not enter this and be successful. This is done by simply
460 # toggling the first_time flag:
461 cache["first_time"] = False
462
463 # otherwise, we set our first-time failure settings
464 request.status_code = 403
465 request.content = dumps(
466 {
467 "error_code": 200,
468 "error_string": "Invalid token",
469 }
470 )
471
472 elif url.endswith("threads/add") and cache["first_time"] is False:
473 # unparseable response throws the exception
474 request.status_code = 200
475 request.content = "{"
476
477 return request
478
479 mock_get.side_effect = _reauth_exception_response
480 mock_post.side_effect = _reauth_exception_response
481
482 # Instantiate an object
483 obj = Apprise.instantiate("twist://password:[email protected]/#Channel/34")
484 assert isinstance(obj, NotifyTwist)
485
486 # Simulate a re-authentication
487 postokay, response = obj._fetch("threads/add")
488
489 ##########################################################################
490 cache = {
491 "first_time": True,
492 }
493
494 def _reauth_failed_response(url, *args, **kwargs):
495 """Tests re-authentication process and have it not succeed."""
496
497 # Default configuration
498 request = mock.Mock()
499 request.status_code = requests.codes.ok
500
501 # Simulate a successful login
502 request.content = dumps(
503 {
504 "token": "2e82c1e4e8b0091fdaa34ff3972351821406f796",
505 "default_workspace": 12345,
506 }
507 )
508
509 if url.endswith("threads/add") and cache["first_time"] is True:
510 # First time iteration; act as if we failed; our second iteration
511 # will not enter this and be successful. This is done by simply
512 # toggling the first_time flag:
513 cache["first_time"] = False
514
515 # otherwise, we set our first-time failure settings
516 request.status_code = 403
517 request.content = dumps(
518 {
519 "error_code": 200,
520 "error_string": "Invalid token",
521 }
522 )
523
524 elif url.endswith("/login") and cache["first_time"] is False:
525 # Fail to login
526 request.status_code = 403
527 request.content = "{}"
528
529 return request
530
531 mock_get.side_effect = _reauth_failed_response
532 mock_post.side_effect = _reauth_failed_response
533
534 # Instantiate an object
535 obj = Apprise.instantiate("twist://password:[email protected]/#Channel/34")
536 assert isinstance(obj, NotifyTwist)
537
538 # Simulate a re-authentication
539 postokay, response = obj._fetch("threads/add")
540
541 def _unparseable_json_response(url, *args, **kwargs):
542
543 # Default configuration
544 request = mock.Mock()
545 request.status_code = requests.codes.ok
546 request.content = "{"
547 return request
548
549 mock_get.side_effect = _unparseable_json_response
550 mock_post.side_effect = _unparseable_json_response
551
552 # Instantiate our object
553 obj = Apprise.instantiate("twist://password:[email protected]/#Channel/34")
554 assert isinstance(obj, NotifyTwist)
555
556 # Simulate a re-authentication
557 postokay, response = obj._fetch("threads/add")
558 assert postokay is True
559 # When we can't parse the content, we still default to an empty
560 # dictionary
561 assert response == {}
562
563
564 @mock.patch("requests.get")
565 @mock.patch("requests.post")
566 def test_plugin_twist_html_to_markdown_format(mock_post, mock_get):
567 """NotifyTwist(): HTML body is converted to Markdown."""
568
569 def _response(url, *args, **kwargs):
570 # Default configuration
571 request = mock.Mock()
572 request.status_code = requests.codes.ok
573
574 if url.endswith("/login"):
575 # Simulate a successful login
576 request.content = dumps(
577 {
578 "token": "2e82c1e4e8b0091fdaa34ff3972351821406f796",
579 "default_workspace": 1,
580 }
581 )
582
583 else:
584 # All other endpoints return an empty JSON object
585 request.content = "{}"
586
587 return request
588
589 mock_get.side_effect = _response
590 mock_post.side_effect = _response
591
592 # Twist has class-level notify_format = MARKDOWN, so no ?format=
593 # is needed; incoming HTML bodies are converted before dispatch
594 aobj = Apprise()
595 assert aobj.add("twist://password:[email protected]/1:1")
596
597 # Notify with an HTML body; the framework converts it to Markdown
598 # before dispatching to the Twist plugin
599 assert (
600 bool(
601 aobj.notify(
602 body="<b>hello</b> <i>world</i>",
603 body_format=NotifyFormat.HTML,
604 )
605 )
606 is True
607 )
608
609 # Two POST calls are expected: login then threads/add
610 assert mock_post.call_count == 2
611
612 # The body must arrive as Markdown in the threads/add payload
613 data = mock_post.call_args_list[1][1]["data"]
614 assert data["content"] == "**hello** *world*"