Debian Codegraph @

tests/test_attach_memory.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 # Disable logging for a cleaner testing output
29 import logging
30 import re
31 import urllib
32
33 import pytest
34
35 from apprise import AppriseAttachment, exception
36 from apprise.attachment.base import AttachBase
37 from apprise.attachment.memory import AttachMemory
38 from apprise.common import ContentLocation
39 from apprise.exception import AppriseImproperlyConfigured
40
41 logging.disable(logging.CRITICAL)
42
43
44 def test_attach_memory_parse_url():
45 """
46 API: AttachMemory().parse_url()
47
48 """
49
50 # Bad Entry
51 assert AttachMemory.parse_url(object) is None
52
53 # Our filename is detected automatically
54 assert AttachMemory.parse_url("memory://")
55
56 # pass our content in as a string
57 mem = AttachMemory(content="string")
58 # it loads a string type by default
59 assert mem.mimetype == "text/plain"
60 # Our filename is automatically generated (with .txt)
61 assert re.match(r"^[a-z0-9-]+\.txt$", mem.name, re.I)
62
63 # open our file
64 with mem as fp:
65 assert fp.getbuffer().nbytes == len(mem)
66
67 # pass our content in as a string
68 mem = AttachMemory(
69 content="<html/>", name="test.html", mimetype="text/html"
70 )
71 # it loads a string type by default
72 assert mem.mimetype == "text/html"
73 assert mem.name == "test.html"
74
75 # Stub function
76 assert mem.download()
77
78 with pytest.raises(AppriseImproperlyConfigured):
79 # garbage in, garbage out
80 AttachMemory(content=3)
81
82 # Each open call returns an independent pointer to our data.
83 first = mem.open()
84 second = mem.open()
85 assert first is not second
86 assert first.read(1) == b"<"
87 assert second.read() == b"<html/>"
88
89 # Closing one pointer does not affect another or the attachment.
90 with first:
91 assert first.read() == b"html/>"
92 assert first.closed is True
93 assert second.closed is False
94 assert second.read() == b""
95
96 # The attachment remains readable after its prior pointers are closed.
97 second.close()
98 with mem.open() as pointer:
99 assert pointer.read() == b"<html/>"
100 assert pointer.closed is True
101 with mem.open() as pointer:
102 assert pointer.read() == b"<html/>"
103
104 # pass our content in as a string
105 mem = AttachMemory(content=b"binary-data", name="raw.dat")
106 # it loads a string type by default
107 assert mem.mimetype == "application/octet-stream"
108 assert mem.name == "raw.dat"
109
110 # pass our content in as a string
111 mem = AttachMemory(content=b"binary-data")
112 # it loads a string type by default
113 assert mem.mimetype == "application/octet-stream"
114 # Our filename is automatically generated (with .dat)
115 assert re.match(r"^[a-z0-9-]+\.dat$", mem.name, re.I)
116
117
118 def test_attach_memory():
119 """
120 API: AttachMemory()
121
122 """
123 # A url we can test with
124 fname = "testfile"
125 url = f"memory:///ignored/path/{fname}"
126
127 # Simple gif test
128 response = AppriseAttachment.instantiate(url)
129 assert isinstance(response, AttachMemory)
130
131 # There is no path yet as we haven't written anything to our memory object
132 # yet
133 assert response.path is None
134 assert bool(response) is False
135
136 with response as memobj:
137 memobj.write(b"content")
138
139 # Memory object defaults
140 assert response.name == fname
141 assert response.path == response.name
142 assert response.mimetype == "application/octet-stream"
143 assert bool(response) is True
144
145 #
146 fname_in_url = urllib.parse.quote(response.name)
147 assert response.url().startswith(f"memory://{fname_in_url}")
148
149 # Mime is always part of url
150 assert re.search(r"[?&]mime=", response.url()) is not None
151
152 # Test case where location is simply set to INACCESSIBLE
153 # Below is a bad example, but it proves the section of code properly works.
154 # Ideally a server admin may wish to just disable all File based
155 # attachments entirely. In this case, they simply just need to change the
156 # global singleton at the start of their program like:
157 #
158 # import apprise
159 # apprise.attachment.AttachMemory.location = \
160 # apprise.ContentLocation.INACCESSIBLE
161 #
162 response = AppriseAttachment.instantiate(url)
163 assert isinstance(response, AttachMemory)
164 with response as memobj:
165 memobj.write(b"content")
166
167 response.location = ContentLocation.INACCESSIBLE
168 assert response.path is None
169 # Downloads just don't work period
170 assert response.download() is False
171
172 # File handling (even if image is set to maxium allowable)
173 response = AppriseAttachment.instantiate(url)
174 assert isinstance(response, AttachMemory)
175 with response as memobj:
176 memobj.write(b"content")
177
178 # Memory handling when size is to large
179 response = AppriseAttachment.instantiate(url)
180 assert isinstance(response, AttachMemory)
181 with response as memobj:
182 memobj.write(b"content")
183
184 # Test case where we exceed our defined max_file_size in memory
185 prev_value = AttachBase.max_file_size
186 AttachBase.max_file_size = len(response) - 1
187 # We can't work in this case
188 assert response.path is None
189 assert response.download() is False
190
191 # Restore our file_size
192 AttachBase.max_file_size = prev_value
193
194 response = AppriseAttachment.instantiate(
195 "memory://apprise-file.gif?mime=image/gif"
196 )
197 assert isinstance(response, AttachMemory)
198 with response as memobj:
199 memobj.write(b"content")
200
201 assert response.name == "apprise-file.gif"
202 assert response.path == response.name
203 assert response.mimetype == "image/gif"
204 # No mime-type and/or filename over-ride was specified, so therefore it
205 # won't show up in the generated URL
206 assert re.search(r"[?&]mime=", response.url()) is not None
207 assert "image/gif" in response.url()
208
209 # Force a mime-type and new name
210 response = AppriseAttachment.instantiate(
211 "memory://{}?mime={}&name={}".format(
212 "ignored.gif", "image/jpeg", "test.jpeg"
213 )
214 )
215 assert isinstance(response, AttachMemory)
216 with response as memobj:
217 memobj.write(b"content")
218
219 assert response.name == "test.jpeg"
220 assert response.path == response.name
221 assert response.mimetype == "image/jpeg"
222 # We will match on mime type now (%2F = /)
223 assert re.search(r"[?&]mime=image/jpeg", response.url(), re.I)
224 assert response.url().startswith("memory://test.jpeg")
225
226 # Test hosted configuration and that we can't add a valid memory file
227 aa = AppriseAttachment(location=ContentLocation.HOSTED)
228 assert aa.add(response) is False
229
230 # now test our base64 output
231 assert isinstance(response.base64(), str)
232 # No encoding if we choose
233 assert isinstance(response.base64(encoding=None), bytes)
234
235 response.invalidate()
236 with pytest.raises(exception.AppriseFileNotFound):
237 response.base64()
238
239
240 def test_attach_memory_open_reusable():
241 """
242 API: AttachMemory().open() returns a reusable handle
243
244 """
245 mem = AttachMemory(content=b"content")
246
247 # Closing a handle returned by open() (as a `with` block does)
248 # must not affect the attachment itself
249 with mem.open() as fp:
250 assert fp.read() == b"content"
251
252 # The attachment is still usable afterwards
253 assert bool(mem) is True
254 assert len(mem) == len(b"content")
255 assert mem.exists() is True
256
257 # A second open() call still works and returns the full content
258 with mem.open() as fp:
259 assert fp.read() == b"content"
260
261 # Each call to open() hands back an independent object
262 assert mem.open() is not mem.open()
263
264
265 def test_attach_memory_invalidate_closed_buffer():
266 """
267 API: AttachMemory().invalidate() on an already-closed buffer
268
269 """
270 mem = AttachMemory(content=b"content")
271
272 # Simulate our internal buffer already being closed
273 mem._data.close()
274
275 # invalidate() must not attempt to truncate a closed buffer
276 mem.invalidate()