File: test_notification_manager.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 (401 lines) | stat: -rw-r--r-- 12,411 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
# -*- 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.

import re
import pytest
import types
import threading
from inspect import cleandoc

from apprise import Apprise
from apprise import NotificationManager
from apprise.plugins import NotifyBase

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

# Grant access to our Notification Manager Singleton
N_MGR = NotificationManager()


def test_notification_manager_general():
    """
    N_MGR: Notification Manager General testing

    """
    # Clear our set so we can test init calls
    N_MGR.unload_modules()
    assert isinstance(N_MGR.schemas(), list)
    assert len(N_MGR.schemas()) > 0
    N_MGR.unload_modules(disable_native=True)
    assert isinstance(N_MGR.schemas(), list)
    assert len(N_MGR.schemas()) == 0

    N_MGR.unload_modules()
    assert len(N_MGR) > 0

    N_MGR.unload_modules()
    iter(N_MGR)
    iter(N_MGR)

    N_MGR.unload_modules()
    assert bool(N_MGR) is False
    assert len([x for x in iter(N_MGR)]) > 0
    assert bool(N_MGR)

    N_MGR.unload_modules()
    assert isinstance(N_MGR.plugins(), types.GeneratorType)
    assert len([x for x in N_MGR.plugins()]) > 0
    N_MGR.unload_modules(disable_native=True)
    assert isinstance(N_MGR.plugins(), types.GeneratorType)
    assert len([x for x in N_MGR.plugins()]) == 0
    N_MGR.unload_modules()
    assert isinstance(N_MGR['json'](host='localhost'), NotifyBase)
    N_MGR.unload_modules()
    assert 'json' in N_MGR

    # Define our good:// url
    class DisabledNotification(NotifyBase):
        # Always disabled
        enabled = False

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

        def notify(self, *args, **kwargs):
            # Pretend everything is okay
            return True

        def url(self, **kwargs):
            # Support url() function
            return ''

    # Define our good:// url
    class GoodNotification(NotifyBase):

        secure_protocol = ('good', 'goods')

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

        def notify(self, *args, **kwargs):
            # Pretend everything is okay
            return True

        def url(self, **kwargs):
            # Support url() function
            return ''

    N_MGR.unload_modules()
    assert N_MGR.add(GoodNotification)
    assert 'good' in N_MGR
    assert 'goods' in N_MGR
    assert 'abcd' not in N_MGR
    assert 'xyz' not in N_MGR

    N_MGR.unload_modules()
    assert N_MGR.add(GoodNotification, 'abcd')
    assert 'good' in N_MGR
    assert 'goods' in N_MGR
    assert 'abcd' in N_MGR
    assert 'xyz' not in N_MGR

    N_MGR.unload_modules()
    assert N_MGR.add(GoodNotification, ['abcd', 'xYz'])
    assert 'good' in N_MGR
    assert 'goods' in N_MGR
    assert 'abcd' in N_MGR
    # Lower case
    assert 'xyz' in N_MGR

    N_MGR.unload_modules()
    # Not going to work; schemas must be a list of string
    assert N_MGR.add(GoodNotification, object) is False

    N_MGR.unload_modules()
    with pytest.raises(KeyError):
        del N_MGR['good']
    N_MGR['good'] = GoodNotification
    del N_MGR['good']

    N_MGR.unload_modules()
    N_MGR['good'] = GoodNotification
    assert N_MGR['good'].enabled is True
    N_MGR.enable_only('json', 'xml')
    assert N_MGR['good'].enabled is False
    assert N_MGR['json'].enabled is True
    assert N_MGR['jsons'].enabled is True
    assert N_MGR['xml'].enabled is True
    assert N_MGR['xmls'].enabled is True

    # Only two plugins are enabled
    assert len([p for p in N_MGR.plugins(include_disabled=False)]) == 2

    N_MGR.enable_only('good')
    assert N_MGR['good'].enabled is True
    assert N_MGR['json'].enabled is False
    assert N_MGR['jsons'].enabled is False
    assert N_MGR['xml'].enabled is False
    assert N_MGR['xmls'].enabled is False

    assert len([p for p in N_MGR.plugins(include_disabled=False)]) == 1

    N_MGR.unload_modules()
    N_MGR['disabled'] = DisabledNotification
    assert N_MGR['disabled'].enabled is False
    N_MGR.enable_only('disabled')
    # Can't enable items that aren't supposed to be:
    assert N_MGR['disabled'].enabled is False

    N_MGR['good'] = GoodNotification
    assert N_MGR['good'].enabled is True

    # You can't disable someething already disabled
    N_MGR.disable('disabled')
    assert N_MGR['disabled'].enabled is False

    N_MGR.unload_modules()
    N_MGR.enable_only('form', 'xml')
    for schema in N_MGR.schemas(include_disabled=False):
        assert re.match(r'^(form|xml)s?$', schema, re.IGNORECASE) is not None

    N_MGR.unload_modules()
    assert N_MGR['form'].enabled is True
    assert N_MGR['xml'].enabled is True
    assert N_MGR['json'].enabled is True
    N_MGR.enable_only('form', 'xml')
    assert N_MGR['form'].enabled is True
    assert N_MGR['xml'].enabled is True
    assert N_MGR['json'].enabled is False

    N_MGR.disable('invalid', 'xml')
    assert N_MGR['form'].enabled is True
    assert N_MGR['xml'].enabled is False
    assert N_MGR['json'].enabled is False

    # Detect that our json object is enabled
    with pytest.raises(KeyError):
        # The below can not be indexed
        N_MGR['invalid']

    N_MGR.unload_modules()
    N_MGR.disable('invalid', 'xml')

    N_MGR.unload_modules()
    assert N_MGR['json'].enabled is True

    # Work with an empty module tree
    N_MGR.unload_modules(disable_native=True)
    with pytest.raises(KeyError):
        # The below can not be indexed
        N_MGR['good']

    N_MGR.unload_modules()
    assert 'hello' not in N_MGR
    assert 'good' not in N_MGR
    assert 'goods' not in N_MGR

    N_MGR['hello'] = GoodNotification
    assert 'hello' in N_MGR
    assert 'good' in N_MGR
    assert 'goods' in N_MGR

    N_MGR.unload_modules()
    N_MGR['good'] = GoodNotification

    with pytest.raises(KeyError):
        # Can not assign the value again without getting a Conflict
        N_MGR['good'] = GoodNotification

    N_MGR.unload_modules()
    N_MGR.remove('good', 'invalid')
    assert 'good' not in N_MGR
    assert 'goods' not in N_MGR


