Debian Codegraph @

tests/test_delivery_tracking_structure.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
29 """Static checks on how plugins use delivery tracking.
30
31 These read the plugin sources instead of running them, so a new plugin
32 that picks up one of the mistakes already found in the fleet is caught
33 the moment it is added:
34
35 - marking a target while a payload is still being built (a generator)
36 or while the plugin is still being set up (``__init__``)
37 - a ``mark_delivered()`` placed after a ``continue`` where it can never
38 run
39 - asking ``is_delivered()`` without ever marking anything, or the other
40 way around
41 """
42
43 # Disable logging for a cleaner testing output
44 import ast
45 import logging
46 import os
47
48 logging.disable(logging.CRITICAL)
49
50 # Where the plugins live
51 PLUGIN_DIR = os.path.join(
52 os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
53 "apprise",
54 "plugins",
55 )
56
57 # The two calls being looked for
58 TRACKERS = ("is_delivered", "mark_delivered")
59
60
61 def _plugins():
62 """Yield (name, parsed module) for every plugin file."""
63 for root, _dirs, files in os.walk(PLUGIN_DIR):
64 for fname in sorted(files):
65 if not fname.endswith(".py"):
66 continue
67
68 path = os.path.join(root, fname)
69 with open(path, encoding="utf-8") as f:
70 yield (
71 os.path.relpath(path, PLUGIN_DIR),
72 ast.parse(f.read(), filename=path),
73 )
74
75
76 def _tracker(node):
77 """Return the tracking call a statement makes, or None."""
78 if not isinstance(node, ast.Call):
79 return None
80
81 func = node.func
82 return (
83 func.attr
84 if isinstance(func, ast.Attribute)
85 and isinstance(func.value, ast.Name)
86 and func.value.id == "self"
87 and func.attr in TRACKERS
88 else None
89 )
90
91
92 def _scan():
93 """Walk every plugin once and collect anything that looks wrong."""
94
95 built = []
96 unreachable = []
97 lonely = []
98
99 for name, tree in _plugins():
100 used = set()
101
102 for node in ast.walk(tree):
103 called = _tracker(node)
104 if called:
105 used.add(called)
106
107 # A mark that sits after a continue/break/return in the same
108 # block can never run
109 body = getattr(node, "body", None)
110 if isinstance(body, list):
111 stop = None
112 for statement in body:
113 if stop and any(
114 _tracker(child) == "mark_delivered"
115 for child in ast.walk(statement)
116 ):
117 unreachable.append(
118 f"{name}:{statement.lineno} marks a target"
119 f" after the {stop[0]} on line {stop[1]}"
120 )
121
122 if isinstance(
123 statement, (ast.Continue, ast.Break, ast.Return)
124 ):
125 stop = (
126 type(statement).__name__.lower(),
127 statement.lineno,
128 )
129
130 # Where the mark lives matters too
131 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
132 marks = [
133 child
134 for child in ast.walk(node)
135 if _tracker(child) == "mark_delivered"
136 ]
137 if not marks:
138 continue
139
140 if node.name == "__init__":
141 built.append(
142 f"{name}:{marks[0].lineno} marks a target from"
143 " __init__(), before anything is sent"
144 )
145
146 elif any(
147 isinstance(child, (ast.Yield, ast.YieldFrom))
148 for child in ast.walk(node)
149 ):
150 built.append(
151 f"{name}:{marks[0].lineno} marks a target inside"
152 f" the generator {node.name}(), while the payload"
153 " is still being built"
154 )
155
156 if used and used != set(TRACKERS):
157 lonely.append(
158 f"{name} uses {sorted(used)[0]}() on its own; a target is"
159 " either never skipped or never recorded"
160 )
161
162 return built, unreachable, lonely
163
164
165 # Scanned once for the whole module
166 BUILT, UNREACHABLE, LONELY = _scan()
167
168
169 def test_targets_are_not_marked_while_a_payload_is_built():
170 """Marking belongs in the loop that sends, nowhere else."""
171
172 assert not BUILT, "\n".join(BUILT)
173
174
175 def test_marking_a_target_is_reachable():
176 """A mark placed after a continue can never run."""
177
178 assert not UNREACHABLE, "\n".join(UNREACHABLE)
179
180
181 def test_asking_and_marking_go_together():
182 """A plugin that asks also marks, and one that marks also asks."""
183
184 assert not LONELY, "\n".join(LONELY)