Debian Codegraph @

tests/test_logger.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 import asyncio
29 import concurrent.futures as cf
30 import contextvars
31 from datetime import datetime, timezone
32 from importlib import import_module
33 import io
34 import json
35 import os
36 import re
37 import sys
38 import threading
39 import time
40 from unittest import mock
41
42 import pytest
43 import requests
44
45 from apprise import Apprise, AppriseAsset, URLBase
46 from apprise.common import AWARE_DATE_ISO_FORMAT
47
48 # Disable logging for a cleaner testing output
49 from apprise.logger import (
50 LogCapture,
51 NotifyLogEntry,
52 _active_call_capture,
53 _active_capture,
54 _LogCaptureBudget,
55 _NotifyLogStore,
56 _ServiceLogCapture,
57 logger,
58 logging,
59 )
60 from apprise.plugins import NotifyBase
61
62 # Import the module directly because ``apprise.logger`` is also a public
63 # package attribute containing the shared Logger instance.
64 _LOGGER_MODULE = import_module("apprise.logger")
65
66
67 def test_apprise_logger():
68 """
69 API: Apprise() Logger
70
71 """
72
73 # Ensure we're not running in a disabled state
74 logging.disable(logging.NOTSET)
75
76 # Set our log level
77 URLBase.logger.setLevel(logging.DEPRECATE + 1)
78
79 # Deprication will definitely not trigger
80 URLBase.logger.deprecate("test")
81
82 # Verbose Debugging is not on at this point
83 URLBase.logger.trace("test")
84
85 # Set both logging entries on
86 URLBase.logger.setLevel(logging.TRACE)
87
88 # Deprication will definitely trigger
89 URLBase.logger.deprecate("test")
90
91 # Verbose Debugging will activate
92 URLBase.logger.trace("test")
93
94 # Disable Logging
95 logging.disable(logging.CRITICAL)
96
97
98 def test_apprise_log_memory_captures():
99 """
100 API: Apprise() Log Memory Captures
101
102 """
103
104 # Ensure we're not running in a disabled state
105 logging.disable(logging.NOTSET)
106
107 logger.setLevel(logging.CRITICAL)
108 with LogCapture(level=logging.TRACE) as stream:
109 logger.trace("trace")
110 logger.debug("debug")
111 logger.info("info")
112 logger.warning("warning")
113 logger.error("error")
114 logger.deprecate("deprecate")
115
116 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
117
118 # We have a log entry for each of the 6 logs we generated above
119 assert "trace" in stream.getvalue()
120 assert "debug" in stream.getvalue()
121 assert "info" in stream.getvalue()
122 assert "warning" in stream.getvalue()
123 assert "error" in stream.getvalue()
124 assert "deprecate" in stream.getvalue()
125 assert len(logs) == 6
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.CRITICAL
130
131 logger.setLevel(logging.TRACE)
132 with LogCapture(level=logging.DEBUG) 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 5 of the log entries we generated above
141 # There will be no 'trace' entry
142 assert "trace" not in stream.getvalue()
143 assert "debug" in stream.getvalue()
144 assert "info" 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) == 5
151
152 # Verify that we did not lose our effective log level even though
153 # the above steps the level up for the duration of the capture
154 assert logger.getEffectiveLevel() == logging.TRACE
155
156 logger.setLevel(logging.ERROR)
157 with LogCapture(level=logging.WARNING) 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 # We have a log entry for 3 of the log entries we generated above
166 # There will be no 'trace', 'debug', or 'info' entry
167 assert "trace" not in stream.getvalue()
168 assert "debug" not in stream.getvalue()
169 assert "info" not in stream.getvalue()
170 assert "warning" in stream.getvalue()
171 assert "error" in stream.getvalue()
172 assert "deprecate" in stream.getvalue()
173
174 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
175 assert len(logs) == 3
176
177 # Set a global level of ERROR
178 logger.setLevel(logging.ERROR)
179
180 # Use the default level of None (by not specifying one); we then
181 # use whatever has been defined globally
182 with LogCapture() as stream:
183 logger.trace("trace")
184 logger.debug("debug")
185 logger.info("info")
186 logger.warning("warning")
187 logger.error("error")
188 logger.deprecate("deprecate")
189
190 assert "trace" not in stream.getvalue()
191 assert "debug" not in stream.getvalue()
192 assert "info" not in stream.getvalue()
193 assert "warning" not in stream.getvalue()
194 assert "error" in stream.getvalue()
195 assert "deprecate" in stream.getvalue()
196
197 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
198 assert len(logs) == 2
199
200 # Verify that we did not lose our effective log level
201 assert logger.getEffectiveLevel() == logging.ERROR
202
203 with LogCapture(level=logging.TRACE) as stream:
204 logger.trace("trace")
205 logger.debug("debug")
206 logger.info("info")
207 logger.warning("warning")
208 logger.error("error")
209 logger.deprecate("deprecate")
210
211 # We have a log entry for each of the 6 logs we generated above
212 assert "trace" in stream.getvalue()
213 assert "debug" in stream.getvalue()
214 assert "info" in stream.getvalue()
215 assert "warning" in stream.getvalue()
216 assert "error" in stream.getvalue()
217 assert "deprecate" in stream.getvalue()
218
219 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
220 assert len(logs) == 6
221
222 # Verify that we did not lose our effective log level even though
223 # the above steps the level up for the duration of the capture
224 assert logger.getEffectiveLevel() == logging.ERROR
225
226 # Test capture where our notification throws an unhandled exception
227 obj = Apprise.instantiate("json://user:[email protected]")
228 with (
229 mock.patch("requests.request", side_effect=NotImplementedError()),
230 pytest.raises(NotImplementedError),
231 # Our exception gets caught in side our with() block
232 # and although raised, all graceful handling of the log
233 # is reverted as it was
234 LogCapture(level=logging.TRACE) as stream,
235 ):
236 obj.send("hello world")
237
238 # Disable Logging
239 logging.disable(logging.CRITICAL)
240
241
242 def test_apprise_log_file_captures(tmpdir):
243 """
244 API: Apprise() Log File Captures
245
246 """
247
248 # Ensure we're not running in a disabled state
249 logging.disable(logging.NOTSET)
250
251 log_file = tmpdir.join("capture.log")
252 assert not os.path.isfile(str(log_file))
253
254 logger.setLevel(logging.CRITICAL)
255 with LogCapture(path=str(log_file), level=logging.TRACE) as fp:
256 # The file will exit now
257 assert os.path.isfile(str(log_file))
258
259 logger.trace("trace")
260 logger.debug("debug")
261 logger.info("info")
262 logger.warning("warning")
263 logger.error("error")
264 logger.deprecate("deprecate")
265
266 content = fp.read().rstrip()
267 logs = re.split(r"\r*\n", content)
268
269 # We have a log entry for each of the 6 logs we generated above
270 assert "trace" in content
271 assert "debug" in content
272 assert "info" in content
273 assert "warning" in content
274 assert "error" in content
275 assert "deprecate" in content
276 assert len(logs) == 6
277
278 # The file is automatically cleaned up afterwards
279 assert not os.path.isfile(str(log_file))
280
281 # Verify that we did not lose our effective log level even though
282 # the above steps the level up for the duration of the capture
283 assert logger.getEffectiveLevel() == logging.CRITICAL
284
285 logger.setLevel(logging.TRACE)
286 with LogCapture(path=str(log_file), level=logging.DEBUG) as fp:
287 # The file will exit now
288 assert os.path.isfile(str(log_file))
289
290 logger.trace("trace")
291 logger.debug("debug")
292 logger.info("info")
293 logger.warning("warning")
294 logger.error("error")
295 logger.deprecate("deprecate")
296
297 content = fp.read().rstrip()
298 logs = re.split(r"\r*\n", content)
299
300 # We have a log entry for 5 of the log entries we generated above
301 # There will be no 'trace' entry
302 assert "trace" not in content
303 assert "debug" in content
304 assert "info" in content
305 assert "warning" in content
306 assert "error" in content
307 assert "deprecate" in content
308
309 assert len(logs) == 5
310
311 # Concurrent file access is not possible on Windows.
312 # PermissionError: [WinError 32] The process cannot access the file
313 # because it is being used by another process.
314 if sys.platform != "win32":
315 # Remove our file before we exit the with clause
316 # this causes our delete() call to throw gracefully inside
317 os.unlink(str(log_file))
318
319 # Verify file is gone
320 assert not os.path.isfile(str(log_file))
321
322 # Verify that we did not lose our effective log level even though
323 # the above steps the level up for the duration of the capture
324 assert logger.getEffectiveLevel() == logging.TRACE
325
326 logger.setLevel(logging.ERROR)
327 with LogCapture(
328 path=str(log_file), delete=False, level=logging.WARNING
329 ) as fp:
330 # Verify exists
331 assert os.path.isfile(str(log_file))
332
333 logger.trace("trace")
334 logger.debug("debug")
335 logger.info("info")
336 logger.warning("warning")
337 logger.error("error")
338 logger.deprecate("deprecate")
339
340 content = fp.read().rstrip()
341 logs = re.split(r"\r*\n", content)
342
343 # We have a log entry for 3 of the log entries we generated above
344 # There will be no 'trace', 'debug', or 'info' entry
345 assert "trace" not in content
346 assert "debug" not in content
347 assert "info" not in content
348 assert "warning" in content
349 assert "error" in content
350 assert "deprecate" in content
351
352 assert len(logs) == 3
353
354 # Verify the file still exists (because delete was set to False)
355 assert os.path.isfile(str(log_file))
356
357 # remove it now
358 os.unlink(str(log_file))
359
360 # Enure it's been removed
361 assert not os.path.isfile(str(log_file))
362
363 # Set a global level of ERROR
364 logger.setLevel(logging.ERROR)
365
366 # Test case where we can't open the file
367 with (
368 mock.patch("builtins.open", side_effect=OSError()),
369 # Use the default level of None (by not specifying one); we then
370 # use whatever has been defined globally
371 pytest.raises(OSError),
372 LogCapture(path=str(log_file)) as fp,
373 ):
374 # we'll never get here because we'll fail to open the file
375 pass
376
377 # Disable Logging
378 logging.disable(logging.CRITICAL)
379
380
381 @mock.patch("requests.request")
382 def test_apprise_secure_logging(mock_request):
383 """
384 API: Apprise() secure logging tests
385 """
386
387 # Ensure we're not running in a disabled state
388 logging.disable(logging.NOTSET)
389
390 logger.setLevel(logging.CRITICAL)
391
392 # Prepare Mock
393 mock_request.return_value = requests.Request()
394 mock_request.return_value.status_code = requests.codes.ok
395
396 # Default Secure Logging is set to enabled
397 asset = AppriseAsset()
398 assert asset.secure_logging is True
399
400 # Load our asset
401 a = Apprise(asset=asset)
402
403 with LogCapture(level=logging.DEBUG) as stream:
404 # add a test service
405 assert a.add("json://user:pass1$-3!@localhost") is True
406
407 # Our services should carry this flag
408 assert a[0].asset.secure_logging is True
409
410 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
411 assert len(logs) == 1
412 entry = re.split(r"\s-\s", logs[0])
413 assert len(entry) == 3
414 assert entry[1] == "DEBUG"
415 assert entry[2].startswith(
416 "Loaded JSON URL: json://user:****@localhost/"
417 )
418
419 # Send notification
420 assert bool(a.notify("test")) is True
421
422 # Test our call count
423 assert mock_request.call_count == 1
424
425 # Reset
426 mock_request.reset_mock()
427
428 # Now we test the reverse configuration and turn off
429 # secure logging.
430
431 # Default Secure Logging is set to disable
432 asset = AppriseAsset(secure_logging=False)
433 assert asset.secure_logging is False
434
435 # Load our asset
436 a = Apprise(asset=asset)
437
438 with LogCapture(level=logging.DEBUG) as stream:
439 # add a test service
440 assert a.add("json://user:pass1$-3!@localhost") is True
441
442 # Our services should carry this flag
443 assert a[0].asset.secure_logging is False
444
445 logs = re.split(r"\r*\n", stream.getvalue().rstrip())
446 assert len(logs) == 1
447 entry = re.split(r"\s-\s", logs[0])
448 assert len(entry) == 3
449 assert entry[1] == "DEBUG"
450
451 # Note that our password is no longer escaped (it is however
452 # url encoded)
453 assert entry[2].startswith(
454 "Loaded JSON URL: json://user:pass1%24-3%21@localhost/"
455 )
456
457 # Disable Logging
458 logging.disable(logging.CRITICAL)
459
460
461 class _DummyNotify(NotifyBase):
462 """Minimal plugin used to exercise _ServiceLogCapture directly."""
463
464 service_name = "dummy"
465
466 def url(self, privacy=False, *args, **kwargs):
467 """Return a stable URL for assertions that only need an identity."""
468 return "dummy://"
469
470 def send(self, *args, **kwargs):
471 """Pretend the notification was delivered successfully."""
472 return True
473
474
475 def test_notify_log_entry_equality_and_hash():
476 """Two entries are equal (and hash equally) only when their time,
477 level, and message all match."""
478 t = datetime(2026, 1, 1, tzinfo=timezone.utc)
479
480 a = NotifyLogEntry(level="WARNING", message="hi", time=t)
481 b = NotifyLogEntry(level="WARNING", message="hi", time=t)
482 diff_level = NotifyLogEntry(level="ERROR", message="hi", time=t)
483 diff_message = NotifyLogEntry(level="WARNING", message="bye", time=t)
484
485 assert a == b
486 assert hash(a) == hash(b)
487 assert a != diff_level
488 assert a != diff_message
489 assert a != "not a NotifyLogEntry"
490
491
492 def test_notify_log_entry_ordering_by_time():
493 """Entries sort by time alone -- every relational operator is
494 defined directly against time (see the class docstring)."""
495 early = NotifyLogEntry(
496 level="WARNING",
497 message="first",
498 time=datetime(2026, 1, 1, tzinfo=timezone.utc),
499 )
500 late = NotifyLogEntry(
501 level="ERROR",
502 message="second",
503 time=datetime(2026, 1, 2, tzinfo=timezone.utc),
504 )
505
506 assert early < late
507 assert late > early
508 assert early <= late
509 assert late >= early
510 assert sorted([late, early]) == [early, late]
511
512
513 def test_notify_log_entry_equal_time_ordering():
514 """Two different (unequal) entries sharing the same timestamp must
515 never both compare greater than each other.
516
517 Equality compares the full entry; ordering compares timestamps only.
518 """
519 t = datetime(2026, 1, 1, tzinfo=timezone.utc)
520 a = NotifyLogEntry(level="WARNING", message="alpha", time=t)
521 b = NotifyLogEntry(level="ERROR", message="beta", time=t)
522
523 assert a != b
524 assert not (a > b and b > a)
525 assert not (a < b)
526 assert not (b < a)
527 assert a <= b
528 assert b <= a
529 assert a >= b
530 assert b >= a
531
532
533 def test_notify_log_entry_combine_and_sort_across_calls():
534 """Entries captured across separate notify() calls (potentially for
535 different plugins) can be combined into one set and replayed back
536 in chronological order -- the scenario this supports directly."""
537 call_a = [
538 NotifyLogEntry(
539 level="WARNING",
540 message="from service A",
541 time=datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
542 )
543 ]
544 call_b = [
545 NotifyLogEntry(
546 level="ERROR",
547 message="from service B",
548 time=datetime(2026, 1, 1, 11, 0, 0, tzinfo=timezone.utc),
549 ),
550 # A duplicate of call_a's entry -- should collapse in a set.
551 NotifyLogEntry(
552 level="WARNING",
553 message="from service A",
554 time=datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
555 ),
556 ]
557
558 combined = sorted(set(call_a) | set(call_b))
559
560 assert len(combined) == 2
561 assert combined[0].message == "from service B"
562 assert combined[1].message == "from service A"
563
564
565 def test_notify_log_entry_ordering_notimplemented():
566 """Comparing to a non-NotifyLogEntry returns NotImplemented for
567 every relational operator."""
568 entry = NotifyLogEntry(level="WARNING", message="hi")
569
570 assert entry.__lt__("nope") is NotImplemented
571 assert entry.__le__("nope") is NotImplemented
572 assert entry.__gt__("nope") is NotImplemented
573 assert entry.__ge__("nope") is NotImplemented
574
575
576 def test_notify_log_entry_asdict_json_repr():
577 """asdict(), json(), and repr() all render the entry consistently."""
578 t = datetime(2026, 1, 1, 12, 30, 0, tzinfo=timezone.utc)
579 entry = NotifyLogEntry(level="WARNING", message="hi", time=t)
580
581 d = entry.asdict()
582 assert d == {
583 "level": "WARNING",
584 "message": "hi",
585 "time": t.strftime(AWARE_DATE_ISO_FORMAT),
586 }
587
588 assert json.loads(entry.json()) == d
589
590 assert repr(entry) == (
591 f"<NotifyLogEntry level='WARNING' message='hi' time={t!r}>"
592 )
593
594
595 def test_service_log_capture_keeps_all_entries():
596 """Captures remain complete beyond the former 5,000-entry boundary."""
597 service = _DummyNotify()
598 with _ServiceLogCapture(service) as cap:
599 for index in range(5001):
600 record = logging.LogRecord(
601 "apprise",
602 logging.WARNING,
603 __file__,
604 0,
605 "entry %d",
606 (index,),
607 None,
608 )
609 cap.handle(record)
610
611 assert len(cap.entries) == 5001
612 assert cap.entries[-1].message == "entry 5000"
613
614
615 def test_result_log_store_spills_to_disk_in_order():
616 """A bounded capture reads disk-backed entries in their original order."""
617 budget = _LogCaptureBudget(memory_size=1, disk_size=4096)
618 store = _NotifyLogStore(budget)
619 entries = [
620 NotifyLogEntry("WARNING", "first"),
621 NotifyLogEntry("ERROR", "second"),
622 ]
623
624 for entry in entries:
625 store.append(entry)
626
627 assert store._memory == []
628 assert store._disk_count == 2
629 assert len(store) == 2
630 assert store == entries
631 assert store[0] == entries[0]
632 assert store[:] == entries
633 store.close()
634 assert budget._disk is None
635
636
637 def test_result_log_store_stays_on_disk_after_large_entry():
638 """A smaller entry cannot move ahead of one already stored on disk."""
639 entries = [
640 NotifyLogEntry("WARNING", "first " + ("x" * 256)),
641 NotifyLogEntry("ERROR", "second"),
642 ]
643
644 # Only the second entry fits in memory when considered by itself.
645 memory_size = _LogCaptureBudget._HEADER.size + len(
646 entries[1].json().encode("utf-8")
647 )
648 budget = _LogCaptureBudget(memory_size=memory_size, disk_size=4096)
649 store = _NotifyLogStore(budget)
650
651 for entry in entries:
652 store.append(entry)
653
654 # Once the first entry spills, later entries remain behind it on disk.
655 assert store._memory == []
656 assert store._disk_count == 2
657 assert list(store) == entries
658 store.close()
659 assert budget._disk is None
660
661
662 def test_result_log_store_uses_unbounded_memory_without_disk():
663 """The library default retains all logs in memory without a temp file."""
664 store = _NotifyLogStore(_LogCaptureBudget(memory_size=1, disk_size=0))
665 entry = NotifyLogEntry("WARNING", "kept in memory")
666
667 store.append(entry)
668
669 assert list(store) == [entry]
670 assert store._budget._disk is None
671
672
673 def test_result_log_stores_share_one_temporary_file():
674 """All captures in one notification share a single temporary file."""
675 budget = _LogCaptureBudget(memory_size=4096, disk_size=4096)
676 memory_store = _NotifyLogStore(budget)
677 disk_store = _NotifyLogStore(budget)
678
679 memory_store.append(NotifyLogEntry("WARNING", "memory"))
680 budget.memory_used = budget.memory_size
681 disk_store.append(NotifyLogEntry("WARNING", "disk"))
682
683 assert len(memory_store._memory) == 1
684 assert disk_store._disk_count == 1
685 disk = budget._disk
686 memory_store.close()
687 assert budget._disk is disk
688 disk_store.close()
689 assert budget._disk is None
690
691
692 def test_result_log_store_reports_capacity_once(caplog):
693 """A full store adds one warning while live callbacks remain unaffected."""
694 logging.disable(logging.NOTSET)
695 caplog.set_level(logging.WARNING, logger=logger.name)
696 received = []
697
698 try:
699 with _ServiceLogCapture(
700 service=None,
701 log_callback=lambda entry, service: received.append(entry),
702 memory_size=0,
703 disk_size=1,
704 ) as cap:
705 logger.warning("first")
706 logger.warning("second")
707 finally:
708 logging.disable(logging.CRITICAL)
709
710 assert [entry.message for entry in received] == ["first", "second"]
711 assert [entry.message for entry in cap.entries] == [
712 _NotifyLogStore._LIMIT_MESSAGE
713 ]
714 assert caplog.text.count(_NotifyLogStore._LIMIT_MESSAGE) == 1
715
716
717 def test_result_log_store_handles_disk_failure(caplog):
718 """Temporary-file failures are logged and contained."""
719 logging.disable(logging.NOTSET)
720 caplog.set_level(logging.DEBUG, logger=logger.name)
721 store = _NotifyLogStore(_LogCaptureBudget(memory_size=0, disk_size=1024))
722
723 try:
724 with mock.patch.object(
725 _LOGGER_MODULE.tempfile,
726 "TemporaryFile",
727 side_effect=OSError("no space"),
728 ):
729 store.append(NotifyLogEntry("ERROR", "delivery failed"))
730 finally:
731 logging.disable(logging.CRITICAL)
732
733 assert [entry.message for entry in store] == [
734 _NotifyLogStore._DISK_MESSAGE
735 ]
736 assert "no space" in caplog.text
737
738
739 def test_result_log_store_contains_logging_failure_on_write():
740 """A broken handler cannot expose a result-log write failure."""
741 store = _NotifyLogStore(_LogCaptureBudget(memory_size=0, disk_size=1024))
742
743 with (
744 mock.patch.object(
745 _LOGGER_MODULE.tempfile,
746 "TemporaryFile",
747 side_effect=OSError("no space"),
748 ),
749 mock.patch.object(
750 logger,
751 "log",
752 side_effect=RuntimeError("broken handler"),
753 ),
754 ):
755 # The storage warning remains available even when it cannot be logged.
756 store.append(NotifyLogEntry("ERROR", "delivery failed"))
757
758 assert [entry.message for entry in store] == [
759 _NotifyLogStore._DISK_MESSAGE
760 ]
761 store.close()
762
763
764 @pytest.mark.parametrize("failed_write", (1, 2, 5))
765 def test_result_log_store_handles_short_writes(failed_write):
766 """Short header, entry, and link writes are contained."""
767
768 class ShortWriteFile(io.BytesIO):
769 """Return one short write at the requested call."""
770
771 def __init__(self):
772 super().__init__()
773 self.calls = 0
774
775 def write(self, value):
776 self.calls += 1
777 if self.calls == failed_write:
778 super().write(value[:-1])
779 return len(value) - 1
780 return super().write(value)
781
782 budget = _LogCaptureBudget(memory_size=0, disk_size=4096)
783 store = _NotifyLogStore(budget)
784 with mock.patch.object(
785 _LOGGER_MODULE.tempfile,
786 "TemporaryFile",
787 return_value=ShortWriteFile(),
788 ):
789 # The first record covers header and payload writes.
790 store.append(NotifyLogEntry("WARNING", "first"))
791 if failed_write == 5:
792 # A second record reaches the write that links both records.
793 store.append(NotifyLogEntry("WARNING", "second"))
794
795 assert store._notice.message == _NotifyLogStore._DISK_MESSAGE
796 assert budget.disk_failed is True
797 store.close()
798
799
800 @pytest.mark.parametrize("corruption", ("header", "size", "payload", "chain"))
801 def test_result_log_store_handles_unreadable_data(corruption, caplog):
802 """Corrupt temporary data is logged instead of escaping iteration."""
803 logging.disable(logging.NOTSET)
804 caplog.set_level(logging.WARNING, logger=logger.name)
805 budget = _LogCaptureBudget(memory_size=0, disk_size=4096)
806 store = _NotifyLogStore(budget)
807 store.append(NotifyLogEntry("WARNING", "first"))
808 if corruption == "chain":
809 store.append(NotifyLogEntry("WARNING", "second"))
810
811 disk = budget._disk
812 if corruption == "header":
813 # Leave too few bytes to form a complete record header.
814 disk.seek(0)
815 disk.truncate(1)
816 elif corruption == "size":
817 # Claim a size that can never fit within this capture's limit.
818 disk.seek(0)
819 disk.write(budget._HEADER.pack(budget.disk_size + 1, budget._END))
820 elif corruption == "payload":
821 # Keep the header but remove most of the promised content.
822 disk.seek(0)
823 disk.truncate(budget._HEADER.size + 1)
824 else:
825 # End the chain while the store still expects another record.
826 disk.seek(budget._LINK.size)
827 disk.write(budget._LINK.pack(budget._END))
828
829 try:
830 list(store)
831 finally:
832 logging.disable(logging.CRITICAL)
833 store.close()
834
835 assert "could not be read" in caplog.text
836
837
838 def test_result_log_store_contains_logging_failure_on_read():
839 """A broken handler cannot expose a result-log read failure."""
840 budget = _LogCaptureBudget(memory_size=0, disk_size=4096)
841 store = _NotifyLogStore(budget)
842 store.append(NotifyLogEntry("WARNING", "first"))
843
844 # Leave too little data for a complete disk record.
845 budget._disk.seek(0)
846 budget._disk.truncate(1)
847
848 with mock.patch.object(
849 logger,
850 "log",
851 side_effect=RuntimeError("broken handler"),
852 ):
853 entries = list(store)
854
855 # Iteration still returns a useful warning to the caller.
856 assert [entry.message for entry in entries] == [
857 _NotifyLogStore._READ_MESSAGE
858 ]
859 store.close()
860
861
862 def test_result_log_store_handles_close_failure(caplog):
863 """Temporary-file close failures are logged and contained."""
864
865 class CloseFailFile(io.BytesIO):
866 """Raise when temporary storage is closed."""
867
868 failed = False
869
870 def close(self):
871 if not self.failed:
872 self.failed = True
873 raise OSError("close failed")
874 super().close()
875
876 logging.disable(logging.NOTSET)
877 caplog.set_level(logging.DEBUG, logger=logger.name)
878 budget = _LogCaptureBudget(memory_size=0, disk_size=4096)
879 store = _NotifyLogStore(budget)
880 with mock.patch.object(
881 _LOGGER_MODULE.tempfile,
882 "TemporaryFile",
883 return_value=CloseFailFile(),
884 ):
885 store.append(NotifyLogEntry("WARNING", "entry"))
886
887 try:
888 store.close()
889 store.append(NotifyLogEntry("WARNING", "ignored after close"))
890 with pytest.raises(OSError):
891 budget.read(0)
892 finally:
893 logging.disable(logging.CRITICAL)
894
895 assert "close failed" in caplog.text
896
897
898 def test_result_log_store_contains_logging_failure_on_close():
899 """A broken handler cannot expose a result-log cleanup failure."""
900
901 class CloseFailFile(io.BytesIO):
902 """Fail the first close request, like a temporary-file error."""
903
904 failed = False
905
906 def close(self):
907 if not self.failed:
908 self.failed = True
909 raise OSError("close failed")
910
911 super().close()
912
913 budget = _LogCaptureBudget(memory_size=0, disk_size=4096)
914 store = _NotifyLogStore(budget)
915
916 with mock.patch.object(
917 _LOGGER_MODULE.tempfile,
918 "TemporaryFile",
919 return_value=CloseFailFile(),
920 ):
921 store.append(NotifyLogEntry("WARNING", "entry"))
922
923 with mock.patch.object(
924 logger,
925 "log",
926 side_effect=RuntimeError("broken handler"),
927 ):
928 # Cleanup remains safe even when its warning cannot be logged.
929 store.close()
930
931 assert budget._disk is None
932
933
934 def test_result_log_store_sequence_and_repeat_failure_paths():
935 """Sequence comparisons and repeated storage failures stay safe."""
936 budget = _LogCaptureBudget(memory_size=0, disk_size=4096)
937 first = _NotifyLogStore(budget)
938 second = _NotifyLogStore(budget)
939 entry = NotifyLogEntry("WARNING", "entry")
940 first.append(entry)
941 second.append(entry)
942
943 assert budget.claim_warning("one warning") is True
944 assert budget.claim_warning("one warning") is False
945 assert first == second
946 assert first.__eq__(object()) is NotImplemented
947 first._set_notice("first warning", log=False)
948 first._set_notice("ignored warning", log=False)
949 assert first._notice.message == "first warning"
950 first.close()
951 second.close()
952
953 class ConcurrentFailFile(io.BytesIO):
954 """Simulate another writer reporting the same disk failure first."""
955
956 def write(self, value):
957 budget.disk_failed = True
958 raise OSError("shared failure")
959
960 budget = _LogCaptureBudget(memory_size=0, disk_size=4096)
961 store = _NotifyLogStore(budget)
962 budget.claim_warning(_NotifyLogStore._DISK_MESSAGE)
963 with mock.patch.object(
964 _LOGGER_MODULE.tempfile,
965 "TemporaryFile",
966 return_value=ConcurrentFailFile(),
967 ):
968 store.append(entry)
969 assert store._notice.message == _NotifyLogStore._DISK_MESSAGE
970 store.close()
971
972
973 def test_service_captures_share_call_log_budget():
974 """Service captures draw from their enclosing call's storage budget."""
975 service = _DummyNotify()
976 with (
977 _ServiceLogCapture(
978 service=None, memory_size=0, disk_size=4096
979 ) as call_cap,
980 _ServiceLogCapture(service) as service_cap,
981 ):
982 assert service_cap._budget is call_cap._budget
983
984
985 def test_notify_uses_asset_result_log_limits():
986 """Sync and async notifications apply their asset's shared log limits."""
987 logging.disable(logging.NOTSET)
988
989 class _WarnNotify(_DummyNotify):
990 """Emit one retained warning during delivery."""
991
992 def send(self, *args, **kwargs):
993 """Log a warning and report success."""
994 self.logger.warning("stored on disk")
995 return True
996
997 try:
998 for use_async in (False, True):
999 asset = AppriseAsset(
1000 result_log_memory_size=0, result_log_disk_size=4096
1001 )
1002 instance = Apprise(asset=asset)
1003 assert instance.add(_WarnNotify(asset=asset))
1004
1005 result = (
1006 asyncio.run(instance.async_notify("body"))
1007 if use_async
1008 else instance.notify("body")
1009 )
1010 attempt_logs = result.results[0].attempts[0].logs
1011 assert attempt_logs._disk_count == 1
1012 assert [entry.message for entry in result.logs()] == [
1013 "stored on disk"
1014 ]
1015 result.close()
1016 finally:
1017 logging.disable(logging.CRITICAL)
1018
1019
1020 def test_service_log_capture_exit_without_enter():
1021 """__exit__ tolerates being called when __enter__ never ran, and
1022 skips the contextvar reset since there is no token to restore."""
1023 service = _DummyNotify()
1024 cap = _ServiceLogCapture(service)
1025 assert cap._token is None
1026
1027 # Must not raise even though __enter__ was never called.
1028 cap.__exit__(None, None, None)
1029
1030
1031 def test_service_log_capture_bad_format():
1032 """A plugin's own malformed logging call must not escape capture."""
1033 service = _DummyNotify()
1034 with _ServiceLogCapture(service) as cap:
1035 # Only one arg supplied for two required by the format string --
1036 # this must not raise back out of handle().
1037 cap.handle(
1038 logging.LogRecord(
1039 name="apprise",
1040 level=logging.WARNING,
1041 pathname=__file__,
1042 lineno=1,
1043 msg="missing %s %s",
1044 args=("one",),
1045 exc_info=None,
1046 )
1047 )
1048 cap.handle(
1049 logging.LogRecord(
1050 name="apprise",
1051 level=logging.WARNING,
1052 pathname=__file__,
1053 lineno=2,
1054 msg="a real one: %s",
1055 args=("fine",),
1056 exc_info=None,
1057 )
1058 )
1059
1060 assert len(cap.entries) == 1
1061 assert cap.entries[0].message == "a real one: fine"
1062
1063
1064 def test_service_log_capture_async_send_warning():
1065 """The default async_notify() path captures warnings logged in send()."""
1066 logging.disable(logging.NOTSET)
1067
1068 class _WarnOnSend(_DummyNotify):
1069 """Dummy service that logs during send()."""
1070
1071 def send(self, *args, **kwargs):
1072 """Emit one warning before reporting success."""
1073 self.logger.warning("a warning from send()")
1074 return True
1075
1076 async def _run():
1077 """Run async_notify() under a capture context."""
1078 service = _WarnOnSend()
1079 with _ServiceLogCapture(service) as cap:
1080 result = await service.async_notify(body="x")
1081 return result, cap.entries
1082
1083 try:
1084 result, entries = asyncio.run(_run())
1085 finally:
1086 logging.disable(logging.CRITICAL)
1087
1088 assert result is True
1089 assert len(entries) == 1
1090 assert entries[0].message == "a warning from send()"
1091
1092
1093 def test_service_log_capture_async_concurrent_isolation():
1094 """Concurrent async captures keep each service's logs separate."""
1095 logging.disable(logging.NOTSET)
1096
1097 class _WarnOnSend(_DummyNotify):
1098 """Dummy service that can stagger warning emission."""
1099
1100 def __init__(self, tag_message, delay=0.0, **kwargs):
1101 """Store the warning message and optional delay."""
1102 super().__init__(**kwargs)
1103 self._tag_message = tag_message
1104 self._delay = delay
1105
1106 def send(self, *args, **kwargs):
1107 """Emit this service's distinct warning."""
1108 if self._delay:
1109 time.sleep(self._delay)
1110 self.logger.warning(self._tag_message)
1111 return True
1112
1113 async def _run_one(service):
1114 """Capture one async service call."""
1115 with _ServiceLogCapture(service) as cap:
1116 await service.async_notify(body="x")
1117 return [e.message for e in cap.entries]
1118
1119 async def _run():
1120 """Run two captures at the same time."""
1121 a = _WarnOnSend("warning from A")
1122 b = _WarnOnSend("warning from B", delay=0.05)
1123 return await asyncio.gather(_run_one(a), _run_one(b))
1124
1125 try:
1126 results = asyncio.run(_run())
1127 finally:
1128 logging.disable(logging.CRITICAL)
1129
1130 assert results == [["warning from A"], ["warning from B"]]
1131
1132
1133 def test_service_log_capture_thread_isolation():
1134 """Threaded captures keep each service's logs separate."""
1135 logging.disable(logging.NOTSET)
1136
1137 class _WarnOnSend(_DummyNotify):
1138 """Dummy service that can stagger warning emission in threads."""
1139
1140 def __init__(self, tag_message, delay=0.0, **kwargs):
1141 """Store the warning message and optional delay."""
1142 super().__init__(**kwargs)
1143 self._tag_message = tag_message
1144 self._delay = delay
1145
1146 def send(self, *args, **kwargs):
1147 """Emit this service's distinct warning."""
1148 if self._delay:
1149 time.sleep(self._delay)
1150 self.logger.warning(self._tag_message)
1151 return True
1152
1153 def _run_one(service):
1154 """Capture one threaded service call."""
1155 with _ServiceLogCapture(service) as cap:
1156 service.notify(body="x")
1157 return [e.message for e in cap.entries]
1158
1159 try:
1160 a = _WarnOnSend("warning from A")
1161 b = _WarnOnSend("warning from B", delay=0.05)
1162 with cf.ThreadPoolExecutor() as ex:
1163 fut_a = ex.submit(_run_one, a)
1164 fut_b = ex.submit(_run_one, b)
1165 result_a, result_b = fut_a.result(), fut_b.result()
1166 finally:
1167 logging.disable(logging.CRITICAL)
1168
1169 assert result_a == ["warning from A"]
1170 assert result_b == ["warning from B"]
1171
1172
1173 def test_call_capture_uses_separate_context():
1174 """Call and service captures use separate context markers."""
1175 with _ServiceLogCapture(service=None) as cap:
1176 assert _active_capture.get() is None
1177 assert _active_call_capture.get() is cap
1178 assert cap._token is None
1179
1180
1181 def test_call_capture_records_shared_logs():
1182 """A call capture stores unclaimed shared-logger records."""
1183 logging.disable(logging.NOTSET)
1184
1185 try:
1186 with _ServiceLogCapture(service=None) as cap:
1187 logger.warning("no services to notify")
1188 finally:
1189 logging.disable(logging.CRITICAL)
1190
1191 assert [e.message for e in cap.entries] == ["no services to notify"]
1192
1193
1194 def test_call_capture_defers_to_service():
1195 """A call capture ignores records owned by a service capture."""
1196 logging.disable(logging.NOTSET)
1197 service = _DummyNotify()
1198
1199 try:
1200 with _ServiceLogCapture(service=None) as call_cap:
1201 logger.warning("before service window")
1202
1203 with _ServiceLogCapture(service) as svc_cap:
1204 service.logger.warning("during service window")
1205
1206 logger.warning("after service window")
1207 finally:
1208 logging.disable(logging.CRITICAL)
1209
1210 assert [e.message for e in call_cap.entries] == [
1211 "before service window",
1212 "after service window",
1213 ]
1214 assert [e.message for e in svc_cap.entries] == ["during service window"]
1215
1216
1217 def test_call_capture_callback_has_no_service():
1218 """Call-level callbacks receive ``service=None``."""
1219 logging.disable(logging.NOTSET)
1220 received = []
1221
1222 def _cb(entry, service):
1223 """Record the (message, service) pair delivered live."""
1224 received.append((entry.message, service))
1225
1226 try:
1227 with _ServiceLogCapture(service=None, log_callback=_cb) as cap:
1228 logger.warning("orchestration message")
1229 finally:
1230 logging.disable(logging.CRITICAL)
1231
1232 assert received == [("orchestration message", None)]
1233 assert [e.message for e in cap.entries] == ["orchestration message"]
1234
1235
1236 def test_call_capture_keeps_concurrent_logs():
1237 """A call capture keeps concurrent entries without loss."""
1238 logging.disable(logging.NOTSET)
1239
1240 n_per_thread = 200
1241 barrier = threading.Barrier(4)
1242
1243 def _hammer(tag):
1244 """Log many messages from one thread, all starting together."""
1245 barrier.wait()
1246 for i in range(n_per_thread):
1247 logger.warning("%s-%d", tag, i)
1248
1249 try:
1250 with (
1251 _ServiceLogCapture(service=None) as cap,
1252 cf.ThreadPoolExecutor(max_workers=4) as ex,
1253 ):
1254 futures = [
1255 ex.submit(contextvars.copy_context().run, _hammer, tag)
1256 for tag in ("A", "B", "C", "D")
1257 ]
1258 for future in futures:
1259 future.result()
1260 finally:
1261 logging.disable(logging.CRITICAL)
1262
1263 messages = sorted(e.message for e in cap.entries)
1264 expected = sorted(
1265 f"{tag}-{i}"
1266 for tag in ("A", "B", "C", "D")
1267 for i in range(n_per_thread)
1268 )
1269 assert messages == expected
1270
1271
1272 def test_call_capture_blocks_recursive_callback():
1273 """A callback cannot recursively capture its own log message."""
1274 logging.disable(logging.NOTSET)
1275 received = []
1276
1277 def _reentrant_cb(entry, service):
1278 """Try to log again through the same handler while still
1279 inside the first entry's own callback."""
1280 received.append(entry.message)
1281 if entry.message == "first":
1282 logger.warning("triggered from callback")
1283
1284 try:
1285 with _ServiceLogCapture(
1286 service=None, log_callback=_reentrant_cb
1287 ) as cap:
1288 logger.warning("first")
1289 finally:
1290 logging.disable(logging.CRITICAL)
1291
1292 # The reentrant call is swallowed by _in_emit, not processed as a
1293 # second entry or a second callback invocation.
1294 assert [e.message for e in cap.entries] == ["first"]
1295 assert received == ["first"]
1296
1297
1298 def test_callback_error_contains_logging_failure():
1299 """A broken handler cannot expose a callback failure."""
1300 logging.disable(logging.NOTSET)
1301
1302 def _broken_callback(_entry, _service):
1303 """Represent application callback code that unexpectedly fails."""
1304 raise RuntimeError("callback failed")
1305
1306 try:
1307 with (
1308 mock.patch.object(
1309 logger,
1310 "log",
1311 side_effect=RuntimeError("broken handler"),
1312 ),
1313 _ServiceLogCapture(
1314 service=None,
1315 log_callback=_broken_callback,
1316 ) as cap,
1317 ):
1318 # The original log call and notification flow both continue.
1319 logger.warning("first")
1320
1321 finally:
1322 logging.disable(logging.CRITICAL)
1323
1324 assert [entry.message for entry in cap.entries] == ["first"]
1325
1326
1327 def test_call_captures_are_thread_isolated():
1328 """Concurrent call captures do not receive each other's entries."""
1329 logging.disable(logging.NOTSET)
1330 barrier = threading.Barrier(2)
1331
1332 def _capture(message):
1333 with _ServiceLogCapture(service=None) as cap:
1334 barrier.wait()
1335 logger.warning(message)
1336 return [entry.message for entry in cap.entries]
1337
1338 try:
1339 with cf.ThreadPoolExecutor(max_workers=2) as executor:
1340 first = executor.submit(_capture, "first")
1341 second = executor.submit(_capture, "second")
1342 assert first.result() == ["first"]
1343 assert second.result() == ["second"]
1344 finally:
1345 logging.disable(logging.CRITICAL)
1346
1347
1348 def test_service_log_capture_sync_log_callback():
1349 """A plain log_callback receives each captured entry live."""
1350 logging.disable(logging.NOTSET)
1351 received = []
1352
1353 def _cb(entry, service):
1354 """Record callback delivery in the order entries are emitted."""
1355 received.append((service.service_name, entry.message))
1356
1357 try:
1358 service = _DummyNotify()
1359 with _ServiceLogCapture(service, log_callback=_cb) as cap:
1360 service.logger.warning("first")
1361 service.logger.warning("second")
1362 finally:
1363 logging.disable(logging.CRITICAL)
1364
1365 assert received == [
1366 ("dummy", "first"),
1367 ("dummy", "second"),
1368 ]
1369 assert [e.message for e in cap.entries] == ["first", "second"]
1370
1371
1372 def test_service_log_capture_callback_error():
1373 """A raising log_callback must not break capture."""
1374 logging.disable(logging.NOTSET)
1375
1376 def _broken_cb(entry, service):
1377 """Raise from the callback."""
1378 raise ValueError("boom")
1379
1380 try:
1381 service = _DummyNotify()
1382 with _ServiceLogCapture(service, log_callback=_broken_cb) as cap:
1383 # Must not raise back out to the caller.
1384 service.logger.warning("still captured")
1385 finally:
1386 logging.disable(logging.CRITICAL)
1387
1388 assert [e.message for e in cap.entries] == ["still captured"]
1389
1390
1391 def test_service_log_capture_rejects_async_callback(caplog):
1392 """Reject an async callback without losing the captured warning."""
1393 # Older pytest releases may leave logging disabled after another test.
1394 logging.disable(logging.NOTSET)
1395 caplog.set_level(logging.WARNING, logger=logger.name)
1396
1397 async def _cb(entry, service):
1398 """A callback mistakenly defined as async; body never runs."""
1399 pass # pragma: no cover -- the coroutine is closed, not awaited
1400
1401 try:
1402 service = _DummyNotify()
1403 with _ServiceLogCapture(service, log_callback=_cb) as cap:
1404 service.logger.warning("service warning")
1405 finally:
1406 logging.disable(logging.CRITICAL)
1407
1408 assert [e.message for e in cap.entries] == ["service warning"]
1409 assert "must be synchronous" in caplog.text