File: test_plugin_twist.py

package info (click to toggle)
apprise 1.9.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,792 kB
  • sloc: python: 74,226; sh: 132; makefile: 6
file content (527 lines) | stat: -rw-r--r-- 16,632 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# -*- coding: utf-8 -*-
# BSD 2-Clause License
#
# Apprise - Push Notification Library.
# Copyright (c) 2025, Chris Caron <lead2gold@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from unittest import mock

import pytest
import requests
from json import dumps
from apprise import Apprise
from apprise.plugins.twist import NotifyTwist
from helpers import AppriseURLTester

# Disable logging for a cleaner testing output
import logging
logging.disable(logging.CRITICAL)

# Our Testing URLs
apprise_url_tests = (
    ('twist://', {
        # Missing Email and Login
        'instance': None,
    }),
    ('twist://:@/', {
        'instance': None,
    }),
    ('twist://user@example.com/', {
        # No password
        'instance': None,
    }),
    ('twist://user@example.com/password', {
        # Password acceptable as first entry in path
        'instance': NotifyTwist,
        # Expected notify() response is False because internally we would
        # have failed to login
        'notify_response': False,
    }),
    ('twist://password:user1@example.com', {
        # password:login acceptable
        'instance': NotifyTwist,
        # Expected notify() response is False because internally we would
        # have failed to login
        'notify_response': False,

        # Our expected url(privacy=True) startswith() response:
        'privacy_url': 'twist://****:user1@example.com',
    }),
    ('twist://password:user2@example.com', {
        # password:login acceptable
        'instance': NotifyTwist,
        # Expected notify() response is False because internally we would
        # have logged in, but we would have failed to look up the #General
        # channel and workspace.
        'requests_response_text': {
            # Login expected response
            'id': 1234,
            'default_workspace': 9876,
        },
        'notify_response': False,
    }),
    ('twist://password:user2@example.com', {
        'instance': NotifyTwist,
        # throw a bizzare code forcing us to fail to look it up
        'response': False,
        'requests_response_code': 999,
    }),
    ('twist://password:user2@example.com', {
        'instance': NotifyTwist,
        # Throws a series of connection and transfer exceptions when this flag
        # is set and tests that we gracfully handle them
        'test_requests_exceptions': True,
    }),
)


def test_plugin_twist_urls():
    """
    NotifyTwist() Apprise URLs

    """

    # Run our general tests
    AppriseURLTester(tests=apprise_url_tests).run_all()


def test_plugin_twist_init():
    """
    NotifyTwist() init()

    """
    with pytest.raises(TypeError):
        NotifyTwist(email='invalid', targets=None)

    with pytest.raises(TypeError):
        NotifyTwist(email='user@domain', targets=None)

    # Simple object initialization
    result = NotifyTwist(
        password='abc123', email='user@domain.com', targets=None)
    assert result.user == 'user'
    assert result.host == 'domain.com'
    assert result.password == 'abc123'

    # Channel Instantiation by name
    obj = Apprise.instantiate('twist://password:user@example.com/#Channel')
    assert isinstance(obj, NotifyTwist)

    # Channel Instantiation by id (faster if you know the translation)
    obj = Apprise.instantiate('twist://password:user@example.com/12345')
    assert isinstance(obj, NotifyTwist)

    # Invalid Channel - (max characters is 64), the below drops it
    obj = Apprise.instantiate(
        'twist://password:user@example.com/{}'.format('a' * 65))
    assert isinstance(obj, NotifyTwist)

    # No User detect
    result = NotifyTwist.parse_url('twist://example.com')
    assert result is None

    # test usage of to=
    result = NotifyTwist.parse_url(
        'twist://password:user@example.com?to=#channel')
    assert isinstance(result, dict)
    assert 'user' in result
    assert result['user'] == 'user'
    assert 'host' in result
    assert result['host'] == 'example.com'
    assert 'password' in result
    assert result['password'] == 'password'
    assert 'targets' in result
    assert isinstance(result['targets'], list) is True
    assert len(result['targets']) == 1
    assert '#channel' in result['targets']


