Debian Codegraph @

tests/test_apprise_attachments.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 inspect import cleandoc
29 import json
30
31 # Disable logging for a cleaner testing output
32 import logging
33 from os.path import dirname, getsize, join
34 from unittest import mock
35
36 import pytest
37 import requests
38
39 from apprise import Apprise, AppriseAsset, AttachmentManager
40 from apprise.apprise_attachment import AppriseAttachment
41 from apprise.attachment import AttachBase
42 from apprise.common import ContentLocation
43 from apprise.exception import AppriseImproperlyConfigured
44 from apprise.logger import LogCapture
45
46 logging.disable(logging.CRITICAL)
47
48 TEST_VAR_DIR = join(dirname(__file__), "var")
49
50 # Grant access to our Attachment Manager Singleton
51 A_MGR = AttachmentManager()
52
53
54 def test_apprise_attachment():
55 """
56 API: AppriseAttachment basic testing
57
58 """
59
60 # Create ourselves an attachment object
61 aa = AppriseAttachment()
62
63 # There are no attachents loaded
64 assert len(aa) == 0
65
66 # Object can be directly checked as a boolean; response is False
67 # when there are no entries loaded
68 assert not aa
69
70 # An attachment object using a custom Apprise Asset object
71 # Set a cache expiry of 5 minutes (300 seconds)
72 aa = AppriseAttachment(asset=AppriseAsset(), cache=300)
73
74 # still no attachments added
75 assert len(aa) == 0
76
77 # Add a file by it's path
78 path = join(TEST_VAR_DIR, "apprise-test.gif")
79 assert aa.add(path)
80
81 # There is now 1 attachment
82 assert len(aa) == 1
83
84 # our attachment took on our cache value
85 assert aa[0].cache == 300
86
87 # we can test the object as a boolean and get a value of True now
88 assert aa
89
90 # Add another entry already in it's AttachBase format
91 response = AppriseAttachment.instantiate(path, cache=True)
92 assert isinstance(response, AttachBase)
93 assert aa.add(response, asset=AppriseAsset())
94
95 # There is now 2 attachments
96 assert len(aa) == 2
97
98 # Cache is initialized to True
99 assert aa[1].cache is True
100
101 # Reset our object
102 aa = AppriseAttachment()
103
104 # We can add by lists as well in a variety of formats
105 attachments = (
106 path,
107 f"file://{path}?name=newfilename.gif?cache=120",
108 AppriseAttachment.instantiate(
109 f"file://{path}?name=anotherfilename.gif", cache=100
110 ),
111 )
112
113 # Add them
114 assert aa.add(attachments, cache=False)
115
116 # There is now 3 attachments
117 assert len(aa) == 3
118
119 # Take on our fixed cache value of False.
120 # The last entry will have our set value of 100
121 assert aa[0].cache is False
122 # Even though we set a value of 120, we take on the value of False because
123 # it was forced on the instantiate call
124 assert aa[1].cache is False
125 assert aa[2].cache == 100
126
127 # We can pop the last element off of the list as well
128 attachment = aa.pop()
129 assert isinstance(attachment, AttachBase)
130 # we can test of the attachment is valid using a boolean check:
131 assert attachment
132 assert len(aa) == 2
133 assert attachment.path == path
134 assert attachment.name == "anotherfilename.gif"
135 assert attachment.mimetype == "image/gif"
136
137 # elements can also be directly indexed
138 assert isinstance(aa[0], AttachBase)
139 assert isinstance(aa[1], AttachBase)
140
141 with pytest.raises(IndexError):
142 aa[2]
143
144 # We can iterate over attachments too:
145 for count, a in enumerate(aa):
146 assert isinstance(a, AttachBase)
147
148 # we'll never iterate more then the number of entries in our object
149 assert count < len(aa)
150
151 # Get the file-size of our image
152 expected_size = getsize(path) * len(aa)
153
154 # verify that's what we get as a result
155 assert aa.size() == expected_size
156
157 # Attachments can also be loaded during the instantiation of the
158 # AppriseAttachment object
159 aa = AppriseAttachment(attachments)
160
161 # There is now 3 attachments
162 assert len(aa) == 3
163
164 # Reset our object
165 aa.clear()
166 assert len(aa) == 0
167 assert not aa
168
169 assert aa.add(
170 AppriseAttachment.instantiate(
171 f"file://{path}?name=andanother.png&cache=Yes"
172 )
173 )
174 assert aa.add(
175 AppriseAttachment.instantiate(
176 f"file://{path}?name=andanother.png&cache=No"
177 )
178 )
179 AppriseAttachment.instantiate(
180 f"file://{path}?name=andanother.png&cache=600"
181 )
182 assert aa.add(
183 AppriseAttachment.instantiate(
184 f"file://{path}?name=andanother.png&cache=600"
185 )
186 )
187
188 assert len(aa) == 3
189 assert aa[0].cache is True
190 assert aa[1].cache is False
191 assert aa[2].cache == 600
192
193 # Negative cache are not allowed
194 assert not aa.add(
195 AppriseAttachment.instantiate(
196 f"file://{path}?name=andanother.png&cache=-600"
197 )
198 )
199
200 # Invalid cache value
201 assert not aa.add(
202 AppriseAttachment.instantiate(
203 f"file://{path}?name=andanother.png", cache="invalid"
204 )
205 )
206
207 # No length change
208 assert len(aa) == 3
209
210 # Reset our object
211 aa.clear()
212
213 # Garbage in produces garbage out
214 assert aa.add(None) is False
215 assert aa.add(object()) is False
216 assert aa.add(42) is False
217
218 # length remains unchanged
219 assert len(aa) == 0
220
221 # We can add by lists as well in a variety of formats
222 attachments = (
223 None,
224 object(),
225 42,
226 "garbage://",
227 )
228
229 # Add our attachments
230 assert aa.add(attachments) is False
231
232 # length remains unchanged
233 assert len(aa) == 0
234
235 # Direct construction reports attachments that could not be loaded.
236 with pytest.raises(AppriseImproperlyConfigured):
237 AppriseAttachment("garbage://")
238
239 # Load our other attachment types
240 aa = AppriseAttachment(location=ContentLocation.LOCAL)
241
242 # Hosted type won't allow us to import files
243 aa = AppriseAttachment(location=ContentLocation.HOSTED)
244 assert len(aa) == 0
245
246 # Add our attachments defined a the head of this function
247 aa.add(attachments)
248
249 # Our length is still zero because we can't import files in
250 # a hosted environment
251 assert len(aa) == 0
252
253 # Inaccessible type prevents the adding of new stuff
254 aa = AppriseAttachment(location=ContentLocation.INACCESSIBLE)
255 assert len(aa) == 0
256
257 # Add our attachments defined a the head of this function
258 aa.add(attachments)
259
260 # Our length is still zero
261 assert len(aa) == 0
262
263 with pytest.raises(AppriseImproperlyConfigured):
264 # Invalid location specified
265 AppriseAttachment(location="invalid")
266
267 # test cases when file simply doesn't exist
268 aa = AppriseAttachment("file://non-existant-file.png")
269 # Our length is still 1
270 assert len(aa) == 1
271 # Our object will still return a True
272 assert aa
273
274 # However our indexed entry will not
275 assert not aa[0]
276
277 # length will return 0
278 assert len(aa[0]) == 0
279
280 # Total length will also return 0
281 assert aa.size() == 0
282
283
284 @mock.patch("requests.request")
285 def test_apprise_attachment_truncate(mock_request):
286 """
287 API: AppriseAttachment when truncation in place
288
289 """
290
291 # Prepare our response
292 response = requests.Request()
293 response.status_code = requests.codes.ok
294
295 # Prepare Mock
296 mock_request.return_value = response
297
298 # our Apprise Object
299 ap_obj = Apprise()
300
301 # Add ourselves an object set to truncate
302 ap_obj.add("json://localhost/?method=GET&overflow=truncate")
303
304 # Create ourselves an attachment object
305 aa = AppriseAttachment()
306
307 # There are no attachents loaded
308 assert len(aa) == 0
309
310 # Object can be directly checked as a boolean; response is False
311 # when there are no entries loaded
312 assert not aa
313
314 # Add 2 attachments
315 assert aa.add(join(TEST_VAR_DIR, "apprise-test.gif"))
316 assert aa.add(join(TEST_VAR_DIR, "apprise-test.png"))
317
318 assert mock_request.call_count == 0
319 assert ap_obj.notify(body="body", title="title", attach=aa)
320
321 assert mock_request.call_count == 1
322
323 # Our first item was truncated, so only 1 attachment
324 details = mock_request.call_args_list[0]
325 assert details[0][0] == "GET"
326 dataset = json.loads(details[1]["data"])
327 assert len(dataset["attachments"]) == 1
328
329 # Reset our object
330 mock_request.reset_mock()
331
332 # our Apprise Object
333 ap_obj = Apprise()
334
335 # Add ourselves an object set to upstream
336 ap_obj.add("json://localhost/?method=GET&overflow=upstream")
337
338 # Create ourselves an attachment object
339 aa = AppriseAttachment()
340
341 # Add 2 attachments
342 assert aa.add(join(TEST_VAR_DIR, "apprise-test.gif"))
343 assert aa.add(join(TEST_VAR_DIR, "apprise-test.png"))
344
345 assert mock_request.call_count == 0
346 assert ap_obj.notify(body="body", title="title", attach=aa)
347
348 assert mock_request.call_count == 1
349
350 # Our item was not truncated, so all attachments
351 details = mock_request.call_args_list[0]
352 assert details[0][0] == "GET"
353 dataset = json.loads(details[1]["data"])
354 assert len(dataset["attachments"]) == 2
355
356
357 def test_apprise_attachment_instantiate():
358 """
359 API: AppriseAttachment.instantiate()
360
361 """
362 assert (
363 AppriseAttachment.instantiate("file://?", suppress_exceptions=True)
364 is None
365 )
366
367 assert (
368 AppriseAttachment.instantiate("invalid://?", suppress_exceptions=True)
369 is None
370 )
371
372 class BadAttachType(AttachBase):
373 def __init__(self, **kwargs):
374 super().__init__(**kwargs)
375
376 # We fail whenever we're initialized
377 raise TypeError()
378
379 # Store our bad attachment type in our schema map
380 A_MGR["bad"] = BadAttachType
381
382 with pytest.raises(TypeError):
383 AppriseAttachment.instantiate("bad://path", suppress_exceptions=False)
384
385 # Same call but exceptions suppressed
386 assert (
387 AppriseAttachment.instantiate("bad://path", suppress_exceptions=True)
388 is None
389 )
390
391
392 def test_attachment_matrix_dynamic_importing(tmpdir):
393 """
394 API: Apprise() Attachment Matrix Importing
395
396 """
397
398 # Make our new path valid
399 suite = tmpdir.mkdir("apprise_attach_test_suite")
400 suite.join("__init__.py").write("")
401
402 module_name = "badattach"
403
404 # Create a base area to work within
405 base = suite.mkdir(module_name)
406 base.join("__init__.py").write("")
407
408 # Test no app_id
409 base.join("AttachBadFile1.py").write(
410 cleandoc("""
411 class AttachBadFile1:
412 pass
413 """)
414 )
415
416 # No class of the same name
417 base.join("AttachBadFile2.py").write(
418 cleandoc("""
419 class BadClassName:
420 pass
421 """)
422 )
423
424 # Exception thrown
425 base.join("AttachBadFile3.py").write("""raise ImportError()""")
426
427 # Utilizes a schema:// already occupied (as string)
428 base.join("AttachGoober.py").write(
429 cleandoc("""
430 from apprise import AttachBase
431 class AttachGoober(AttachBase):
432 # This class tests the fact we have a new class name, but we're
433 # trying to over-ride items previously used
434
435 # The default simple (insecure) protocol
436 protocol = 'http'
437
438 # The default secure protocol
439 secure_protocol = 'https'
440 """)
441 )
442
443 # Utilizes a schema:// already occupied (as tuple)
444 base.join("AttachBugger.py").write(
445 cleandoc("""
446 from apprise import AttachBase
447 class AttachBugger(AttachBase):
448 # This class tests the fact we have a new class name, but we're
449 # trying to over-ride items previously used
450
451 # The default simple (insecure) protocol
452 protocol = ('http', 'bugger-test' )
453
454 # The default secure protocol
455 secure_protocol = ('https', 'bugger-tests')
456 """)
457 )
458
459 A_MGR.load_modules(path=str(base), name=module_name)
460
461
462 def test_attachment_manager_no_import_failures():
463 """Verify all native attach plugins load without TRACE import errors."""
464
465 # Remove the global test-suite log suppression so TRACE records
466 # are visible during the scan below
467 logging.disable(logging.NOTSET)
468
469 # Force a clean reload of the native attachment plugin directory
470 A_MGR.unload_modules()
471
472 with LogCapture(level=logging.TRACE) as stream:
473 # Trigger load_modules() via the lazy-load path
474 len(A_MGR)
475
476 # Grab the captured log content before the handler is removed
477 content = stream.getvalue()
478
479 # Restore log suppression for the remainder of the test suite
480 logging.disable(logging.CRITICAL)
481
482 # Any "import failed" line means a plugin directory was found but
483 # contained no loadable Attach* class (e.g. a stale __pycache__
484 # directory left behind after a rename).
485 failures = [
486 line for line in content.splitlines() if "import failed" in line
487 ]
488 assert not failures, (
489 "Attachment plugin import failures detected:\n" + "\n".join(failures)
490 )
491
492 # Leave the manager in a clean state for subsequent tests
493 A_MGR.unload_modules()