Debian Codegraph @

tests/test_apprise_attachments.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 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.logger import LogCapture
44
45 logging.disable(logging.CRITICAL)
46
47 TEST_VAR_DIR = join(dirname(__file__), "var")
48
49 # Grant access to our Attachment Manager Singleton
50 A_MGR = AttachmentManager()
51
52
53 def test_apprise_attachment():
54 """
55 API: AppriseAttachment basic testing
56
57 """
58
59 # Create ourselves an attachment object
60 aa = AppriseAttachment()
61
62 # There are no attachents loaded
63 assert len(aa) == 0
64
65 # Object can be directly checked as a boolean; response is False
66 # when there are no entries loaded
67 assert not aa
68
69 # An attachment object using a custom Apprise Asset object
70 # Set a cache expiry of 5 minutes (300 seconds)
71 aa = AppriseAttachment(asset=AppriseAsset(), cache=300)
72
73 # still no attachments added
74 assert len(aa) == 0
75
76 # Add a file by it's path
77 path = join(TEST_VAR_DIR, "apprise-test.gif")
78 assert aa.add(path)
79
80 # There is now 1 attachment
81 assert len(aa) == 1
82
83 # our attachment took on our cache value
84 assert aa[0].cache == 300
85
86 # we can test the object as a boolean and get a value of True now
87 assert aa
88
89 # Add another entry already in it's AttachBase format
90 response = AppriseAttachment.instantiate(path, cache=True)
91 assert isinstance(response, AttachBase)
92 assert aa.add(response, asset=AppriseAsset())
93
94 # There is now 2 attachments
95 assert len(aa) == 2
96
97 # Cache is initialized to True
98 assert aa[1].cache is True
99
100 # Reset our object
101 aa = AppriseAttachment()
102
103 # We can add by lists as well in a variety of formats
104 attachments = (
105 path,
106 f"file://{path}?name=newfilename.gif?cache=120",
107 AppriseAttachment.instantiate(
108 f"file://{path}?name=anotherfilename.gif", cache=100
109 ),
110 )
111
112 # Add them
113 assert aa.add(attachments, cache=False)
114
115 # There is now 3 attachments
116 assert len(aa) == 3
117
118 # Take on our fixed cache value of False.
119 # The last entry will have our set value of 100
120 assert aa[0].cache is False
121 # Even though we set a value of 120, we take on the value of False because
122 # it was forced on the instantiate call
123 assert aa[1].cache is False
124 assert aa[2].cache == 100
125
126 # We can pop the last element off of the list as well
127 attachment = aa.pop()
128 assert isinstance(attachment, AttachBase)
129 # we can test of the attachment is valid using a boolean check:
130 assert attachment
131 assert len(aa) == 2
132 assert attachment.path == path
133 assert attachment.name == "anotherfilename.gif"
134 assert attachment.mimetype == "image/gif"
135
136 # elements can also be directly indexed
137 assert isinstance(aa[0], AttachBase)
138 assert isinstance(aa[1], AttachBase)
139
140 with pytest.raises(IndexError):
141 aa[2]
142
143 # We can iterate over attachments too:
144 for count, a in enumerate(aa):
145 assert isinstance(a, AttachBase)
146
147 # we'll never iterate more then the number of entries in our object
148 assert count < len(aa)
149
150 # Get the file-size of our image
151 expected_size = getsize(path) * len(aa)
152
153 # verify that's what we get as a result
154 assert aa.size() == expected_size
155
156 # Attachments can also be loaded during the instantiation of the
157 # AppriseAttachment object
158 aa = AppriseAttachment(attachments)
159
160 # There is now 3 attachments
161 assert len(aa) == 3
162
163 # Reset our object
164 aa.clear()
165 assert len(aa) == 0
166 assert not aa
167
168 assert aa.add(
169 AppriseAttachment.instantiate(
170 f"file://{path}?name=andanother.png&cache=Yes"
171 )
172 )
173 assert aa.add(
174 AppriseAttachment.instantiate(
175 f"file://{path}?name=andanother.png&cache=No"
176 )
177 )
178 AppriseAttachment.instantiate(
179 f"file://{path}?name=andanother.png&cache=600"
180 )
181 assert aa.add(
182 AppriseAttachment.instantiate(
183 f"file://{path}?name=andanother.png&cache=600"
184 )
185 )
186
187 assert len(aa) == 3
188 assert aa[0].cache is True
189 assert aa[1].cache is False
190 assert aa[2].cache == 600
191
192 # Negative cache are not allowed
193 assert not aa.add(
194 AppriseAttachment.instantiate(
195 f"file://{path}?name=andanother.png&cache=-600"
196 )
197 )
198
199 # Invalid cache value
200 assert not aa.add(
201 AppriseAttachment.instantiate(
202 f"file://{path}?name=andanother.png", cache="invalid"
203 )
204 )
205
206 # No length change
207 assert len(aa) == 3
208
209 # Reset our object
210 aa.clear()
211
212 # Garbage in produces garbage out
213 assert aa.add(None) is False
214 assert aa.add(object()) is False
215 assert aa.add(42) is False
216
217 # length remains unchanged
218 assert len(aa) == 0
219
220 # We can add by lists as well in a variety of formats
221 attachments = (
222 None,
223 object(),
224 42,
225 "garbage://",
226 )
227
228 # Add our attachments
229 assert aa.add(attachments) is False
230
231 # length remains unchanged
232 assert len(aa) == 0
233
234 # if instantiating attachments from the class, it will throw a TypeError
235 # if attachments couldn't be loaded
236 with pytest.raises(TypeError):
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(TypeError):
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()