Debian Codegraph @

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