def test_notification_manager_module_loading(tmpdir):
    """
    N_MGR: Notification Manager Module Loading

    """

    # Handle loading modules twice (they gracefully handle not loading more in
    # memory then needed)
    N_MGR.load_modules()
    N_MGR.load_modules()

    #
    # Thread Testing
    #

    # This tests against a racing condition when the modules have not been
    # loaded.  When multiple instances of Apprise are all instantiated,
    # the loading of the modules will occur for each instance if detected
    # having not been previously done, this tests that we can dynamically
    # support the loading of modules once whe multiple instances to apprise
    # are instantiated.
    thread_count = 10

    def thread_test(result, no):
        """
        Load our apprise object with valid URLs and store our result
        """
        apobj = Apprise()
        result[no] = apobj.add('json://localhost') and \
            apobj.add('form://localhost') and \
            apobj.add('xml://localhost')

    # Unload our modules
    N_MGR.unload_modules()

    # Prepare threads to load
    results = [None] * thread_count
    threads = [
        threading.Thread(target=thread_test, args=(results, no))
        for no in range(thread_count)
    ]

    # Verify we can safely load our modules in a thread safe environment
    for t in threads:
        t.start()

    for t in threads:
        t.join()

    # Verify we loaded our urls in all threads successfully
    for result in results:
        assert result is True


def test_notification_manager_decorators(tmpdir):
    """
    N_MGR: Notification Manager Decorator testing

    """

    # Prepare ourselves a file to work with
    notify_hook = tmpdir.mkdir('goodmodule').join('__init__.py')
    notify_hook.write(cleandoc("""
    from apprise.decorators import notify

    # We want to trigger on anyone who configures a call to clihook://
    @notify(on="clihooka")
    def mywrapper(body, title, notify_type, *args, **kwargs):
        # A simple test - print to screen
        print("A {}: {} - {}".format(notify_type, title, body))

        # No return (so a return of None) get's translated to True

    # Define another in the same file; uppercase goes to lower
    @notify(on="CLIhookb")
    def mywrapper(body, title, notify_type, *args, **kwargs):
        # A simple test - print to screen
        print("B {}: {} - {}".format(notify_type, title, body))

        # No return (so a return of None) get's translated to True
    """))

    N_MGR.module_detection(str(notify_hook))

    assert 'clihooka' in N_MGR
    assert 'clihookb' in N_MGR
    N_MGR.unload_modules()
    assert 'clihooka' not in N_MGR
    assert 'clihookb' not in N_MGR

    N_MGR.module_detection(str(notify_hook))
    assert 'clihooka' in N_MGR
    assert 'clihookb' in N_MGR
    del N_MGR['clihookb']
    assert 'clihooka' in N_MGR
    assert 'clihookb' not in N_MGR
    del N_MGR['clihooka']
    assert 'clihooka' not in N_MGR
    assert 'clihookb' not in N_MGR

    # Prepare ourselves a file to work with
    notify_base = tmpdir.mkdir('plugins')
    notify_test = notify_base.join('NotifyTest.py')
    notify_test.write(cleandoc("""
    #
    # Bare Minimum Valid Object
    #
    from apprise.plugins import NotifyBase
    from apprise.common import NotifyType

    class NotifyTest(NotifyBase):

        service_name = 'Test'

        # The services URL
        service_url = 'https://github.com/caronc/apprise/'

        # Define our protocol
        secure_protocol = 'mytest'

        # A URL that takes you to the setup/help of the specific protocol
        setup_url = 'https://github.com/caronc/apprise/wiki/Notify_mytest'

        # Define object templates
        templates = (
            '{schema}://',
        )

        def __init__(self, **kwargs):
            super().__init__(**kwargs)

        def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
            return True

        def url(self):
            return 'mytest://'
    """))
    assert 'mytest' not in N_MGR
    N_MGR.load_modules(path=str(notify_base))
    assert 'mytest' in N_MGR
    del N_MGR['mytest']
    assert 'mytest' not in N_MGR

    assert 'mytest' not in N_MGR
    N_MGR.load_modules(path=str(notify_base))

    # It's still not loaded because the path has already been scanned
    assert 'mytest' not in N_MGR
    N_MGR.load_modules(path=str(notify_base), force=True)
    assert 'mytest' in N_MGR

    # Double load will test section of code that prevents a notification
    # From reloading if previously already loaded
    N_MGR.load_modules(path=str(notify_base))
    # Our item is still loaded as expected
    assert 'mytest' in N_MGR

    # Simple test to make sure we can handle duplicate entries loaded
    N_MGR.load_modules(path=str(notify_base), force=True)
    N_MGR.load_modules(path=str(notify_base), force=True)