Debian Codegraph @

tests/test_result.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 from datetime import datetime, timezone
30 from io import StringIO
31 from json import loads
32 import logging
33
34 from apprise.common import AWARE_DATE_ISO_FORMAT
35 from apprise.logger import NotifyLogEntry
36 from apprise.result import (
37 AppriseResult,
38 AppriseResultStatus,
39 NotifyAttempt,
40 NotifyResult,
41 )
42
43 logging.disable(logging.CRITICAL)
44
45
46 def _json_data(value):
47 """Decode one result object's bounded JSON iterator for assertions."""
48 return loads("".join(value.iter_json()))
49
50
51 def test_notify_log_entry():
52 """NotifyLogEntry: attributes, asdict(), json(), __str__/__repr__."""
53
54 entry = NotifyLogEntry(level="WARNING", message="HTTP 403 Forbidden")
55
56 assert entry.level == "WARNING"
57 assert entry.message == "HTTP 403 Forbidden"
58 assert entry.time.tzinfo is not None
59 assert entry.asdict() == {
60 "level": "WARNING",
61 "message": "HTTP 403 Forbidden",
62 "time": entry.time.strftime(AWARE_DATE_ISO_FORMAT),
63 }
64 assert loads(entry.json()) == entry.asdict()
65 # __str__ mirrors Python logging's own default format:
66 # "%(asctime)s - %(levelname)s - %(message)s".
67 expected_asctime = "{},{:03d}".format(
68 entry.time.strftime("%Y-%m-%d %H:%M:%S"),
69 entry.time.microsecond // 1000,
70 )
71 assert str(entry) == (f"{expected_asctime} - WARNING - HTTP 403 Forbidden")
72 assert "WARNING" in repr(entry)
73 assert "HTTP 403 Forbidden" in repr(entry)
74
75
76 def test_notify_log_entry_time_defaults_to_now():
77 """NotifyLogEntry.time defaults to now() when constructed directly
78 (e.g. in tests) without an explicit time= from a real LogRecord."""
79
80 before = datetime.now(timezone.utc)
81 entry = NotifyLogEntry(level="WARNING", message="test")
82 after = datetime.now(timezone.utc)
83
84 assert before <= entry.time <= after
85
86
87 def test_notify_log_entry_explicit_time():
88 """NotifyLogEntry accepts an explicit time=, as _ServiceLogCapture.emit()
89 does from the underlying LogRecord's own timestamp."""
90
91 when = datetime(2026, 1, 1, tzinfo=timezone.utc)
92 entry = NotifyLogEntry(level="ERROR", message="test", time=when)
93
94 assert entry.time == when
95
96
97 def test_notify_attempt_defaults():
98 """NotifyAttempt: default construction requires only status."""
99
100 attempt = NotifyAttempt(status=AppriseResultStatus.SUCCESS)
101
102 assert attempt.status == AppriseResultStatus.SUCCESS
103 assert attempt.elapsed == 0.0
104 assert attempt.logs == []
105 assert bool(attempt) is True
106
107
108 def test_notify_attempt_bool_matches_status():
109 """NotifyAttempt.__bool__ is True only for status=SUCCESS -- raw,
110 never adjusted for optional=."""
111
112 success = NotifyAttempt(status=AppriseResultStatus.SUCCESS)
113 failure = NotifyAttempt(status=AppriseResultStatus.FAILURE)
114 timeout = NotifyAttempt(status=AppriseResultStatus.TIMEOUT)
115
116 assert bool(success) is True
117 assert bool(failure) is False
118 assert bool(timeout) is False
119
120
121 def test_notify_attempt_start_end_time_match_elapsed():
122 """start_time/end_time are always populated and their difference is
123 exactly elapsed -- by construction, not by measurement, so there is
124 no separate clock to drift out of sync."""
125
126 before = datetime.now(timezone.utc)
127 attempt = NotifyAttempt(status=AppriseResultStatus.SUCCESS, elapsed=3.5)
128 after = datetime.now(timezone.utc)
129
130 assert attempt.start_time.tzinfo is not None
131 assert attempt.end_time.tzinfo is not None
132 assert (attempt.end_time - attempt.start_time).total_seconds() == 3.5
133 assert before <= attempt.end_time <= after
134 parsed = datetime.strptime(
135 _json_data(attempt)["start_time"], AWARE_DATE_ISO_FORMAT
136 )
137 assert parsed == attempt.start_time
138
139
140 def test_notify_attempt_iterates_logs():
141 """NotifyAttempt iterates directly over its own captured log entries."""
142
143 logs = [
144 NotifyLogEntry(level="WARNING", message="rate limited"),
145 NotifyLogEntry(level="ERROR", message="invalid token"),
146 ]
147 attempt = NotifyAttempt(
148 status=AppriseResultStatus.FAILURE, elapsed=0.2, logs=logs
149 )
150
151 assert list(attempt) == logs
152 messages = [str(entry) for entry in attempt]
153 assert " - WARNING - rate limited" in messages[0]
154 assert " - ERROR - invalid token" in messages[1]
155
156
157 def test_notify_attempt_iter_json_and_write_json():
158 """Attempt JSON streams every field and can write to a text stream."""
159
160 logs = [NotifyLogEntry(level="WARNING", message="HTTP 429")]
161 attempt = NotifyAttempt(
162 status=AppriseResultStatus.FAILURE, elapsed=0.5, logs=logs
163 )
164
165 expected = {
166 "status": "FAILURE",
167 "elapsed": 0.5,
168 "start_time": attempt.start_time.strftime(AWARE_DATE_ISO_FORMAT),
169 "end_time": attempt.end_time.strftime(AWARE_DATE_ISO_FORMAT),
170 "logs": [logs[0].asdict()],
171 }
172 output = "".join(attempt.iter_json())
173 assert loads(output) == expected
174 assert ", " not in output
175 assert ": " not in output
176
177 # write_json consumes the same bounded chunks without joining them first.
178 stream = StringIO()
179 attempt.write_json(stream)
180 assert stream.getvalue() == output
181
182
183 def test_notify_attempt_json_reads_disk_logs_lazily():
184 """Creating and starting JSON output does not preload disk-backed logs."""
185 from apprise.logger import _LogCaptureBudget, _NotifyLogStore
186
187 budget = _LogCaptureBudget(memory_size=0, disk_size=4096)
188 logs = _NotifyLogStore(budget)
189 logs.append(NotifyLogEntry(level="WARNING", message="from disk"))
190
191 reads = 0
192 original_read = budget.read
193
194 def tracked_read(offset):
195 """Count actual disk reads while preserving normal behavior."""
196 nonlocal reads
197 reads += 1
198 return original_read(offset)
199
200 budget.read = tracked_read
201 attempt = NotifyAttempt(AppriseResultStatus.FAILURE, logs=logs)
202 chunks = attempt.iter_json()
203
204 # Fixed fields are emitted before iteration reaches the disk log array.
205 first_chunk = next(chunks)
206 assert first_chunk.startswith('{"status":')
207 assert reads == 0
208
209 output = first_chunk + "".join(chunks)
210 assert loads(output)["logs"][0]["message"] == "from disk"
211 assert reads == 1
212 logs.close()
213
214
215 def test_notify_attempt_repr():
216 """NotifyAttempt.__repr__ is a compact, informative one-liner."""
217
218 attempt = NotifyAttempt(status=AppriseResultStatus.TIMEOUT, elapsed=1.2)
219 text = repr(attempt)
220
221 assert "TIMEOUT" in text
222 assert "1.2" in text
223
224
225 def test_notify_result_defaults():
226 """NotifyResult: default construction requires only name/url, and
227 with no attempts given reports FAILURE (nothing ever succeeded)."""
228
229 result = NotifyResult(name="Slack", url="slack://t/ch")
230
231 assert result.name == "Slack"
232 assert result.url == "slack://t/ch"
233 assert result.url_id is None
234 assert result.tag == ()
235 assert result.status == AppriseResultStatus.FAILURE
236 assert bool(result) is False
237 assert result.optional is False
238 assert result.weight == 1
239 assert result.max_attempts == 1
240 assert result.attempts == ()
241 assert len(result) == 0
242 assert result.elapsed == 0.0
243 assert list(result.logs()) == []
244
245
246 def test_notify_result_status_reflects_any_success():
247 """.status is SUCCESS if any attempt succeeded, regardless of earlier
248 failed attempts."""
249
250 result = NotifyResult(
251 name="Slack",
252 url="slack://t/ch",
253 max_attempts=3,
254 attempts=[
255 NotifyAttempt(status=AppriseResultStatus.FAILURE),
256 NotifyAttempt(status=AppriseResultStatus.SUCCESS),
257 ],
258 )
259
260 assert result.status == AppriseResultStatus.SUCCESS
261 assert bool(result) is True
262 assert len(result) == 2
263
264
265 def test_notify_result_status_pure_timeout_no_failure():
266 """.status is TIMEOUT when Apprise gave up waiting without ever
267 seeing a confirmed failure from this service -- e.g. the deadline
268 had already passed before any attempt could even start, or the one
269 attempt made was abandoned mid-flight rather than completing."""
270
271 result = NotifyResult(
272 name="Slack",
273 url="slack://t/ch",
274 attempts=[NotifyAttempt(status=AppriseResultStatus.TIMEOUT)],
275 )
276
277 assert result.status == AppriseResultStatus.TIMEOUT
278 assert bool(result) is False
279
280
281 def test_notify_result_status_failure_trumps_timeout():
282 """.status is FAILURE, not TIMEOUT, when at least one attempt
283 confirmed a real failure before Apprise later gave up waiting on a
284 further retry -- a confirmed failure is more informative than "ran
285 out of time" and takes priority over it."""
286
287 result = NotifyResult(
288 name="Slack",
289 url="slack://t/ch",
290 attempts=[
291 NotifyAttempt(status=AppriseResultStatus.FAILURE),
292 NotifyAttempt(status=AppriseResultStatus.TIMEOUT),
293 ],
294 )
295
296 assert result.status == AppriseResultStatus.FAILURE
297 assert bool(result) is False
298
299
300 def test_notify_result_status_failure_trumps_timeout_multiple_retries():
301 """The same FAILURE-over-TIMEOUT priority holds regardless of how
302 many failed retries preceded the eventual TIMEOUT."""
303
304 result = NotifyResult(
305 name="Slack",
306 url="slack://t/ch",
307 attempts=[
308 NotifyAttempt(status=AppriseResultStatus.FAILURE),
309 NotifyAttempt(status=AppriseResultStatus.FAILURE),
310 NotifyAttempt(status=AppriseResultStatus.FAILURE),
311 NotifyAttempt(status=AppriseResultStatus.TIMEOUT),
312 ],
313 )
314
315 assert result.status == AppriseResultStatus.FAILURE
316
317
318 def test_notify_result_optional_absorbs_failure_trumping_timeout():
319 """optional=True still absorbs a FAILURE-trumps-TIMEOUT outcome into
320 SUCCESS, same as it would a plain FAILURE or a plain TIMEOUT."""
321
322 result = NotifyResult(
323 name="Slack",
324 url="slack://t/ch",
325 optional=True,
326 attempts=[
327 NotifyAttempt(status=AppriseResultStatus.FAILURE),
328 NotifyAttempt(status=AppriseResultStatus.TIMEOUT),
329 ],
330 )
331
332 assert result.status == AppriseResultStatus.SUCCESS
333
334
335 def test_notify_result_status_failure_when_no_timeout_no_success():
336 """.status is FAILURE when every attempt failed outright (no
337 TIMEOUT, no SUCCESS, no optional)."""
338
339 result = NotifyResult(
340 name="Slack",
341 url="slack://t/ch",
342 attempts=[NotifyAttempt(status=AppriseResultStatus.FAILURE)],
343 )
344
345 assert result.status == AppriseResultStatus.FAILURE
346
347
348 def test_notify_result_optional_absorbs_failure():
349 """optional=True remaps a failed outcome's reflective .status to
350 SUCCESS, even though the underlying NotifyAttempt stays raw."""
351
352 result = NotifyResult(
353 name="Slack",
354 url="slack://t/ch",
355 optional=True,
356 attempts=[NotifyAttempt(status=AppriseResultStatus.FAILURE)],
357 )
358
359 assert result.status == AppriseResultStatus.SUCCESS
360 assert bool(result) is True
361 # The raw attempt itself is untouched by optional=.
362 assert next(iter(result)).status == AppriseResultStatus.FAILURE
363
364
365 def test_notify_result_optional_absorbs_timeout():
366 """optional=True also absorbs a TIMEOUT outcome the same way it
367 absorbs a plain FAILURE."""
368
369 result = NotifyResult(
370 name="Slack",
371 url="slack://t/ch",
372 optional=True,
373 attempts=[NotifyAttempt(status=AppriseResultStatus.TIMEOUT)],
374 )
375
376 assert result.status == AppriseResultStatus.SUCCESS
377 assert next(iter(result)).status == AppriseResultStatus.TIMEOUT
378
379
380 def test_notify_result_optional_does_not_mask_success():
381 """optional=True on an already-successful result is a no-op --
382 .status is still simply SUCCESS."""
383
384 result = NotifyResult(
385 name="Slack",
386 url="slack://t/ch",
387 optional=True,
388 attempts=[NotifyAttempt(status=AppriseResultStatus.SUCCESS)],
389 )
390
391 assert result.status == AppriseResultStatus.SUCCESS
392
393
394 def test_notify_result_weight():
395 """.weight defaults to 1 and stores whatever value is given (e.g. a
396 plugin's own target count via len(service))."""
397
398 default = NotifyResult(name="Slack", url="slack://t/ch")
399 fanned_out = NotifyResult(name="Twilio", url="twilio://x", weight=50)
400
401 assert default.weight == 1
402 assert fanned_out.weight == 50
403
404
405 def test_notify_result_max_attempts_ratio():
406 """max_attempts is the configured ceiling; len(result)/.attempts show
407 how many were actually used -- e.g. 1/3 means the first try
408 succeeded."""
409
410 result = NotifyResult(
411 name="Telegram",
412 url="tgram://bot/chat",
413 url_id="abc123",
414 max_attempts=3,
415 attempts=[NotifyAttempt(status=AppriseResultStatus.SUCCESS)],
416 )
417
418 assert result.url_id == "abc123"
419 assert result.max_attempts == 3
420 assert len(result) == 1
421 assert len(result.attempts) == 1
422
423
424 def test_notify_result_start_end_time_span_all_attempts():
425 """start_time is the first attempt's start, end_time is the last
426 attempt's end, and elapsed is the difference between them -- not the
427 sum of each attempt's own elapsed."""
428
429 first = NotifyAttempt(status=AppriseResultStatus.FAILURE, elapsed=1.0)
430 second = NotifyAttempt(status=AppriseResultStatus.SUCCESS, elapsed=1.0)
431 result = NotifyResult(
432 name="Slack", url="slack://t/ch", attempts=[first, second]
433 )
434
435 assert result.start_time == first.start_time
436 assert result.end_time == second.end_time
437 assert result.elapsed == (
438 (second.end_time - first.start_time).total_seconds()
439 )
440
441
442 def test_notify_result_start_end_time_default_when_no_attempts():
443 """With no attempts at all, start_time/end_time still coincide --
444 never left unset."""
445
446 result = NotifyResult(name="Slack", url="slack://t/ch")
447 assert result.start_time == result.end_time
448
449
450 def test_notify_result_iterates_attempts():
451 """NotifyResult iterates over its NotifyAttempt entries, not log
452 lines directly -- use .logs() for a flattened log view."""
453
454 a1 = NotifyAttempt(status=AppriseResultStatus.FAILURE)
455 a2 = NotifyAttempt(status=AppriseResultStatus.SUCCESS)
456 result = NotifyResult(
457 name="Telegram", url="tgram://bot/chat", attempts=[a1, a2]
458 )
459
460 assert list(result) == [a1, a2]
461 assert result.attempts == (a1, a2)
462
463
464 def test_notify_result_logs_flattens_every_attempt_in_order():
465 """NotifyResult.logs() yields every log entry across every attempt,
466 in call order."""
467
468 logs1 = [NotifyLogEntry(level="WARNING", message="rate limited")]
469 logs2 = [NotifyLogEntry(level="ERROR", message="invalid token")]
470 result = NotifyResult(
471 name="Telegram",
472 url="tgram://bot/chat",
473 attempts=[
474 NotifyAttempt(status=AppriseResultStatus.FAILURE, logs=logs1),
475 NotifyAttempt(status=AppriseResultStatus.SUCCESS, logs=logs2),
476 ],
477 )
478
479 assert list(result.logs()) == logs1 + logs2
480
481
482 def test_notify_result_optional_and_tag():
483 """NotifyResult carries the tag tuple and optional flag through."""
484
485 result = NotifyResult(
486 name="Discord",
487 url="discord://w/t",
488 tag=("devops", "alerts"),
489 optional=True,
490 attempts=[NotifyAttempt(status=AppriseResultStatus.FAILURE)],
491 )
492
493 assert result.tag == ("devops", "alerts")
494 assert result.optional is True
495 # Absorbed by optional=True.
496 assert bool(result) is True
497
498
499 def test_notify_result_iter_json_and_write_json():
500 """Service JSON streams every field and its nested attempts."""
501
502 logs = [NotifyLogEntry(level="WARNING", message="HTTP 429")]
503 attempt = NotifyAttempt(
504 status=AppriseResultStatus.FAILURE, elapsed=0.5, logs=logs
505 )
506 result = NotifyResult(
507 name="Telegram",
508 url="tgram://bot/chat",
509 url_id="abc123",
510 tag=("alerts",),
511 optional=False,
512 weight=3,
513 max_attempts=3,
514 attempts=[attempt],
515 )
516
517 expected = {
518 "name": "Telegram",
519 "url": "tgram://bot/chat",
520 "url_id": "abc123",
521 "tag": ["alerts"],
522 "status": "FAILURE",
523 "optional": False,
524 "weight": 3,
525 "max_attempts": 3,
526 "elapsed": result.elapsed,
527 "start_time": result.start_time.strftime(AWARE_DATE_ISO_FORMAT),
528 "end_time": result.end_time.strftime(AWARE_DATE_ISO_FORMAT),
529 "attempts": [_json_data(attempt)],
530 }
531 output = "".join(result.iter_json())
532 assert loads(output) == expected
533 assert ", " not in output
534 assert ": " not in output
535
536 stream = StringIO()
537 result.write_json(stream)
538 assert stream.getvalue() == output
539
540
541 def test_notify_result_repr():
542 """NotifyResult.__repr__ is a compact, informative one-liner."""
543
544 result = NotifyResult(
545 name="Slack",
546 url="slack://t/ch",
547 attempts=[NotifyAttempt(status=AppriseResultStatus.SUCCESS)],
548 )
549 text = repr(result)
550
551 assert "Slack" in text
552 assert "slack://t/ch" in text
553 assert "SUCCESS" in text
554
555
556 def test_apprise_result_defaults():
557 """AppriseResult: default construction is an empty NOMATCH result."""
558
559 result = AppriseResult()
560
561 assert result.status == AppriseResultStatus.NOMATCH
562 assert len(result) == 0
563 assert list(result) == []
564 assert result.results == ()
565 assert result.success_count == 0
566 assert result.failed_count == 0
567 assert result.timeout_count == 0
568 assert result.elapsed == 0.0
569 assert bool(result) is False
570 assert list(result.call_logs()) == []
571
572
573 def test_apprise_result_elapsed_custom():
574 """AppriseResult.elapsed stores the caller-supplied wall-clock time."""
575
576 result = AppriseResult(status=AppriseResultStatus.SUCCESS, elapsed=2.5)
577 assert result.elapsed == 2.5
578
579
580 def test_apprise_result_start_end_time_match_elapsed():
581 """Same start_time/end_time-derived-from-elapsed guarantee as
582 NotifyResult, at the whole-call level."""
583
584 result = AppriseResult(status=AppriseResultStatus.SUCCESS, elapsed=4.0)
585
586 assert result.start_time.tzinfo is not None
587 assert result.end_time.tzinfo is not None
588 assert (result.end_time - result.start_time).total_seconds() == 4.0
589 parsed = datetime.strptime(
590 _json_data(result)["end_time"], AWARE_DATE_ISO_FORMAT
591 )
592 assert parsed == result.end_time
593
594
595 def test_apprise_result_bool_success():
596 """AppriseResult.__bool__ is True only for SUCCESS."""
597
598 result = AppriseResult(status=AppriseResultStatus.SUCCESS)
599 assert bool(result) is True
600
601
602 def test_apprise_result_bool_failure():
603 """AppriseResult.__bool__ is False for FAILURE."""
604
605 result = AppriseResult(status=AppriseResultStatus.FAILURE)
606 assert bool(result) is False
607
608
609 def test_apprise_result_bool_nomatch():
610 """AppriseResult.__bool__ is False for NOMATCH."""
611
612 result = AppriseResult(status=AppriseResultStatus.NOMATCH)
613 assert bool(result) is False
614
615
616 def test_apprise_result_bool_timeout():
617 """AppriseResult.__bool__ is False for TIMEOUT."""
618
619 result = AppriseResult(status=AppriseResultStatus.TIMEOUT)
620 assert bool(result) is False
621
622
623 def test_apprise_result_status_exit_code_alignment():
624 """AppriseResultStatus values equal the CLI's historical exit codes."""
625
626 assert int(AppriseResultStatus.SUCCESS) == 0
627 assert int(AppriseResultStatus.FAILURE) == 1
628 assert int(AppriseResultStatus.NOMATCH) == 3
629 assert int(AppriseResultStatus.PARTIAL) == 4
630
631
632 def test_apprise_result_timeout_status_value():
633 """TIMEOUT is the highest-numbered status value (5)."""
634
635 assert int(AppriseResultStatus.TIMEOUT) == 5
636
637
638 def _notify_result(name, url, status):
639 """Test helper: build a one-attempt NotifyResult with the given
640 reflective status (SUCCESS/FAILURE/TIMEOUT), for tests that only
641 care about the aggregate outcome, not attempt-level detail."""
642
643 return NotifyResult(name=name, url=url, attempts=[NotifyAttempt(status)])
644
645
646 def test_apprise_result_len_and_iter():
647 """AppriseResult.__len__/__iter__ walk the collected NotifyResults."""
648
649 r1 = _notify_result("Slack", "slack://t/ch", AppriseResultStatus.SUCCESS)
650 r2 = _notify_result(
651 "Discord", "discord://w/t", AppriseResultStatus.FAILURE
652 )
653 result = AppriseResult(
654 status=AppriseResultStatus.FAILURE, results=[r1, r2]
655 )
656
657 assert len(result) == 2
658 assert list(result) == [r1, r2]
659 assert result.results == (r1, r2)
660
661
662 def test_apprise_result_success_and_failed_counts():
663 """success_count/failed_count are derived from each NotifyResult's
664 reflective .status, and timeout_count narrows failed_count down to
665 just TIMEOUT entries."""
666
667 results = [
668 _notify_result("Slack", "slack://t/ch", AppriseResultStatus.SUCCESS),
669 _notify_result(
670 "Discord", "discord://w/t", AppriseResultStatus.FAILURE
671 ),
672 _notify_result("Telegram", "tgram://b/c", AppriseResultStatus.SUCCESS),
673 _notify_result("Twilio", "twilio://x", AppriseResultStatus.TIMEOUT),
674 ]
675 result = AppriseResult(status=AppriseResultStatus.FAILURE, results=results)
676
677 assert result.success_count == 2
678 assert result.failed_count == 2
679 assert result.timeout_count == 1
680
681
682 def test_apprise_result_logs_merges_and_sorts_across_services():
683 """AppriseResult.logs() combines every service's log entries into
684 one chronological timeline -- not simply service by service, since
685 services dispatched concurrently can log in any relative order to
686 each other regardless of which NotifyResult they end up attached
687 to."""
688
689 early = datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
690 middle = datetime(2026, 1, 1, 12, 0, 1, tzinfo=timezone.utc)
691 late = datetime(2026, 1, 1, 12, 0, 2, tzinfo=timezone.utc)
692
693 # Discord's own NotifyResult is built first, but its one log entry
694 # actually happened AFTER Slack's -- e.g. two services notified
695 # concurrently, with Discord simply finishing (and being appended
696 # to the batch) first.
697 discord = NotifyResult(
698 name="Discord",
699 url="discord://w/t",
700 attempts=[
701 NotifyAttempt(
702 status=AppriseResultStatus.SUCCESS,
703 logs=[
704 NotifyLogEntry(
705 level="WARNING", message="from discord", time=late
706 )
707 ],
708 )
709 ],
710 )
711 slack = NotifyResult(
712 name="Slack",
713 url="slack://t/ch",
714 attempts=[
715 NotifyAttempt(
716 status=AppriseResultStatus.SUCCESS,
717 logs=[
718 NotifyLogEntry(
719 level="WARNING", message="from slack", time=early
720 ),
721 NotifyLogEntry(
722 level="ERROR", message="from slack, later", time=middle
723 ),
724 ],
725 )
726 ],
727 )
728
729 result = AppriseResult(
730 status=AppriseResultStatus.SUCCESS, results=[discord, slack]
731 )
732
733 messages = [entry.message for entry in result.logs()]
734 assert messages == ["from slack", "from slack, later", "from discord"]
735
736
737 def test_apprise_result_call_logs():
738 """Call logs expose a read-only snapshot of orchestration entries."""
739
740 t = datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
741 entries = [
742 NotifyLogEntry(
743 level="WARNING", message="no services to notify", time=t
744 )
745 ]
746 result = AppriseResult(
747 status=AppriseResultStatus.NOMATCH, call_logs=entries
748 )
749
750 assert list(result.call_logs()) == entries
751 # Mutating the input list afterwards must not affect the snapshot.
752 entries.append(
753 NotifyLogEntry(level="WARNING", message="late addition", time=t)
754 )
755 assert len(list(result.call_logs())) == 1
756
757
758 def test_result_logs_merge_call_logs():
759 """Combined logs merge call and service entries by time."""
760
761 early = datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
762 middle = datetime(2026, 1, 1, 12, 0, 1, tzinfo=timezone.utc)
763 late = datetime(2026, 1, 1, 12, 0, 2, tzinfo=timezone.utc)
764
765 slack = NotifyResult(
766 name="Slack",
767 url="slack://t/ch",
768 attempts=[
769 NotifyAttempt(
770 status=AppriseResultStatus.SUCCESS,
771 logs=[
772 NotifyLogEntry(
773 level="WARNING", message="from slack", time=middle
774 )
775 ],
776 )
777 ],
778 )
779 call_logs = [
780 NotifyLogEntry(
781 level="TRACE", message="starting attempt 1/1", time=early
782 ),
783 NotifyLogEntry(level="TRACE", message="attempt finished", time=late),
784 ]
785
786 result = AppriseResult(
787 status=AppriseResultStatus.SUCCESS,
788 results=[slack],
789 call_logs=call_logs,
790 )
791
792 messages = [entry.message for entry in result.logs()]
793 assert messages == [
794 "starting attempt 1/1",
795 "from slack",
796 "attempt finished",
797 ]
798
799
800 def test_apprise_result_iter_json_and_write_json():
801 """Overall JSON streams summary fields and every service result."""
802
803 results = [
804 _notify_result("Slack", "slack://t/ch", AppriseResultStatus.SUCCESS),
805 _notify_result(
806 "Discord", "discord://w/t", AppriseResultStatus.FAILURE
807 ),
808 ]
809 result = AppriseResult(
810 status=AppriseResultStatus.FAILURE, results=results, elapsed=0.75
811 )
812
813 expected = {
814 "status": "FAILURE",
815 "success_count": 1,
816 "failed_count": 1,
817 "elapsed": 0.75,
818 "start_time": result.start_time.strftime(AWARE_DATE_ISO_FORMAT),
819 "end_time": result.end_time.strftime(AWARE_DATE_ISO_FORMAT),
820 "results": [_json_data(item) for item in results],
821 "call_logs": [],
822 }
823 output = "".join(result.iter_json())
824 assert loads(output) == expected
825 assert ", " not in output
826 assert ": " not in output
827
828 stream = StringIO()
829 result.write_json(stream)
830 assert stream.getvalue() == output
831
832
833 def test_result_json_includes_call_logs():
834 """Bounded result JSON includes call-level logs."""
835
836 t = datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
837 entries = [NotifyLogEntry(level="WARNING", message="no services", time=t)]
838 result = AppriseResult(
839 status=AppriseResultStatus.NOMATCH, call_logs=entries
840 )
841
842 assert _json_data(result)["call_logs"] == [e.asdict() for e in entries]
843
844
845 def test_apprise_result_repr():
846 """AppriseResult.__repr__ reports status and entry count."""
847
848 result = AppriseResult(
849 status=AppriseResultStatus.SUCCESS,
850 results=[
851 _notify_result(
852 "Slack", "slack://t/ch", AppriseResultStatus.SUCCESS
853 )
854 ],
855 )
856 text = repr(result)
857
858 assert "SUCCESS" in text
859 assert "1" in text
860
861
862 def test_apprise_result_results_is_read_only_view():
863 """.results is a snapshot tuple; mutating the input list afterwards
864 does not affect it."""
865
866 source = [
867 _notify_result("Slack", "slack://t/ch", AppriseResultStatus.SUCCESS)
868 ]
869 result = AppriseResult(status=AppriseResultStatus.SUCCESS, results=source)
870
871 source.append(
872 _notify_result("Discord", "discord://w/t", AppriseResultStatus.FAILURE)
873 )
874
875 assert len(result) == 1
876 assert len(result.results) == 1
877
878
879 def test_apprise_result_closes_disk_backed_logs():
880 """Closing a result releases temporary files held by its log stores."""
881 from apprise.logger import _LogCaptureBudget, _NotifyLogStore
882
883 call_logs = _NotifyLogStore(
884 _LogCaptureBudget(memory_size=0, disk_size=4096)
885 )
886 attempt_logs = _NotifyLogStore(
887 _LogCaptureBudget(memory_size=0, disk_size=4096)
888 )
889 call_logs.append(NotifyLogEntry("WARNING", "call"))
890 attempt_logs.append(NotifyLogEntry("WARNING", "attempt"))
891 service = NotifyResult(
892 name="Slack",
893 url="slack://t/ch",
894 attempts=[
895 NotifyAttempt(
896 status=AppriseResultStatus.SUCCESS, logs=attempt_logs
897 )
898 ],
899 )
900
901 with AppriseResult(
902 status=AppriseResultStatus.SUCCESS,
903 results=[service],
904 call_logs=call_logs,
905 ) as result:
906 assert [entry.message for entry in result.logs()] == [
907 "call",
908 "attempt",
909 ]
910
911 assert call_logs._budget._disk is None
912 assert attempt_logs._budget._disk is None
913
914 # Closing ordinary list-backed results is also a safe no-op.
915 AppriseResult(
916 results=[
917 NotifyResult(
918 name="Slack",
919 url="slack://t/ch",
920 attempts=[NotifyAttempt(AppriseResultStatus.SUCCESS)],
921 )
922 ]
923 ).close()