@mock.patch('requests.get')
@mock.patch('requests.post')
def test_plugin_twist_auth(mock_post, mock_get):
    """
    NotifyTwist() login/logout()

    """

    # Prepare Mock
    mock_get.return_value = requests.Request()
    mock_post.return_value = requests.Request()
    mock_post.return_value.status_code = requests.codes.ok
    mock_get.return_value.status_code = requests.codes.ok
    mock_post.return_value.content = dumps({
        'token': '2e82c1e4e8b0091fdaa34ff3972351821406f796',
        'default_workspace': 12345,
    })
    mock_get.return_value.content = mock_post.return_value.content

    # Instantiate an object
    obj = Apprise.instantiate('twist://password:user@example.com/#Channel')
    assert isinstance(obj, NotifyTwist)
    # not logged in yet
    obj.logout()
    assert obj.login() is True

    # Clear our channel listing
    obj.channels.clear()
    # No channels mean there is no internal migration/lookups required
    assert obj._channel_migration() is True

    # Workspace Success
    mock_post.return_value.content = dumps([
        {
            'name': 'TesT',
            'id': 1,
        }, {
            'name': 'tESt2',
            'id': 2,
        },
    ])
    mock_get.return_value.content = mock_post.return_value.content

    results = obj.get_workspaces()
    assert len(results) == 2
    assert 'test' in results
    assert results['test'] == 1
    assert 'test2' in results
    assert results['test2'] == 2

    mock_post.return_value.content = dumps([
        {
            'name': 'ChaNNEL1',
            'id': 1,
        }, {
            'name': 'chaNNel2',
            'id': 2,
        },
    ])
    mock_get.return_value.content = mock_post.return_value.content
    results = obj.get_channels(wid=1)
    assert len(results) == 2
    assert 'channel1' in results
    assert results['channel1'] == 1
    assert 'channel2' in results
    assert results['channel2'] == 2

    # Test result failure response
    mock_post.return_value.status_code = 403
    mock_get.return_value.status_code = 403
    assert obj.get_workspaces() == dict()

    # Return things how they were
    mock_post.return_value.status_code = requests.codes.ok
    mock_get.return_value.status_code = requests.codes.ok

    # Forces call to logout:
    del obj

    #
    # Authentication failures
    #
    mock_post.return_value.status_code = 403
    mock_get.return_value.status_code = 403

    # Instantiate an object
    obj = Apprise.instantiate('twist://password:user@example.com/#Channel')
    assert isinstance(obj, NotifyTwist)

    # Authentication failed
    assert obj.get_workspaces() == dict()
    assert obj.get_channels(wid=1) == dict()
    assert obj._channel_migration() is False
    assert obj.send('body', 'title') is False

    obj = Apprise.instantiate('twist://password:user@example.com/#Channel')
    assert isinstance(obj, NotifyTwist)

    # Calling logout on an object already logged out
    obj.logout()


@mock.patch('requests.get')
@mock.patch('requests.post')
def test_plugin_twist_cache(mock_post, mock_get):
    """
    NotifyTwist() Cache Handling

    """

    def _response(url, *args, **kwargs):

        # Default configuration
        request = mock.Mock()
        request.status_code = requests.codes.ok
        request.content = '{}'

        if url.endswith('/login'):
            # Simulate a successful login
            request.content = dumps({
                'token': '2e82c1e4e8b0091fdaa34ff3972351821406f796',
                'default_workspace': 1,
            })

        elif url.endswith('workspaces/get'):
            request.content = dumps([
                {
                    'name': 'TeamA',
                    'id': 1,
                }, {
                    'name': 'TeamB',
                    'id': 2,
                },
            ])

        elif url.endswith('channels/get'):
            request.content = dumps([
                {
                    'name': 'ChanA',
                    'id': 1,
                }, {
                    'name': 'ChanB',
                    'id': 2,
                },
            ])

        return request

    mock_get.side_effect = _response
    mock_post.side_effect = _response

    # Instantiate an object
    obj = Apprise.instantiate(
        'twist://password:user@example.com/'
        '#ChanB/1:1/TeamA:ChanA/Ignore:Chan/3:1')
    assert isinstance(obj, NotifyTwist)

    # Will detect channels except Ignore:Chan
    assert obj._channel_migration() is False

    # Add another channel
    obj.channels.add('ChanB')
    assert obj._channel_migration() is True

    # Nothing more to detect the second time around
    assert obj._channel_migration() is True

    # Send a notification
    assert obj.send('body', 'title') is True

    def _can_not_send_response(url, *args, **kwargs):
        """
        Simulate a case where we can't send a notification
        """
        # Force a failure
        request = mock.Mock()
        request.status_code = 403
        request.content = '{}'
        return request

    mock_get.side_effect = _can_not_send_response
    mock_post.side_effect = _can_not_send_response

    # Send a notification and fail at it
    assert obj.send('body', 'title') is False


