Debian Codegraph @

tests/test_logger.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 import os
29 import re
30 import sys
31 from unittest import mock
32
33 import pytest
34 import requests
35
36 from apprise import Apprise, AppriseAsset, URLBase
37
38 # Disable logging for a cleaner testing output
39 from apprise.logger import LogCapture, logger, logging
40
41
42 def test_apprise_logger():
43 """
44 API: Apprise() Logger
45
46 """
47
48 # Ensure we're not running in a disabled state
49 logging.disable(logging.NOTSET)
50
51 # Set our log level
52 URLBase.logger.setLevel(logging.DEPRECATE + 1)
53
54 # Deprication will definitely not trigger
55 URLBase.logger.deprecate("test")
56
57 # Verbose Debugging is not on at this point
58 URLBase.logger.trace("test")
59
60 # Set both logging entries on
61 URLBase.logger.setLevel(logging.TRACE)
62
63 # Deprication will definitely trigger
64 URLBase.logger.deprecate("test")
65
66 # Verbose Debugging will activate
67 URLBase.logger.trace("test")
68
69 # Disable Logging
70 logging.disable(logging.CRITICAL)
71
72
73 def test_apprise_log_memory_captures():
74 """
75 API: Apprise() Log Memory Captures
76
77 """
78
79 # Ensure we're not running in a disabled state
80 logging.disable(logging.NOTSET)
81
82 logger.setLevel(logging.CRITICAL)
83 with LogCapture(level=logging.TRACE) as stream:
84 logger.trace("trace")
85 logger.debug("debug")
86 logger.info("info")
87 logger.warning("warning")
88 logger.error("error")
89 logger.deprecate("deprecate")
90
91 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
92
93 # We have a log entry for each of the 6 logs we generated above
94 assert "trace" in stream.getvalue()
95 assert "debug" in stream.getvalue()
96 assert "info" in stream.getvalue()
97 assert "warning" in stream.getvalue()
98 assert "error" in stream.getvalue()
99 assert "deprecate" in stream.getvalue()
100 assert len(logs) == 6
101
102 # Verify that we did not lose our effective log level even though
103 # the above steps the level up for the duration of the capture
104 assert logger.getEffectiveLevel() == logging.CRITICAL
105
106 logger.setLevel(logging.TRACE)
107 with LogCapture(level=logging.DEBUG) as stream:
108 logger.trace("trace")
109 logger.debug("debug")
110 logger.info("info")
111 logger.warning("warning")
112 logger.error("error")
113 logger.deprecate("deprecate")
114
115 # We have a log entry for 5 of the log entries we generated above
116 # There will be no 'trace' entry
117 assert "trace" not in stream.getvalue()
118 assert "debug" in stream.getvalue()
119 assert "info" in stream.getvalue()
120 assert "warning" in stream.getvalue()
121 assert "error" in stream.getvalue()
122 assert "deprecate" in stream.getvalue()
123
124 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
125 assert len(logs) == 5
126
127 # Verify that we did not lose our effective log level even though
128 # the above steps the level up for the duration of the capture
129 assert logger.getEffectiveLevel() == logging.TRACE
130
131 logger.setLevel(logging.ERROR)
132 with LogCapture(level=logging.WARNING) as stream:
133 logger.trace("trace")
134 logger.debug("debug")
135 logger.info("info")
136 logger.warning("warning")
137 logger.error("error")
138 logger.deprecate("deprecate")
139
140 # We have a log entry for 3 of the log entries we generated above
141 # There will be no 'trace', 'debug', or 'info' entry
142 assert "trace" not in stream.getvalue()
143 assert "debug" not in stream.getvalue()
144 assert "info" not in stream.getvalue()
145 assert "warning" in stream.getvalue()
146 assert "error" in stream.getvalue()
147 assert "deprecate" in stream.getvalue()
148
149 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
150 assert len(logs) == 3
151
152 # Set a global level of ERROR
153 logger.setLevel(logging.ERROR)
154
155 # Use the default level of None (by not specifying one); we then
156 # use whatever has been defined globally
157 with LogCapture() as stream:
158 logger.trace("trace")
159 logger.debug("debug")
160 logger.info("info")
161 logger.warning("warning")
162 logger.error("error")
163 logger.deprecate("deprecate")
164
165 assert "trace" not in stream.getvalue()
166 assert "debug" not in stream.getvalue()
167 assert "info" not in stream.getvalue()
168 assert "warning" not in stream.getvalue()
169 assert "error" in stream.getvalue()
170 assert "deprecate" in stream.getvalue()
171
172 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
173 assert len(logs) == 2
174
175 # Verify that we did not lose our effective log level
176 assert logger.getEffectiveLevel() == logging.ERROR
177
178 with LogCapture(level=logging.TRACE) as stream:
179 logger.trace("trace")
180 logger.debug("debug")
181 logger.info("info")
182 logger.warning("warning")
183 logger.error("error")
184 logger.deprecate("deprecate")
185
186 # We have a log entry for each of the 6 logs we generated above
187 assert "trace" in stream.getvalue()
188 assert "debug" in stream.getvalue()
189 assert "info" in stream.getvalue()
190 assert "warning" in stream.getvalue()
191 assert "error" in stream.getvalue()
192 assert "deprecate" in stream.getvalue()
193
194 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
195 assert len(logs) == 6
196
197 # Verify that we did not lose our effective log level even though
198 # the above steps the level up for the duration of the capture
199 assert logger.getEffectiveLevel() == logging.ERROR
200
201 # Test capture where our notification throws an unhandled exception
202 obj = Apprise.instantiate("json://user:[email protected]")
203 with (
204 mock.patch("requests.request", side_effect=NotImplementedError()),
205 pytest.raises(NotImplementedError),
206 # Our exception gets caught in side our with() block
207 # and although raised, all graceful handling of the log
208 # is reverted as it was
209 LogCapture(level=logging.TRACE) as stream,
210 ):
211 obj.send("hello world")
212
213 # Disable Logging
214 logging.disable(logging.CRITICAL)
215
216
217 def test_apprise_log_file_captures(tmpdir):
218 """
219 API: Apprise() Log File Captures
220
221 """
222
223 # Ensure we're not running in a disabled state
224 logging.disable(logging.NOTSET)
225
226 log_file = tmpdir.join("capture.log")
227 assert not os.path.isfile(str(log_file))
228
229 logger.setLevel(logging.CRITICAL)
230 with LogCapture(path=str(log_file), level=logging.TRACE) as fp:
231 # The file will exit now
232 assert os.path.isfile(str(log_file))
233
234 logger.trace("trace")
235 logger.debug("debug")
236 logger.info("info")
237 logger.warning("warning")
238 logger.error("error")
239 logger.deprecate("deprecate")
240
241 content = fp.read().rstrip()
242 logs = re.split(r"\r*\n", content)
243
244 # We have a log entry for each of the 6 logs we generated above
245 assert "trace" in content
246 assert "debug" in content
247 assert "info" in content
248 assert "warning" in content
249 assert "error" in content
250 assert "deprecate" in content
251 assert len(logs) == 6
252
253 # The file is automatically cleaned up afterwards
254 assert not os.path.isfile(str(log_file))
255
256 # Verify that we did not lose our effective log level even though
257 # the above steps the level up for the duration of the capture
258 assert logger.getEffectiveLevel() == logging.CRITICAL
259
260 logger.setLevel(logging.TRACE)
261 with LogCapture(path=str(log_file), level=logging.DEBUG) as fp:
262 # The file will exit now
263 assert os.path.isfile(str(log_file))
264
265 logger.trace("trace")
266 logger.debug("debug")
267 logger.info("info")
268 logger.warning("warning")
269 logger.error("error")
270 logger.deprecate("deprecate")
271
272 content = fp.read().rstrip()
273 logs = re.split(r"\r*\n", content)
274
275 # We have a log entry for 5 of the log entries we generated above
276 # There will be no 'trace' entry
277 assert "trace" not in content
278 assert "debug" in content
279 assert "info" in content
280 assert "warning" in content
281 assert "error" in content
282 assert "deprecate" in content
283
284 assert len(logs) == 5
285
286 # Concurrent file access is not possible on Windows.
287 # PermissionError: [WinError 32] The process cannot access the file
288 # because it is being used by another process.
289 if sys.platform != "win32":
290 # Remove our file before we exit the with clause
291 # this causes our delete() call to throw gracefully inside
292 os.unlink(str(log_file))
293
294 # Verify file is gone
295 assert not os.path.isfile(str(log_file))
296
297 # Verify that we did not lose our effective log level even though
298 # the above steps the level up for the duration of the capture
299 assert logger.getEffectiveLevel() == logging.TRACE
300
301 logger.setLevel(logging.ERROR)
302 with LogCapture(
303 path=str(log_file), delete=False, level=logging.WARNING
304 ) as fp:
305 # Verify exists
306 assert os.path.isfile(str(log_file))
307
308 logger.trace("trace")
309 logger.debug("debug")
310 logger.info("info")
311 logger.warning("warning")
312 logger.error("error")
313 logger.deprecate("deprecate")
314
315 content = fp.read().rstrip()
316 logs = re.split(r"\r*\n", content)
317
318 # We have a log entry for 3 of the log entries we generated above
319 # There will be no 'trace', 'debug', or 'info' entry
320 assert "trace" not in content
321 assert "debug" not in content
322 assert "info" not in content
323 assert "warning" in content
324 assert "error" in content
325 assert "deprecate" in content
326
327 assert len(logs) == 3
328
329 # Verify the file still exists (because delete was set to False)
330 assert os.path.isfile(str(log_file))
331
332 # remove it now
333 os.unlink(str(log_file))
334
335 # Enure it's been removed
336 assert not os.path.isfile(str(log_file))
337
338 # Set a global level of ERROR
339 logger.setLevel(logging.ERROR)
340
341 # Test case where we can't open the file
342 with (
343 mock.patch("builtins.open", side_effect=OSError()),
344 # Use the default level of None (by not specifying one); we then
345 # use whatever has been defined globally
346 pytest.raises(OSError),
347 LogCapture(path=str(log_file)) as fp,
348 ):
349 # we'll never get here because we'll fail to open the file
350 pass
351
352 # Disable Logging
353 logging.disable(logging.CRITICAL)
354
355
356 @mock.patch("requests.request")
357 def test_apprise_secure_logging(mock_request):
358 """
359 API: Apprise() secure logging tests
360 """
361
362 # Ensure we're not running in a disabled state
363 logging.disable(logging.NOTSET)
364
365 logger.setLevel(logging.CRITICAL)
366
367 # Prepare Mock
368 mock_request.return_value = requests.Request()
369 mock_request.return_value.status_code = requests.codes.ok
370
371 # Default Secure Logging is set to enabled
372 asset = AppriseAsset()
373 assert asset.secure_logging is True
374
375 # Load our asset
376 a = Apprise(asset=asset)
377
378 with LogCapture(level=logging.DEBUG) as stream:
379 # add a test server
380 assert a.add("json://user:pass1$-3!@localhost") is True
381
382 # Our servers should carry this flag
383 assert a[0].asset.secure_logging is True
384
385 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
386 assert len(logs) == 1
387 entry = re.split(r"\s-\s", logs[0])
388 assert len(entry) == 3
389 assert entry[1] == "DEBUG"
390 assert entry[2].startswith(
391 "Loaded JSON URL: json://user:****@localhost/"
392 )
393
394 # Send notification
395 assert a.notify("test") is True
396
397 # Test our call count
398 assert mock_request.call_count == 1
399
400 # Reset
401 mock_request.reset_mock()
402
403 # Now we test the reverse configuration and turn off
404 # secure logging.
405
406 # Default Secure Logging is set to disable
407 asset = AppriseAsset(secure_logging=False)
408 assert asset.secure_logging is False
409
410 # Load our asset
411 a = Apprise(asset=asset)
412
413 with LogCapture(level=logging.DEBUG) as stream:
414 # add a test server
415 assert a.add("json://user:pass1$-3!@localhost") is True
416
417 # Our servers should carry this flag
418 assert a[0].asset.secure_logging is False
419
420 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
421 assert len(logs) == 1
422 entry = re.split(r"\s-\s", logs[0])
423 assert len(entry) == 3
424 assert entry[1] == "DEBUG"
425
426 # Note that our password is no longer escaped (it is however
427 # url encoded)
428 assert entry[2].startswith(
429 "Loaded JSON URL: json://user:pass1%24-3%21@localhost/"
430 )
431
432 # Disable Logging
433 logging.disable(logging.CRITICAL)