Debian Codegraph @

tests/test_config_http.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 time
31 from typing import ClassVar
32 from unittest import mock
33
34 import pytest
35 import requests
36
37 from apprise import NotificationManager
38 from apprise.common import ConfigFormat
39 from apprise.config.http import ConfigHTTP
40 from apprise.exception import AppriseImproperlyConfigured
41 from apprise.plugins import NotifyBase
42
43 logging.disable(logging.CRITICAL)
44
45 # Grant access to our Notification Manager Singleton
46 N_MGR = NotificationManager()
47
48 # Some exception handling we'll use
49 REQUEST_EXCEPTIONS = (
50 requests.ConnectionError(0, "requests.ConnectionError() not handled"),
51 requests.RequestException(0, "requests.RequestException() not handled"),
52 requests.HTTPError(0, "requests.HTTPError() not handled"),
53 requests.ReadTimeout(0, "requests.ReadTimeout() not handled"),
54 requests.TooManyRedirects(0, "requests.TooManyRedirects() not handled"),
55 )
56
57
58 @mock.patch("requests.post")
59 def test_config_http(mock_post):
60 """
61 API: ConfigHTTP() object
62
63 """
64
65 # Define our good:// url
66 class GoodNotification(NotifyBase):
67 def __init__(self, *args, **kwargs):
68 super().__init__(*args, **kwargs)
69
70 def notify(self, *args, **kwargs):
71 # Pretend everything is okay
72 return True
73
74 def url(self, **kwargs):
75 # Support url() function
76 return ""
77
78 # Store our good notification in our schema map
79 N_MGR["good"] = GoodNotification
80
81 # Our default content
82 default_content = """taga,tagb=good://server01"""
83
84 class DummyResponse:
85 """A dummy response used to manage our object."""
86
87 status_code = requests.codes.ok
88 headers: ClassVar[dict[str, str]] = {
89 "Content-Length": str(len(default_content)),
90 "Content-Type": "text/plain",
91 }
92
93 text = default_content
94
95 # Pointer to file
96 ptr = None
97
98 def close(self):
99 return
100
101 def raise_for_status(self):
102 return
103
104 def __enter__(self):
105 return self
106
107 def __exit__(self, *args, **kwargs):
108 return
109
110 # Prepare Mock
111 dummy_response = DummyResponse()
112 mock_post.return_value = dummy_response
113
114 assert ConfigHTTP.parse_url("garbage://") is None
115
116 results = ConfigHTTP.parse_url("http://user:pass@localhost?+key=value")
117 assert isinstance(results, dict)
118 ch = ConfigHTTP(**results)
119 assert isinstance(ch.url(), str) is True
120 assert isinstance(ch.read(), str) is True
121
122 # one entry added
123 assert len(ch) == 1
124
125 # Password-only administrator credentials preserve the empty username.
126 results = ConfigHTTP.parse_url("http://:pass@localhost/path/")
127 assert isinstance(results, dict)
128 ch = ConfigHTTP(**results)
129 assert ch.url(privacy=False).startswith("http://:pass@localhost/path/")
130 assert isinstance(ch.read(), str) is True
131 assert mock_post.call_args.kwargs["auth"] == ("", "pass")
132
133 results = ConfigHTTP.parse_url("http://localhost:8080/path/")
134 assert isinstance(results, dict)
135 ch = ConfigHTTP(**results)
136 assert isinstance(ch.url(), str) is True
137 assert isinstance(ch.read(), str) is True
138
139 # one entry added
140 assert len(ch) == 1
141
142 # Clear all our mock counters
143 mock_post.reset_mock()
144
145 # Cache Handling; cache each request for 30 seconds
146 results = ConfigHTTP.parse_url("http://localhost:8080/path/?cache=30")
147 assert mock_post.call_count == 0
148 assert isinstance(ch.url(), str) is True
149
150 assert isinstance(results, dict)
151 ch = ConfigHTTP(**results)
152 assert mock_post.call_count == 0
153
154 assert isinstance(ch.url(), str) is True
155 assert mock_post.call_count == 0
156
157 assert isinstance(ch.read(), str) is True
158 assert mock_post.call_count == 1
159
160 # Clear all our mock counters
161 mock_post.reset_mock()
162
163 # Behind the scenes we haven't actually made a fetch yet. We can consider
164 # our content expired at this point
165 assert ch.expired() is True
166
167 # Test using boolean check; this will force a remote fetch
168 assert ch
169
170 # Now a call was made
171 assert mock_post.call_count == 1
172 mock_post.reset_mock()
173
174 # Our content hasn't expired yet (it's good for 30 seconds)
175 assert ch.expired() is False
176 assert len(ch) == 1
177 assert mock_post.call_count == 0
178
179 # Test using boolean check; we will re-use our cache and not
180 # make another remote request
181 mock_post.reset_mock()
182 assert ch
183 assert len(ch.services()) == 1
184 assert len(ch) == 1
185
186 # No remote post has been made
187 assert mock_post.call_count == 0
188
189 with mock.patch("time.time", return_value=time.time() + 10):
190 # even with 10 seconds elapsed, no fetch will be made
191 assert ch.expired() is False
192 assert ch
193 assert len(ch.services()) == 1
194 assert len(ch) == 1
195
196 # No remote post has been made
197 assert mock_post.call_count == 0
198
199 with mock.patch("time.time", return_value=time.time() + 31):
200 # but 30+ seconds from now is considered expired
201 assert ch.expired() is True
202 assert ch
203 assert len(ch.services()) == 1
204 assert len(ch) == 1
205
206 # Our content would have been renewed with a single new fetch
207 assert mock_post.call_count == 1
208
209 # one entry added
210 assert len(ch) == 1
211
212 # Invalid cache
213 results = ConfigHTTP.parse_url("http://localhost:8080/path/?cache=False")
214 assert isinstance(results, dict)
215 assert isinstance(ch.url(), str) is True
216
217 results = ConfigHTTP.parse_url("http://localhost:8080/path/?cache=-10")
218 assert isinstance(results, dict)
219 with pytest.raises(AppriseImproperlyConfigured):
220 ch = ConfigHTTP(**results)
221
222 results = ConfigHTTP.parse_url("http://user@localhost?format=text")
223 assert isinstance(results, dict)
224 ch = ConfigHTTP(**results)
225 assert isinstance(ch.url(), str) is True
226 assert isinstance(ch.read(), str) is True
227
228 # one entry added
229 assert len(ch) == 1
230
231 results = ConfigHTTP.parse_url("https://localhost")
232 assert isinstance(results, dict)
233 ch = ConfigHTTP(**results)
234 assert isinstance(ch.url(), str) is True
235 assert isinstance(ch.read(), str) is True
236
237 # one entry added
238 assert len(ch) == 1
239
240 # Testing of pop
241 ch = ConfigHTTP(**results)
242
243 ref = ch[0]
244 assert isinstance(ref, NotifyBase) is True
245
246 ref_popped = ch.pop(0)
247 assert isinstance(ref_popped, NotifyBase) is True
248
249 assert ref == ref_popped
250
251 assert len(ch) == 0
252
253 # reference to calls on initial reference
254 ch = ConfigHTTP(**results)
255 assert isinstance(ch.pop(0), NotifyBase) is True
256
257 ch = ConfigHTTP(**results)
258 assert isinstance(ch[0], NotifyBase) is True
259 # Second reference actually uses cache
260 assert isinstance(ch[0], NotifyBase) is True
261
262 ch = ConfigHTTP(**results)
263 # Itereator creation (nothing needed to assert here)
264 iter(ch)
265 # Second reference actually uses cache
266 iter(ch)
267
268 # Test a buffer size limit reach
269 ch.max_buffer_size = len(dummy_response.text)
270 assert isinstance(ch.read(), str) is True
271
272 # Test YAML detection
273 yaml_supported_types = (
274 "text/yaml",
275 "text/x-yaml",
276 "application/yaml",
277 "application/x-yaml",
278 )
279
280 for st in yaml_supported_types:
281 dummy_response.headers["Content-Type"] = st
282 ch.default_config_format = None
283 assert isinstance(ch.read(), str) is True
284 # Set to YAML
285 assert ch.default_config_format == ConfigFormat.YAML
286
287 # Test TEXT detection
288 text_supported_types = ("text/plain", "text/html")
289
290 for st in text_supported_types:
291 dummy_response.headers["Content-Type"] = st
292 ch.default_config_format = None
293 assert isinstance(ch.read(), str) is True
294 # Set to TEXT
295 assert ch.default_config_format == ConfigFormat.TEXT
296
297 # The type is never adjusted to mime types we don't understand
298 ukwn_supported_types = ("text/css", "application/zip")
299
300 for st in ukwn_supported_types:
301 dummy_response.headers["Content-Type"] = st
302 ch.default_config_format = None
303 assert isinstance(ch.read(), str) is True
304 # Remains unchanged
305 assert ch.default_config_format is None
306
307 # When the entry is missing; we handle this too
308 del dummy_response.headers["Content-Type"]
309 ch.default_config_format = None
310 assert isinstance(ch.read(), str) is True
311 # Remains unchanged
312 assert ch.default_config_format is None
313
314 # Restore our content type object for lower tests
315 dummy_response.headers["Content-Type"] = "text/plain"
316
317 # Take a snapshot
318 max_buffer_size = ch.max_buffer_size
319
320 ch.max_buffer_size = len(dummy_response.text) - 1
321 assert ch.read() is None
322
323 # Restore buffer size count
324 ch.max_buffer_size = max_buffer_size
325
326 # Test erroneous Content-Length
327 # Our content is still within the limits, so we're okay
328 dummy_response.headers["Content-Length"] = "garbage"
329
330 assert isinstance(ch.read(), str) is True
331
332 dummy_response.headers["Content-Length"] = "None"
333 # Our content is still within the limits, so we're okay
334 assert isinstance(ch.read(), str) is True
335
336 # Handle cases where the content length is exactly at our limit
337 dummy_response.text = "a" * ch.max_buffer_size
338 # This is acceptable
339 assert isinstance(ch.read(), str) is True
340
341 # If we are over our limit though..
342 dummy_response.text = "b" * (ch.max_buffer_size + 1)
343 assert ch.read() is None
344
345 # Test an invalid return code
346 dummy_response.status_code = 400
347 assert ch.read() is None
348 ch.max_error_buffer_size = 0
349 assert ch.read() is None
350
351 # Test that a 3xx redirect is rejected when redirect=no is set; a
352 # status-code range guard (300-399) catches what raise_for_status() misses.
353 class RedirectResponse:
354 """Simulates a 301 response returned when allow_redirects=False."""
355
356 status_code = requests.codes.moved_permanently
357 headers: ClassVar[dict[str, str]] = {}
358 text = ""
359
360 def raise_for_status(self):
361 return
362
363 def __enter__(self):
364 return self
365
366 def __exit__(self, *args, **kwargs):
367 return
368
369 mock_post.return_value = RedirectResponse()
370 results = ConfigHTTP.parse_url("http://localhost/?redirect=no")
371 assert isinstance(results, dict)
372 ch_no_redir = ConfigHTTP(**results)
373 assert ch_no_redir.redirects is False
374 # read() must return None -- returning redirect HTML as config is wrong
375 assert ch_no_redir.read() is None
376 # Restore for downstream tests
377 mock_post.return_value = dummy_response
378
379 # Exception handling
380 for exception in REQUEST_EXCEPTIONS:
381 mock_post.side_effect = exception
382 assert ch.read() is None
383
384 # Restore buffer size count
385 ch.max_buffer_size = max_buffer_size