@mock.patch('requests.get')
@mock.patch('requests.post')
def test_plugin_twist_fetch(mock_post, mock_get):
    """
    NotifyTwist() fetch()

    fetch() is a wrapper that handles all kinds of edge cases and even
    attempts to re-authenticate to the Twist server if our token
    happens to expire.  This tests these edge cases

    """

    # Track our iteration; by tracing within an object, we can re-reference
    # it within a function scope.
    _cache = {
        'first_time': True,
    }

    def _reauth_response(url, *args, **kwargs):
        """
        Tests re-authentication process and then a successful
        retry
        """

        # Default configuration
        request = mock.Mock()
        request.status_code = requests.codes.ok

        # Simulate a successful login
        request.content = dumps({
            'token': '2e82c1e4e8b0091fdaa34ff3972351821406f796',
            'default_workspace': 12345,
        })

        if url.endswith('threads/add') and _cache['first_time'] is True:
            # First time iteration; act as if we failed; our second iteration
            # will not enter this and be successful. This is done by simply
            # toggling the first_time flag:
            _cache['first_time'] = False

            # otherwise, we set our first-time failure settings
            request.status_code = 403
            request.content = dumps({
                'error_code': 200,
                'error_string': 'Invalid token',
            })

        return request

    mock_get.side_effect = _reauth_response
    mock_post.side_effect = _reauth_response

    # Instantiate an object
    obj = Apprise.instantiate('twist://password:user@example.com/#Channel/34')
    assert isinstance(obj, NotifyTwist)

    # Simulate a re-authentication
    postokay, response = obj._fetch('threads/add')

    ##########################################################################
    _cache = {
        'first_time': True,
    }

    def _reauth_exception_response(url, *args, **kwargs):
        """
        Tests exception thrown after re-authentication process
        """

        # Default configuration
        request = mock.Mock()
        request.status_code = requests.codes.ok

        # Simulate a successful login
        request.content = dumps({
            'token': '2e82c1e4e8b0091fdaa34ff3972351821406f796',
            'default_workspace': 12345,
        })

        if url.endswith('threads/add') and _cache['first_time'] is True:
            # First time iteration; act as if we failed; our second iteration
            # will not enter this and be successful. This is done by simply
            # toggling the first_time flag:
            _cache['first_time'] = False

            # otherwise, we set our first-time failure settings
            request.status_code = 403
            request.content = dumps({
                'error_code': 200,
                'error_string': 'Invalid token',
            })

        elif url.endswith('threads/add') and _cache['first_time'] is False:
            # unparseable response throws the exception
            request.status_code = 200
            request.content = '{'

        return request

    mock_get.side_effect = _reauth_exception_response
    mock_post.side_effect = _reauth_exception_response

    # Instantiate an object
    obj = Apprise.instantiate('twist://password:user@example.com/#Channel/34')
    assert isinstance(obj, NotifyTwist)

    # Simulate a re-authentication
    postokay, response = obj._fetch('threads/add')

    ##########################################################################
    _cache = {
        'first_time': True,
    }

    def _reauth_failed_response(url, *args, **kwargs):
        """
        Tests re-authentication process and have it not succeed
        """

        # Default configuration
        request = mock.Mock()
        request.status_code = requests.codes.ok

        # Simulate a successful login
        request.content = dumps({
            'token': '2e82c1e4e8b0091fdaa34ff3972351821406f796',
            'default_workspace': 12345,
        })

        if url.endswith('threads/add') and _cache['first_time'] is True:
            # First time iteration; act as if we failed; our second iteration
            # will not enter this and be successful. This is done by simply
            # toggling the first_time flag:
            _cache['first_time'] = False

            # otherwise, we set our first-time failure settings
            request.status_code = 403
            request.content = dumps({
                'error_code': 200,
                'error_string': 'Invalid token',
            })

        elif url.endswith('/login') and _cache['first_time'] is False:
            # Fail to login
            request.status_code = 403
            request.content = '{}'

        return request

    mock_get.side_effect = _reauth_failed_response
    mock_post.side_effect = _reauth_failed_response

    # Instantiate an object
    obj = Apprise.instantiate('twist://password:user@example.com/#Channel/34')
    assert isinstance(obj, NotifyTwist)

    # Simulate a re-authentication
    postokay, response = obj._fetch('threads/add')

    def _unparseable_json_response(url, *args, **kwargs):

        # Default configuration
        request = mock.Mock()
        request.status_code = requests.codes.ok
        request.content = '{'
        return request

    mock_get.side_effect = _unparseable_json_response
    mock_post.side_effect = _unparseable_json_response

    # Instantiate our object
    obj = Apprise.instantiate('twist://password:user@example.com/#Channel/34')
    assert isinstance(obj, NotifyTwist)

    # Simulate a re-authentication
    postokay, response = obj._fetch('threads/add')
    assert postokay is True
    # When we can't parse the content, we still default to an empty
    # dictionary
    assert response == {}