push-claim-audit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 push-claim-audit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ include LICENSE
2
+ recursive-include tests *.py *.md .env
3
+
4
+ include scripts/verify_dists.py
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: push-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented device-notification delivery
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # push-claim-audit
12
+
13
+ Offline static auditing of documented device-notification delivery against Python source. Version 0.1.0; standard library only at runtime. Audited code is never executed. Environment files are never opened.
14
+
15
+ Install and run:
16
+
17
+ ```sh
18
+ python3 -m pip install .
19
+ push-claim-audit /path/to/project --json
20
+ python3 -m push_claim_audit /path/to/project --verbose
21
+ python3 -m unittest discover
22
+ python3 -m build
23
+ ```
24
+
25
+ The positional directory is required. Options: `--json`, `--verbose`, repeatable `--ignore <glob>` relative to the directory, `--fail-on {HIGH,MEDIUM}` (default HIGH), and `--version`. Exit 0 means PASS, 2 means a finding meets the threshold, and 1 means a usage or filesystem error. MEDIUM findings remain visible at the default threshold.
26
+
27
+ Root README.md and Markdown files below any docs path component supply claims. Fenced blocks are excluded; inline code counts. Matching is case insensitive, expands contractions, replaces hyphens, and joins lines within paragraphs. Negative spans are removed before affirmative matching. One finding per family is emitted, at most two.
28
+
29
+ ## Limitations
30
+
31
+ Only the fixed affirmative and negative templates defined in `push_claim_audit/audit.py` count as claims; arbitrary paraphrases do not. The bare word “push”, titles, dependency names, and git commands do not qualify. SMS, email, inbound hooks, framed sockets, browser event streams, GraphQL, gRPC, and MQTT are separate channels.
32
+
33
+ Evidence requires a same-module Firebase message construction and send, a pywebpush call, or an imported APNs/OneSignal client construction followed by a direct send on the bound receiver or chained constructor. Imports resolve aliases. Attribute bindings such as self.client count. Intermediate method aliases and cross-module pairs do not count. This is a syntactic check, without control-flow, runtime reachability, credential validity, or delivery guarantees. Parse-invalid modules supply no evidence. Scope shadowing and reassignment are not modeled.
34
+
35
+ Production scanning excludes tests, test-named modules, fixtures, docs, examples, and symlinks. Evidence confined to tests yields MEDIUM for an affirmative production claim. A contradictory negative claim yields HIGH only when production evidence exists, including a negative claim in test documentation. An affirmative claim without source yields HIGH; an absence claim without source is consistent. JSON includes verdict, findings, claim paths, and evidence paths.
@@ -0,0 +1,25 @@
1
+ # push-claim-audit
2
+
3
+ Offline static auditing of documented device-notification delivery against Python source. Version 0.1.0; standard library only at runtime. Audited code is never executed. Environment files are never opened.
4
+
5
+ Install and run:
6
+
7
+ ```sh
8
+ python3 -m pip install .
9
+ push-claim-audit /path/to/project --json
10
+ python3 -m push_claim_audit /path/to/project --verbose
11
+ python3 -m unittest discover
12
+ python3 -m build
13
+ ```
14
+
15
+ The positional directory is required. Options: `--json`, `--verbose`, repeatable `--ignore <glob>` relative to the directory, `--fail-on {HIGH,MEDIUM}` (default HIGH), and `--version`. Exit 0 means PASS, 2 means a finding meets the threshold, and 1 means a usage or filesystem error. MEDIUM findings remain visible at the default threshold.
16
+
17
+ Root README.md and Markdown files below any docs path component supply claims. Fenced blocks are excluded; inline code counts. Matching is case insensitive, expands contractions, replaces hyphens, and joins lines within paragraphs. Negative spans are removed before affirmative matching. One finding per family is emitted, at most two.
18
+
19
+ ## Limitations
20
+
21
+ Only the fixed affirmative and negative templates defined in `push_claim_audit/audit.py` count as claims; arbitrary paraphrases do not. The bare word “push”, titles, dependency names, and git commands do not qualify. SMS, email, inbound hooks, framed sockets, browser event streams, GraphQL, gRPC, and MQTT are separate channels.
22
+
23
+ Evidence requires a same-module Firebase message construction and send, a pywebpush call, or an imported APNs/OneSignal client construction followed by a direct send on the bound receiver or chained constructor. Imports resolve aliases. Attribute bindings such as self.client count. Intermediate method aliases and cross-module pairs do not count. This is a syntactic check, without control-flow, runtime reachability, credential validity, or delivery guarantees. Parse-invalid modules supply no evidence. Scope shadowing and reassignment are not modeled.
24
+
25
+ Production scanning excludes tests, test-named modules, fixtures, docs, examples, and symlinks. Evidence confined to tests yields MEDIUM for an affirmative production claim. A contradictory negative claim yields HIGH only when production evidence exists, including a negative claim in test documentation. An affirmative claim without source yields HIGH; an absence claim without source is consistent. JSON includes verdict, findings, claim paths, and evidence paths.
@@ -0,0 +1,2 @@
1
+ """Static documentation and outbound device-delivery auditor."""
2
+ __version__ = '0.1.0'
@@ -0,0 +1,41 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+ from . import __version__
5
+ from .audit import audit
6
+
7
+
8
+ class Parser(argparse.ArgumentParser):
9
+ def error(self, message):
10
+ self.print_usage(sys.stderr)
11
+ self.exit(1, 'error: ' + message + '\n')
12
+
13
+
14
+ def main(argv=None):
15
+ parser = Parser(description='Audit documented device-delivery capabilities statically.')
16
+ parser.add_argument('root')
17
+ parser.add_argument('--json', action='store_true')
18
+ parser.add_argument('--verbose', action='store_true')
19
+ parser.add_argument('--ignore', action='append', default=[])
20
+ parser.add_argument('--fail-on', choices=['HIGH', 'MEDIUM'], default='HIGH')
21
+ parser.add_argument('--version', action='version', version=__version__)
22
+ args = parser.parse_args(argv)
23
+ try:
24
+ result = audit(args.root, args.ignore, args.fail_on)
25
+ except (OSError, ValueError, UnicodeError) as exc:
26
+ print('error: ' + str(exc), file=sys.stderr)
27
+ return 1
28
+ if args.json:
29
+ print(json.dumps(result))
30
+ else:
31
+ print(result['verdict'])
32
+ for item in result['findings']:
33
+ print('{severity} {rule}: {message}'.format(**item))
34
+ if args.verbose:
35
+ print('Evidence: ' + (', '.join(result['evidence']) or 'none'))
36
+ print('Claim files: ' + (', '.join(result['claims']) or 'none'))
37
+ return 2 if result['verdict'] == 'FAIL' else 0
38
+
39
+
40
+ if __name__ == '__main__':
41
+ sys.exit(main())
@@ -0,0 +1,138 @@
1
+ """Read documentation and Python ASTs without executing project code."""
2
+ import ast
3
+ import fnmatch
4
+ import re
5
+ from pathlib import Path
6
+
7
+ PUSH = ('support for push notifications', 'support for push', 'push notification support', 'push notifications', 'push notification', 'push alerts', 'push alert', 'push messages', 'push message', 'sends push notifications', 'send push notifications', 'sends push', 'send push', 'push support', 'push enabled', 'push powered', 'push based', 'supports push notifications', 'supports push', 'uses push', 'using push', 'over push', 'via push', 'with push')
8
+ NOPUSH = ('no push notifications', 'no push notification', 'no push support', 'does not support push', 'does not send push', 'does not use push', 'push notifications not supported', 'push not supported', 'without push', 'no push')
9
+ CLIENTS = {'APNsClient', 'APNSClient', 'OneSignalClient', 'Client'}
10
+
11
+
12
+ def normalize(text):
13
+ return re.sub(r'\s+', ' ', text.lower().replace("n't", ' not').replace('-', ' ')).strip()
14
+
15
+
16
+ def pattern(phrases):
17
+ return re.compile(r'\b(?:' + '|'.join(re.escape(p) for p in sorted(phrases, key=len, reverse=True)) + r')\b')
18
+
19
+
20
+ def claims(text):
21
+ lines, fence = [], None
22
+ for line in text.splitlines():
23
+ mark = re.match(r'^\s{0,3}(`{3,}|~{3,})', line)
24
+ if mark:
25
+ token = mark.group(1)
26
+ if fence is None:
27
+ fence = token
28
+ elif token[0] == fence[0] and len(token) >= len(fence) and not line.strip()[len(token):].strip():
29
+ fence = None
30
+ lines.append('')
31
+ elif fence is None:
32
+ lines.append(line)
33
+ positive = negative = False
34
+ for paragraph in re.split(r'\n\s*\n', '\n'.join(lines)):
35
+ text = normalize(paragraph)
36
+ negative |= bool(pattern(NOPUSH).search(text))
37
+ positive |= bool(pattern(PUSH).search(pattern(NOPUSH).sub(' ', text)))
38
+ return positive, negative
39
+
40
+
41
+ def dotted(node):
42
+ if isinstance(node, ast.Name):
43
+ return node.id
44
+ if isinstance(node, ast.Attribute):
45
+ base = dotted(node.value)
46
+ return base + '.' + node.attr if base else ''
47
+ return ''
48
+
49
+
50
+ def push_module(name):
51
+ return bool(set(name.split('.')) & {'apns', 'apns2', 'aioapns', 'onesignal'})
52
+
53
+
54
+ def evidence(text):
55
+ try:
56
+ tree = ast.parse(text)
57
+ except (SyntaxError, ValueError):
58
+ return False
59
+ aliases = {}
60
+ for node in ast.walk(tree):
61
+ if isinstance(node, ast.Import):
62
+ for item in node.names:
63
+ aliases[item.asname or item.name.split('.')[0]] = item.name if item.asname else item.name.split('.')[0]
64
+ elif isinstance(node, ast.ImportFrom) and node.module:
65
+ for item in node.names:
66
+ aliases[item.asname or item.name] = node.module + '.' + item.name
67
+
68
+ def resolve(node):
69
+ name = dotted(node)
70
+ first, sep, rest = name.partition('.')
71
+ return aliases.get(first, '') + (sep + rest if sep else '') if first in aliases else ''
72
+
73
+ def provider_call(node, provider, names):
74
+ if not isinstance(node, ast.Call):
75
+ return False
76
+ path = resolve(node.func)
77
+ module, _, symbol = path.rpartition('.')
78
+ return symbol in names and (module == provider or module.startswith(provider + '.'))
79
+
80
+ def creation(node):
81
+ if not isinstance(node, ast.Call):
82
+ return False
83
+ module, _, symbol = resolve(node.func).rpartition('.')
84
+ return symbol in CLIENTS and push_module(module)
85
+
86
+ nodes = list(ast.walk(tree))
87
+ bindings = set()
88
+ for node in nodes:
89
+ if isinstance(node, (ast.Assign, ast.AnnAssign)) and creation(node.value):
90
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
91
+ bindings.update(dotted(t) for t in targets if dotted(t))
92
+ message = send = usage = False
93
+ for node in nodes:
94
+ message |= provider_call(node, 'firebase_admin.messaging', {'Message'})
95
+ send |= provider_call(node, 'firebase_admin.messaging', {'send', 'send_multicast', 'send_all'})
96
+ if provider_call(node, 'pywebpush', {'webpush'}):
97
+ return True
98
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in {'send_notification', 'create_notification'}:
99
+ usage |= dotted(node.func.value) in bindings or creation(node.func.value)
100
+ return bool((message and send) or usage)
101
+
102
+
103
+ def audit(root, ignores=(), fail_on='HIGH'):
104
+ root = Path(root)
105
+ if not root.is_dir() or root.stat().st_mode & 0o444 == 0:
106
+ raise ValueError('root must be a readable directory')
107
+ positive = negative = prod = test = False
108
+ sources, claim_files = [], []
109
+ for path in sorted(root.rglob('*')):
110
+ rel = path.relative_to(root)
111
+ if path.is_symlink() or any(parent.is_symlink() for parent in path.parents if parent != root) or not path.is_file():
112
+ continue
113
+ if any(fnmatch.fnmatch(rel.as_posix(), glob) for glob in ignores):
114
+ continue
115
+ parts = rel.parts
116
+ if (rel.as_posix() == 'README.md' or 'docs' in parts) and path.suffix.lower() == '.md':
117
+ p, n = claims(path.read_text(encoding='utf-8'))
118
+ if not ('tests' in parts or 'fixtures' in parts):
119
+ positive |= p
120
+ negative |= n
121
+ if p or n:
122
+ claim_files.append(rel.as_posix())
123
+ if path.suffix != '.py' or any(p in {'fixtures', 'docs', 'examples'} for p in parts):
124
+ continue
125
+ is_test = 'tests' in parts or path.name.startswith('test_') or path.name.endswith('_test.py')
126
+ if evidence(path.read_text(encoding='utf-8')):
127
+ sources.append(rel.as_posix())
128
+ if is_test:
129
+ test = True
130
+ else:
131
+ prod = True
132
+ findings = []
133
+ if positive and not prod:
134
+ findings.append(dict(rule='documented-push-claim-false', severity='MEDIUM' if test else 'HIGH', message='Documented device delivery lacks production send evidence.'))
135
+ if negative and prod:
136
+ findings.append(dict(rule='documented-no-push-claim-false', severity='HIGH', message='Documented absence conflicts with production send evidence.'))
137
+ failed = any(f['severity'] == 'HIGH' or fail_on == 'MEDIUM' for f in findings)
138
+ return dict(verdict='FAIL' if failed else 'PASS', findings=findings, claims=claim_files, evidence=sources)
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: push-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented device-notification delivery
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # push-claim-audit
12
+
13
+ Offline static auditing of documented device-notification delivery against Python source. Version 0.1.0; standard library only at runtime. Audited code is never executed. Environment files are never opened.
14
+
15
+ Install and run:
16
+
17
+ ```sh
18
+ python3 -m pip install .
19
+ push-claim-audit /path/to/project --json
20
+ python3 -m push_claim_audit /path/to/project --verbose
21
+ python3 -m unittest discover
22
+ python3 -m build
23
+ ```
24
+
25
+ The positional directory is required. Options: `--json`, `--verbose`, repeatable `--ignore <glob>` relative to the directory, `--fail-on {HIGH,MEDIUM}` (default HIGH), and `--version`. Exit 0 means PASS, 2 means a finding meets the threshold, and 1 means a usage or filesystem error. MEDIUM findings remain visible at the default threshold.
26
+
27
+ Root README.md and Markdown files below any docs path component supply claims. Fenced blocks are excluded; inline code counts. Matching is case insensitive, expands contractions, replaces hyphens, and joins lines within paragraphs. Negative spans are removed before affirmative matching. One finding per family is emitted, at most two.
28
+
29
+ ## Limitations
30
+
31
+ Only the fixed affirmative and negative templates defined in `push_claim_audit/audit.py` count as claims; arbitrary paraphrases do not. The bare word “push”, titles, dependency names, and git commands do not qualify. SMS, email, inbound hooks, framed sockets, browser event streams, GraphQL, gRPC, and MQTT are separate channels.
32
+
33
+ Evidence requires a same-module Firebase message construction and send, a pywebpush call, or an imported APNs/OneSignal client construction followed by a direct send on the bound receiver or chained constructor. Imports resolve aliases. Attribute bindings such as self.client count. Intermediate method aliases and cross-module pairs do not count. This is a syntactic check, without control-flow, runtime reachability, credential validity, or delivery guarantees. Parse-invalid modules supply no evidence. Scope shadowing and reassignment are not modeled.
34
+
35
+ Production scanning excludes tests, test-named modules, fixtures, docs, examples, and symlinks. Evidence confined to tests yields MEDIUM for an affirmative production claim. A contradictory negative claim yields HIGH only when production evidence exists, including a negative claim in test documentation. An affirmative claim without source yields HIGH; an absence claim without source is consistent. JSON includes verdict, findings, claim paths, and evidence paths.
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ push_claim_audit/__init__.py
6
+ push_claim_audit/__main__.py
7
+ push_claim_audit/audit.py
8
+ push_claim_audit.egg-info/PKG-INFO
9
+ push_claim_audit.egg-info/SOURCES.txt
10
+ push_claim_audit.egg-info/dependency_links.txt
11
+ push_claim_audit.egg-info/entry_points.txt
12
+ push_claim_audit.egg-info/top_level.txt
13
+ scripts/verify_dists.py
14
+ tests/__init__.py
15
+ tests/test_audit.py
16
+ tests/fixtures/.env
17
+ tests/fixtures/bad/README.md
18
+ tests/fixtures/bad/app.py
19
+ tests/fixtures/good/README.md
20
+ tests/fixtures/good/app.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ push-claim-audit = push_claim_audit.__main__:main
@@ -0,0 +1 @@
1
+ push_claim_audit
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "push-claim-audit"
7
+ version = "0.1.0"
8
+ description = "Offline static audit of documented device-notification delivery"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+
13
+ [project.scripts]
14
+ push-claim-audit = "push_claim_audit.__main__:main"
15
+
16
+ [tool.setuptools.packages.find]
17
+ include = ["push_claim_audit*"]
@@ -0,0 +1,39 @@
1
+ """Verify distribution installs away from the source checkout."""
2
+ import json
3
+ from pathlib import Path
4
+ import subprocess
5
+ import tempfile
6
+ import venv
7
+
8
+ ROOT = Path(__file__).resolve().parents[1]
9
+
10
+
11
+ def run(command, cwd, expected=0):
12
+ result = subprocess.run([str(p) for p in command], cwd=cwd, text=True, capture_output=True)
13
+ if result.returncode != expected:
14
+ raise AssertionError((command, result.returncode, result.stdout, result.stderr))
15
+ return result.stdout.strip()
16
+
17
+
18
+ def main():
19
+ for artifact in sorted((ROOT / 'dist').iterdir()):
20
+ with tempfile.TemporaryDirectory(prefix='push-claim-install-') as directory:
21
+ work = Path(directory)
22
+ env = work / 'venv'
23
+ venv.EnvBuilder(with_pip=True).create(env)
24
+ interpreter = env / 'bin/python3'
25
+ run([interpreter, '-m', 'pip', 'install', artifact], work)
26
+ for command in ([env / 'bin/push-claim-audit'], [interpreter, '-m', 'push_claim_audit']):
27
+ assert run(command + ['--version'], work) == '0.1.0'
28
+ good = json.loads(run(command + [ROOT / 'tests/fixtures/good', '--json'], work))
29
+ assert good['verdict'] == 'PASS' and good['findings'] == []
30
+ bad = json.loads(run(command + [ROOT / 'tests/fixtures/bad', '--json'], work, 2))
31
+ assert bad['verdict'] == 'FAIL'
32
+ assert [(f['rule'], f['severity']) for f in bad['findings']] == [('documented-push-claim-false', 'HIGH')]
33
+ own = json.loads(run(command + [ROOT, '--json'], work))
34
+ assert own['verdict'] == 'PASS' and own['claims'] == [] and own['findings'] == []
35
+ print(artifact.name + ': fresh install PASS; both entry points, good=0, bad=2 exact HIGH rule, version=0.1.0, self-audit=0 no claim')
36
+
37
+
38
+ if __name__ == '__main__':
39
+ main()
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1 @@
1
+ AUDIT_GUARD_MARKER_ONLY
@@ -0,0 +1 @@
1
+ push notifications
@@ -0,0 +1 @@
1
+ import firebase_admin.messaging
@@ -0,0 +1 @@
1
+ push notifications
@@ -0,0 +1,3 @@
1
+ from firebase_admin.messaging import Message, send
2
+ m = Message(token="fixture")
3
+ send(m)
@@ -0,0 +1,201 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ from pathlib import Path
5
+ import re
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import unittest
10
+ from unittest.mock import patch
11
+
12
+ from push_claim_audit.audit import audit, claims, evidence, normalize, pattern, PUSH, NOPUSH
13
+ from push_claim_audit.__main__ import main
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ WEB = 'from pywebpush import webpush\nwebpush()'
17
+
18
+
19
+ class AuditTests(unittest.TestCase):
20
+ def fixture(self, readme='push notifications', files=None):
21
+ temp = tempfile.TemporaryDirectory()
22
+ self.addCleanup(temp.cleanup)
23
+ root = Path(temp.name)
24
+ for name, text in dict({'README.md': readme}, **(files or {})).items():
25
+ path = root / name
26
+ path.parent.mkdir(parents=True, exist_ok=True)
27
+ path.write_text(text, encoding='utf-8')
28
+ return root
29
+
30
+ def cli(self, root, *args):
31
+ out = io.StringIO()
32
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
33
+ code = main([str(root), *args])
34
+ return code, out.getvalue()
35
+
36
+ def check_case(self, source, good):
37
+ root = self.fixture(files={'app.py': source})
38
+ code, output = self.cli(root, '--json')
39
+ result = json.loads(output)
40
+ self.assertEqual(code, 0 if good else 2)
41
+ self.assertEqual(result['verdict'], 'PASS' if good else 'FAIL')
42
+ self.assertEqual(result['findings'], [] if good else [dict(rule='documented-push-claim-false', severity='HIGH', message='Documented device delivery lacks production send evidence.')])
43
+
44
+ def test_no_push(self):
45
+ root = self.fixture('no push support', {'app.py': WEB})
46
+ code, text = self.cli(root, '--json')
47
+ self.assertEqual(code, 2)
48
+ self.assertEqual([(f['rule'], f['severity']) for f in json.loads(text)['findings']], [('documented-no-push-claim-false', 'HIGH')])
49
+
50
+ def test_exclusions(self):
51
+ for phrase in ('ordinary application', 'the push chapter explains delivery', 'sms notifications', 'email notifications', 'webhook', 'websocket server', 'server-sent events', 'GraphQL interface', 'gRPC interface', 'MQTT'):
52
+ with self.subTest(phrase=phrase):
53
+ root = self.fixture(phrase, {'app.py': WEB})
54
+ self.assertEqual(audit(root)['claims'], [])
55
+ self.assertEqual(self.cli(root)[0], 0)
56
+
57
+ def test_no_source(self):
58
+ self.assertEqual(self.cli(self.fixture())[0], 2)
59
+ self.assertEqual(self.cli(self.fixture('no push support'))[0], 0)
60
+
61
+ def test_test_only(self):
62
+ for path in ('tests/send.py', 'test_send.py', 'send_test.py'):
63
+ root = self.fixture(files={path: WEB})
64
+ self.assertEqual(audit(root)['findings'][0]['severity'], 'MEDIUM')
65
+ self.assertEqual(self.cli(root)[0], 0)
66
+ self.assertEqual(self.cli(root, '--fail-on', 'MEDIUM')[0], 2)
67
+
68
+ def test_fences_and_inline(self):
69
+ for fence in ('```', '~~~~'):
70
+ self.assertEqual(claims(fence + '\npush notifications\n' + fence), (False, False))
71
+ self.assertEqual(self.cli(self.fixture('inline `push notifications`'))[0], 2)
72
+
73
+ def test_negation(self):
74
+ self.assertEqual(claims('does not send push'), (False, True))
75
+ self.assertEqual(claims("doesn't send push"), (False, True))
76
+ for phrase in NOPUSH:
77
+ self.assertEqual(claims(phrase), (False, True), phrase)
78
+ for phrase in PUSH:
79
+ self.assertEqual(claims(phrase), (True, False), phrase)
80
+
81
+ def test_normalization_and_boundaries(self):
82
+ self.assertEqual(claims('PUSH-\nnotifications'), (True, False))
83
+ self.assertEqual(claims('push\n\nnotifications'), (False, False))
84
+ self.assertEqual(claims('repush notificationsXYZ'), (False, False))
85
+
86
+ def test_module_boundary(self):
87
+ root = self.fixture(files={'a.py': 'from firebase_admin.messaging import Message\nm=Message()', 'b.py': 'from firebase_admin.messaging import send\nsend(m)'})
88
+ self.assertEqual(self.cli(root)[0], 2)
89
+ root = self.fixture(files={'a.py': 'from apns2 import APNsClient\nclient=APNsClient()', 'b.py': 'client.send_notification()'})
90
+ self.assertEqual(self.cli(root)[0], 2)
91
+
92
+ def test_self_audit(self):
93
+ result = audit(ROOT)
94
+ self.assertEqual(result['verdict'], 'PASS')
95
+ self.assertEqual(result['claims'], [])
96
+ self.assertEqual(result['findings'], [])
97
+ for path in ROOT.rglob('*.md'):
98
+ if path == ROOT / 'README.md' or 'docs' in path.relative_to(ROOT).parts:
99
+ text = normalize(path.read_text())
100
+ self.assertIsNone(pattern(PUSH + NOPUSH).search(text), str(path))
101
+
102
+ def test_cli_surface(self):
103
+ root = self.fixture(files={'app.py': WEB, 'docs/guide.md': 'no push support'})
104
+ self.assertEqual(self.cli(root)[0], 2)
105
+ self.assertEqual(self.cli(root, '--ignore', 'docs/*')[0], 0)
106
+ code, text = self.cli(root, '--verbose')
107
+ self.assertIn('app.py', text)
108
+ self.assertEqual(self.cli(root / 'missing')[0], 1)
109
+ with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as exc:
110
+ main([])
111
+ self.assertEqual(exc.exception.code, 1)
112
+ version = subprocess.run([sys.executable, '-m', 'push_claim_audit', '--version'], capture_output=True, text=True)
113
+ self.assertEqual((version.returncode, version.stdout.strip()), (0, '0.1.0'))
114
+
115
+ def test_env_guard(self):
116
+ original = Path.open
117
+ def guarded(path, *args, **kwargs):
118
+ self.assertNotEqual(path.name, '.env')
119
+ return original(path, *args, **kwargs)
120
+ with patch.object(Path, 'open', guarded):
121
+ self.assertEqual(audit(ROOT)['verdict'], 'PASS')
122
+ self.assertTrue((ROOT / 'tests/fixtures/.env').is_file())
123
+
124
+ def test_packaging_conventions(self):
125
+ for path in list(ROOT.rglob('*.py')) + [ROOT / 'README.md', ROOT / 'pyproject.toml']:
126
+ if any(p in {'build', 'dist', '.venv'} for p in path.parts):
127
+ continue
128
+ # Match a command token rather than prose language names.
129
+ self.assertIsNone(re.search(r'\bpy' + r'thon\s+(?:-m|-c|[^\s]+\.py)', path.read_text()), str(path))
130
+ config = (ROOT / 'pyproject.toml').read_text()
131
+ self.assertIn('setuptools>=77', config)
132
+ self.assertIn('license = "MIT"', config)
133
+ self.assertIn('recursive-include tests', (ROOT / 'MANIFEST.in').read_text())
134
+
135
+ def test_excluded_source_and_symlinks(self):
136
+ for name in ('fixtures/a.py', 'docs/a.py', 'examples/a.py'):
137
+ self.assertEqual(self.cli(self.fixture(files={name: WEB}))[0], 2)
138
+ root = self.fixture(files={'fixtures/real.py': WEB})
139
+ (root / 'linked.py').symlink_to(root / 'fixtures/real.py')
140
+ self.assertEqual(self.cli(root)[0], 2)
141
+
142
+ def test_negative_test_docs_asymmetry(self):
143
+ root = self.fixture('neutral', {'app.py': WEB, 'tests/docs/readme.md': 'no push support'})
144
+ self.assertEqual(self.cli(root)[0], 2)
145
+
146
+ def test_both_families(self):
147
+ root = self.fixture('push notifications. no push support')
148
+ self.assertEqual(len(audit(root)['findings']), 1)
149
+
150
+
151
+ GOOD = [
152
+ 'from firebase_admin.messaging import Message, send\nm=Message()\nsend(m)',
153
+ 'import firebase_admin.messaging as fm\nm=fm.Message()\nfm.send(m)',
154
+ 'import firebase_admin\nm=firebase_admin.messaging.Message()\nfirebase_admin.messaging.send(m)',
155
+ 'from firebase_admin.messaging import Message as FCMMessage, send as fcm_send\nm=FCMMessage()\nfcm_send(m)',
156
+ WEB,
157
+ 'import pywebpush as pw\npw.webpush()',
158
+ 'from apns2.client import APNsClient\nself.client=APNsClient()\nself.client.send_notification()',
159
+ 'from onesignal import OneSignalClient\nOneSignalClient().create_notification()',
160
+ 'import firebase_admin as fa\nfa.messaging.Message()\nfa.messaging.send_multicast([])',
161
+ 'import firebase_admin.messaging\nfirebase_admin.messaging.Message()\nfirebase_admin.messaging.send_all([])',
162
+ 'import apns2.client as ac\napp.client=ac.APNsClient()\napp.client.send_notification()',
163
+ 'import onesignal\nclient=onesignal.OneSignalClient()\nclient.create_notification()',
164
+ 'import pywebpush\npywebpush.webpush()',
165
+ 'from pywebpush import webpush as wp\nwp()',
166
+ 'from aioapns import APNSClient as C\nc: object=C()\nc.send_notification()',
167
+ 'from onesignal import Client\na=b=Client()\nb.create_notification()',
168
+ 'from firebase_admin.messaging.sub import Message, send_all\nMessage()\nsend_all([])',
169
+ ]
170
+ BAD = [
171
+ 'import firebase_admin.messaging',
172
+ 'from firebase_admin.messaging import Message\nMessage()',
173
+ 'from firebase_admin.messaging import send\nsend(m)',
174
+ 'def webpush(): pass\nwebpush()',
175
+ 'client.send_notification()',
176
+ 'from apns2.client import APNsClient\nclient=APNsClient()\nfn=client.send_notification\nfn()',
177
+ 'from flask import Flask\napp=Flask(__name__)\n@app.post("/subscribe")\ndef subscribe():\n subscriptions.append(request.json)',
178
+ 'import smtplib\nsmtplib.SMTP("localhost").sendmail("a", "b", "hello")',
179
+ 'from twilio.rest import Client\nClient().messages.create(body="hello", to="fixture")',
180
+ 'channel="push"\ntoken="fixture"\nkey="marker"',
181
+ 'from apns2 import APNsClient\nclient=APNsClient()\nother.send_notification()',
182
+ 'from database import Client\nclient=Client()\nclient.send_notification()',
183
+ 'class Client: pass\nclient=Client()\nclient.create_notification()',
184
+ 'def push():\n print("push")\npush()',
185
+ 'client.register_device_token("fixture")',
186
+ 'import boto3\nboto3.client("ses").send_email()',
187
+ 'Message()\nsend()',
188
+ '"from pywebpush import webpush; webpush()"',
189
+ '# from pywebpush import webpush\n# webpush()',
190
+ ]
191
+
192
+
193
+ def add_cases():
194
+ for prefix, cases, good in [('good', GOOD, True), ('bad', BAD, False)]:
195
+ for index, source in enumerate(cases, 1):
196
+ def test(self, source=source, good=good):
197
+ self.check_case(source, good)
198
+ setattr(AuditTests, 'test_' + prefix + '_' + str(index).zfill(2), test)
199
+
200
+
201
+ add_cases()