Debian Codegraph @

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