a11y-ad 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,8 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-10-04)
4
+
5
+ - Initial release: WCAG 4.1.2 accessible-name resolver (aria-labelledby,
6
+ aria-label, visible text, label[for], wrapping label, title, alt),
7
+ file/directory/URL scanning, JSON output, CI exit codes, stdlib-only.
8
+ - Regression tests ported from the proven original implementation.
a11y_ad-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,3 @@
1
+ recursive-include tests *.py
2
+ recursive-include tests/fixtures *.html
3
+ include LICENSE README.md CHANGELOG.md
a11y_ad-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.4
2
+ Name: a11y-ad
3
+ Version: 0.1.0
4
+ Summary: Browserless WCAG 4.1.2 accessible-name auditor for HTML — resolves aria labels, visible text, <label> bindings and titles, and reports every interactive element with no accessible name.
5
+ Author: goun7
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/goun7/a11y-ad
8
+ Project-URL: Issues, https://github.com/goun7/a11y-ad/issues
9
+ Project-URL: Changelog, https://github.com/goun7/a11y-ad/blob/main/CHANGELOG.md
10
+ Keywords: accessibility,a11y,wcag,wcag22,aria,accessible-name,audit,cli,html,eaa
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Software Development :: Quality Assurance
22
+ Classifier: Topic :: Text Processing :: Markup :: HTML
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Dynamic: license-file
27
+
28
+ # a11y-ad — browserless WCAG 4.1.2 accessible-name auditor
29
+
30
+ `a11y-ad` audits HTML for **missing accessible names** (WCAG 4.1.2 / "Name,
31
+ Role, Value") on every interactive element — no browser, no headless Chrome,
32
+ stdlib only. Built for CI.
33
+
34
+ ## Why another accessibility tool?
35
+
36
+ Most lightweight linters check *only* `aria-label`/`<label>` and flag every
37
+ button with visible text as a critical failure. In one audit run against a
38
+ fully-labelled application, a popular scanner reported **68 "critical" HTML
39
+ accessible-name issues — 0 of them real**, because visible button text,
40
+ `aria-labelledby`, and wrapping `<label>` elements are all valid accessible
41
+ names.
42
+
43
+ `a11y-ad` resolves the name the way assistive technology does, following the
44
+ WCAG 4.1.2 resolution order:
45
+
46
+ ```
47
+ aria-labelledby -> aria-label -> visible text -> <label for=id>
48
+ -> wrapping <label> -> title -> alt (input[type=image])
49
+ ```
50
+
51
+ and reports only the elements that end up with **no name at all**.
52
+
53
+ ## Scope (be honest about automated a11y coverage)
54
+
55
+ Automated tools in general catch roughly 30–50% of WCAG issues; manual
56
+ keyboard/screen-reader testing remains necessary. `a11y-ad` covers exactly
57
+ one failure class — missing accessible names — and does it with zero false
58
+ positives in the resolution cases above. Browser-measured checks (target
59
+ size, focus visibility, contrast, reduced motion) are out of scope for the
60
+ core; see Roadmap.
61
+
62
+ ## Install
63
+
64
+ ```bash
65
+ pip install a11y-ad
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ ```bash
71
+ a11y-ad index.html # single file
72
+ a11y-ad src/ # directory (recursive, *.html)
73
+ a11y-ad https://example.com # URL
74
+ a11y-ad src/ --json # machine-readable
75
+ ```
76
+
77
+ Exit code is `1` when any interactive element lacks a name — use it as a CI
78
+ gate:
79
+
80
+ ```yaml
81
+ # GitHub Actions example
82
+ - run: pip install a11y-ad && a11y-ad dist/
83
+ ```
84
+
85
+ ### JSON payload
86
+
87
+ ```json
88
+ [
89
+ {
90
+ "target": "bad.html",
91
+ "total": 3,
92
+ "missing": ["line 3 <button >", "line 4 <input >"],
93
+ "sources": {"MISSING": 2, "text": 1},
94
+ "ok": false
95
+ }
96
+ ]
97
+ ```
98
+
99
+ ### Library
100
+
101
+ ```python
102
+ from a11y_ad import audit, audit_file, audit_tree, fetch
103
+
104
+ r = audit('<button aria-labelledby="h1">Edit</button>')
105
+ r.ok # True
106
+ r.elements[0] # Element(tag='button', name='...', source='aria-labelledby')
107
+ r.missing # elements with no accessible name
108
+ ```
109
+
110
+ ## Exclusions & semantics
111
+
112
+ - `<a>` without `href` and `<input type="hidden">` are not interactive → skipped.
113
+ - `aria-hidden="true"` counts as *named* (it is intentionally hidden from AT).
114
+ - Elements whose visible text lives in a translation dictionary (filled at
115
+ runtime) will read as *statically* missing; audit the rendered DOM for the
116
+ final word (see Roadmap).
117
+
118
+ ## Security
119
+
120
+ `fetch()` refuses non-http(s) schemes and any host resolving to a loopback,
121
+ private, link-local, reserved or multicast address, so the library can be
122
+ wired into "enter your URL" scan forms without handing callers a probe into
123
+ the host network. The guard is best-effort (no DNS-rebinding defense) — for
124
+ untrusted input at scale, front it with a proxy allowlist.
125
+
126
+ ## Roadmap
127
+
128
+ - `--i18n` runtime layer: apply a key/value dictionary before auditing
129
+ (ported from the battle-tested original).
130
+ - GitHub Action wrapper.
131
+ - Browser-measured WCAG 2.2 checks (2.5.8 target size, 2.4.7 focus,
132
+ 1.4.3 contrast) as an optional `[browser]` extra (Playwright).
133
+
134
+ ## Provenance
135
+
136
+ The resolver is a hardened port of an auditor written for a production
137
+ PWA, where four measurement bugs (void-tag stack shifting, early
138
+ `</span>` closure bypassing a wrapping `<label>`, missing `label[for]`
139
+ map, wrapping labels not recognized) were found via live measurement and
140
+ fixed; their regression scenarios ship as tests in this repository.
141
+
142
+ ## License
143
+
144
+ Apache-2.0
@@ -0,0 +1,117 @@
1
+ # a11y-ad — browserless WCAG 4.1.2 accessible-name auditor
2
+
3
+ `a11y-ad` audits HTML for **missing accessible names** (WCAG 4.1.2 / "Name,
4
+ Role, Value") on every interactive element — no browser, no headless Chrome,
5
+ stdlib only. Built for CI.
6
+
7
+ ## Why another accessibility tool?
8
+
9
+ Most lightweight linters check *only* `aria-label`/`<label>` and flag every
10
+ button with visible text as a critical failure. In one audit run against a
11
+ fully-labelled application, a popular scanner reported **68 "critical" HTML
12
+ accessible-name issues — 0 of them real**, because visible button text,
13
+ `aria-labelledby`, and wrapping `<label>` elements are all valid accessible
14
+ names.
15
+
16
+ `a11y-ad` resolves the name the way assistive technology does, following the
17
+ WCAG 4.1.2 resolution order:
18
+
19
+ ```
20
+ aria-labelledby -> aria-label -> visible text -> <label for=id>
21
+ -> wrapping <label> -> title -> alt (input[type=image])
22
+ ```
23
+
24
+ and reports only the elements that end up with **no name at all**.
25
+
26
+ ## Scope (be honest about automated a11y coverage)
27
+
28
+ Automated tools in general catch roughly 30–50% of WCAG issues; manual
29
+ keyboard/screen-reader testing remains necessary. `a11y-ad` covers exactly
30
+ one failure class — missing accessible names — and does it with zero false
31
+ positives in the resolution cases above. Browser-measured checks (target
32
+ size, focus visibility, contrast, reduced motion) are out of scope for the
33
+ core; see Roadmap.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pip install a11y-ad
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ```bash
44
+ a11y-ad index.html # single file
45
+ a11y-ad src/ # directory (recursive, *.html)
46
+ a11y-ad https://example.com # URL
47
+ a11y-ad src/ --json # machine-readable
48
+ ```
49
+
50
+ Exit code is `1` when any interactive element lacks a name — use it as a CI
51
+ gate:
52
+
53
+ ```yaml
54
+ # GitHub Actions example
55
+ - run: pip install a11y-ad && a11y-ad dist/
56
+ ```
57
+
58
+ ### JSON payload
59
+
60
+ ```json
61
+ [
62
+ {
63
+ "target": "bad.html",
64
+ "total": 3,
65
+ "missing": ["line 3 <button >", "line 4 <input >"],
66
+ "sources": {"MISSING": 2, "text": 1},
67
+ "ok": false
68
+ }
69
+ ]
70
+ ```
71
+
72
+ ### Library
73
+
74
+ ```python
75
+ from a11y_ad import audit, audit_file, audit_tree, fetch
76
+
77
+ r = audit('<button aria-labelledby="h1">Edit</button>')
78
+ r.ok # True
79
+ r.elements[0] # Element(tag='button', name='...', source='aria-labelledby')
80
+ r.missing # elements with no accessible name
81
+ ```
82
+
83
+ ## Exclusions & semantics
84
+
85
+ - `<a>` without `href` and `<input type="hidden">` are not interactive → skipped.
86
+ - `aria-hidden="true"` counts as *named* (it is intentionally hidden from AT).
87
+ - Elements whose visible text lives in a translation dictionary (filled at
88
+ runtime) will read as *statically* missing; audit the rendered DOM for the
89
+ final word (see Roadmap).
90
+
91
+ ## Security
92
+
93
+ `fetch()` refuses non-http(s) schemes and any host resolving to a loopback,
94
+ private, link-local, reserved or multicast address, so the library can be
95
+ wired into "enter your URL" scan forms without handing callers a probe into
96
+ the host network. The guard is best-effort (no DNS-rebinding defense) — for
97
+ untrusted input at scale, front it with a proxy allowlist.
98
+
99
+ ## Roadmap
100
+
101
+ - `--i18n` runtime layer: apply a key/value dictionary before auditing
102
+ (ported from the battle-tested original).
103
+ - GitHub Action wrapper.
104
+ - Browser-measured WCAG 2.2 checks (2.5.8 target size, 2.4.7 focus,
105
+ 1.4.3 contrast) as an optional `[browser]` extra (Playwright).
106
+
107
+ ## Provenance
108
+
109
+ The resolver is a hardened port of an auditor written for a production
110
+ PWA, where four measurement bugs (void-tag stack shifting, early
111
+ `</span>` closure bypassing a wrapping `<label>`, missing `label[for]`
112
+ map, wrapping labels not recognized) were found via live measurement and
113
+ fixed; their regression scenarios ship as tests in this repository.
114
+
115
+ ## License
116
+
117
+ Apache-2.0
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "a11y-ad"
7
+ version = "0.1.0"
8
+ description = "Browserless WCAG 4.1.2 accessible-name auditor for HTML — resolves aria labels, visible text, <label> bindings and titles, and reports every interactive element with no accessible name."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "goun7" }]
13
+ keywords = [
14
+ "accessibility", "a11y", "wcag", "wcag22", "aria",
15
+ "accessible-name", "audit", "cli", "html", "eaa",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "License :: OSI Approved :: Apache Software License",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.9",
25
+ "Programming Language :: Python :: 3.10",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Topic :: Software Development :: Quality Assurance",
29
+ "Topic :: Text Processing :: Markup :: HTML",
30
+ ]
31
+ dependencies = []
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/goun7/a11y-ad"
35
+ Issues = "https://github.com/goun7/a11y-ad/issues"
36
+ Changelog = "https://github.com/goun7/a11y-ad/blob/main/CHANGELOG.md"
37
+
38
+ [project.scripts]
39
+ a11y-ad = "a11y_ad.cli:main"
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
43
+
44
+ [tool.pytest.ini_options]
45
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,11 @@
1
+ """a11y-ad — browserless WCAG 4.1.2 accessible-name auditor."""
2
+
3
+ from .core import (AuditResult, Element, FetchError, audit, audit_file,
4
+ audit_tree, fetch)
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = [
9
+ "AuditResult", "Element", "FetchError", "audit", "audit_file",
10
+ "audit_tree", "fetch", "__version__",
11
+ ]
@@ -0,0 +1,77 @@
1
+ """CLI: `a11y-ad <file.html | directory | URL> ... [--json]`
2
+
3
+ Exit codes (CI-friendly):
4
+ 0 — every interactive element has an accessible name
5
+ 1 — at least one missing name (or audit error)
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import List, Tuple
15
+
16
+ from .core import AuditResult, audit_file, audit_tree, fetch
17
+
18
+
19
+ def _collect(targets: List[str]) -> List[Tuple[str, AuditResult]]:
20
+ out: List[Tuple[str, AuditResult]] = []
21
+ for t in targets:
22
+ if t.startswith(("http://", "https://")):
23
+ out.append((t, fetch(t)))
24
+ continue
25
+ p = Path(t)
26
+ if p.is_dir():
27
+ for path, res in audit_tree(p).items():
28
+ out.append((str(path), res))
29
+ else:
30
+ out.append((str(p), audit_file(p)))
31
+ return out
32
+
33
+
34
+ def _summary(label: str, res: AuditResult) -> str:
35
+ srcs = ", ".join("%s=%d" % kv for kv in sorted(res.sources.items()))
36
+ lines = ["%s: %d interactive element(s), %d without accessible name [%s]"
37
+ % (label, res.total, len(res.missing), srcs)]
38
+ lines += [" MISSING " + e.describe() for e in res.missing[:10]]
39
+ if len(res.missing) > 10:
40
+ lines.append(" ... and %d more" % (len(res.missing) - 10))
41
+ return "\n".join(lines)
42
+
43
+
44
+ def main(argv=None) -> int:
45
+ ap = argparse.ArgumentParser(
46
+ prog="a11y-ad",
47
+ description="Browserless WCAG 4.1.2 accessible-name auditor.")
48
+ ap.add_argument("targets", nargs="+",
49
+ help="HTML file, directory (recursive *.html) or URL")
50
+ ap.add_argument("--json", action="store_true",
51
+ help="machine-readable JSON output")
52
+ args = ap.parse_args(argv)
53
+
54
+ try:
55
+ results = _collect(args.targets)
56
+ except Exception as exc: # noqa: BLE001 — CLI boundary
57
+ print("error: %s" % exc, file=sys.stderr)
58
+ return 1
59
+
60
+ if args.json:
61
+ payload = [{
62
+ "target": label,
63
+ "total": r.total,
64
+ "missing": [e.describe() for e in r.missing],
65
+ "sources": r.sources,
66
+ "ok": r.ok,
67
+ } for label, r in results]
68
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
69
+ else:
70
+ for label, r in results:
71
+ print(_summary(label, r))
72
+
73
+ return 0 if all(r.ok for _, r in results) else 1
74
+
75
+
76
+ if __name__ == "__main__":
77
+ raise SystemExit(main())
@@ -0,0 +1,309 @@
1
+ """a11y-ad — browserless WCAG 4.1.2 accessible-name auditor.
2
+
3
+ Core resolver ported from an auditor built for a production PWA, where it
4
+ was hardened against four measurement bugs recorded during development.
5
+ Constraint notes from that port are kept inline.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ipaddress
11
+ import pathlib
12
+ import socket
13
+ import urllib.request
14
+ import urllib.parse
15
+ from dataclasses import dataclass, field
16
+ from html.parser import HTMLParser
17
+ from typing import Dict, List, Optional, Tuple
18
+
19
+ __all__ = ["Element", "AuditResult", "audit", "audit_file", "audit_tree", "fetch"]
20
+
21
+ INTERACTIVE = ("button", "a", "input", "select", "textarea")
22
+ VOID = ("input", "img", "br", "hr", "meta", "link", "source", "area",
23
+ "base", "col", "embed", "param", "track", "wbr")
24
+ SKIP = {"script", "style", "template"}
25
+
26
+ # Source of an accessible name, in WCAG 4.1.2 resolution order.
27
+ SRC_LABELLEDBY = "aria-labelledby"
28
+ SRC_ARIA_LABEL = "aria-label"
29
+ SRC_TEXT = "text"
30
+ SRC_LABEL_FOR = "label[for]"
31
+ SRC_WRAPPING_LABEL = "wrapping-label"
32
+ SRC_TITLE = "title"
33
+ SRC_ALT_IMAGE = "alt"
34
+ SRC_HIDDEN = "aria-hidden"
35
+ SRC_MISSING = "MISSING"
36
+
37
+
38
+ @dataclass
39
+ class Element:
40
+ """One interactive element and its resolved accessible name."""
41
+
42
+ tag: str
43
+ line: int
44
+ attrs: Dict[str, str]
45
+ name: str
46
+ source: str
47
+ # Stable key so two audit passes (e.g. pre/post runtime i18n) can be
48
+ # diffed: element order never changes when only text is injected.
49
+ @property
50
+ def key(self) -> Tuple[int, str, str]:
51
+ return (self.line, self.tag,
52
+ self.attrs.get("id") or self.attrs.get("aria-label") or "")
53
+
54
+ def describe(self) -> str:
55
+ hint = self.attrs.get("id") or self.attrs.get("aria-label") or ""
56
+ return "line %d <%s %s>" % (self.line, self.tag, hint)
57
+
58
+
59
+ @dataclass
60
+ class AuditResult:
61
+ total: int
62
+ elements: List[Element]
63
+ sources: Dict[str, int]
64
+ missing: List[Element] = field(default_factory=list)
65
+
66
+ @property
67
+ def ok(self) -> bool:
68
+ return not self.missing
69
+
70
+
71
+ class _LabelFor(HTMLParser):
72
+ """Collects <label for="id">text</label> bindings."""
73
+
74
+ def __init__(self) -> None:
75
+ super().__init__(convert_charrefs=True)
76
+ self.target: Optional[str] = None
77
+ self.acc: List[str] = []
78
+ self.map: Dict[str, str] = {}
79
+
80
+ def handle_starttag(self, tag, attrs):
81
+ d = {k: (v or "") for k, v in attrs}
82
+ if tag == "label" and d.get("for"):
83
+ self.target = d["for"]
84
+ self.acc = []
85
+
86
+ def handle_endtag(self, tag):
87
+ if tag == "label" and self.target:
88
+ v = " ".join(x for x in self.acc if x).strip()
89
+ if v:
90
+ self.map[self.target] = v
91
+ self.target = None
92
+ self.acc = []
93
+
94
+ def handle_data(self, data):
95
+ if self.target:
96
+ self.acc.append(" ".join(data.split()))
97
+
98
+
99
+ class _Parser(HTMLParser):
100
+ """Walks the HTML and captures every interactive element with context.
101
+
102
+ Measurement-bug notes (from the ported implementation):
103
+ #1 wrapping <label> must be recognised at all
104
+ #2 void tags (<input>) must NOT be pushed on the stack — they have
105
+ no close tag and would shift the <label> frame
106
+ #4 an `</span>` close tag must not close an open <label> early:
107
+ end-tag matching has to check BOTH the `tag` and `kind` fields
108
+ """
109
+
110
+ def __init__(self) -> None:
111
+ super().__init__(convert_charrefs=True)
112
+ self.elements: List[dict] = []
113
+ self.stack: List[dict] = []
114
+ self.wrapping: List[dict] = []
115
+ # generic (non-interactive) elements carrying an id, kept by
116
+ # reference: their text accumulates during parsing, so the
117
+ # id->text map must be resolved AFTER feed() completes.
118
+ self.id_nodes: Dict[str, dict] = {}
119
+
120
+ def handle_starttag(self, tag, attrs):
121
+ d = {k: (v or "") for k, v in attrs}
122
+ if tag in SKIP:
123
+ return
124
+ if tag == "label":
125
+ c = {"kind": "label", "texts": []}
126
+ self.wrapping.append(c)
127
+ self.stack.append(c)
128
+ return
129
+ if tag in INTERACTIVE:
130
+ n = {"tag": tag, "attrs": d, "texts": [],
131
+ "line": self.getpos()[0],
132
+ "wrapping": self.wrapping[-1] if self.wrapping else None}
133
+ self.elements.append(n)
134
+ if self.wrapping:
135
+ self.wrapping[-1].setdefault(
136
+ "children", self.wrapping[-1].get("children", []) + [n])
137
+ if tag in VOID: # bug #2
138
+ return
139
+ self.stack.append(n)
140
+ return
141
+ if tag in VOID:
142
+ alt = d.get("alt", "")
143
+ if alt:
144
+ for c in self.stack[-3:]:
145
+ c.setdefault("alts", []).append(alt)
146
+ return
147
+ node = {"kind": tag, "texts": [], "attrs": d}
148
+ aid = d.get("id")
149
+ if aid:
150
+ self.id_nodes[aid] = node
151
+ self.stack.append(node)
152
+
153
+ def handle_data(self, data):
154
+ v = " ".join(data.split())
155
+ if not v:
156
+ return
157
+ # [-3:] lookback: text may live one or two inline elements deep
158
+ # (e.g. <button><span><b>Go</b></span></button>).
159
+ for c in self.stack[-3:]:
160
+ c["texts"].append(v)
161
+
162
+ def handle_endtag(self, tag):
163
+ # bug #4: match on tag AND kind, never pop past an open <label>.
164
+ while self.stack:
165
+ c = self.stack.pop()
166
+ if c.get("kind") == "label" and tag == "label":
167
+ if self.wrapping and self.wrapping[-1] is c:
168
+ self.wrapping.pop()
169
+ break
170
+ if c.get("tag") == tag or c.get("kind") == tag:
171
+ break
172
+
173
+
174
+ def _text_of(node: dict) -> str:
175
+ a = " ".join(x for x in node.get("texts", []) if x)
176
+ if node.get("alts"):
177
+ b = " ".join(x for x in node["alts"] if x)
178
+ a = (a + " " + b).strip()
179
+ return a
180
+
181
+
182
+ def audit(html: str) -> AuditResult:
183
+ """Audit an HTML document for missing WCAG 4.1.2 accessible names.
184
+
185
+ Resolution order: aria-labelledby -> aria-label -> visible text ->
186
+ <label for=id> -> wrapping <label> -> title -> alt (input[type=image]).
187
+ Excluded from the audit: <a> without href, <input type=hidden>.
188
+ """
189
+ p = _Parser()
190
+ p.feed(html)
191
+ p.close()
192
+ lf = _LabelFor()
193
+ lf.feed(html)
194
+ lf.close()
195
+
196
+ # id -> accessible text, collected for EVERY element (not only
197
+ # interactive ones): aria-labelledby may point at a heading or span.
198
+ id_text: Dict[str, str] = {}
199
+ for e in p.elements:
200
+ if e["attrs"].get("id"):
201
+ id_text[e["attrs"]["id"]] = _text_of(e)
202
+ for aid, node in p.id_nodes.items():
203
+ if aid not in id_text:
204
+ id_text[aid] = _text_of(node)
205
+
206
+ total = 0
207
+ missing: List[Element] = []
208
+ sources: Dict[str, int] = {}
209
+ elements: List[Element] = []
210
+ for e in p.elements:
211
+ d = e["attrs"]
212
+ if e["tag"] == "a" and not d.get("href"):
213
+ continue
214
+ if e["tag"] == "input" and d.get("type") == "hidden":
215
+ continue
216
+ total += 1
217
+ source = SRC_MISSING
218
+ name = ""
219
+ if d.get("aria-hidden") == "true":
220
+ source = SRC_HIDDEN
221
+ elif d.get("aria-labelledby"):
222
+ parts = [id_text.get(x.strip(), "")
223
+ for x in d["aria-labelledby"].split()]
224
+ joined = " ".join(x for x in parts if x).strip()
225
+ if joined:
226
+ source, name = SRC_LABELLEDBY, joined
227
+ elif d.get("aria-label"):
228
+ source, name = SRC_ARIA_LABEL, d["aria-label"]
229
+ elif _text_of(e):
230
+ source, name = SRC_TEXT, _text_of(e)
231
+ elif d.get("id") and d["id"] in lf.map:
232
+ source, name = SRC_LABEL_FOR, lf.map[d["id"]]
233
+ elif e.get("wrapping") is not None and _text_of(e["wrapping"]):
234
+ source, name = SRC_WRAPPING_LABEL, _text_of(e["wrapping"])
235
+ elif d.get("title"):
236
+ source, name = SRC_TITLE, d["title"]
237
+ elif (e["tag"] == "input" and d.get("type") == "image"
238
+ and d.get("alt")):
239
+ source, name = SRC_ALT_IMAGE, d["alt"]
240
+ sources[source] = sources.get(source, 0) + 1
241
+ el = Element(tag=e["tag"], line=e["line"], attrs=d,
242
+ name=name, source=source)
243
+ elements.append(el)
244
+ if source == SRC_MISSING:
245
+ missing.append(el)
246
+ return AuditResult(total=total, elements=elements,
247
+ sources=sources, missing=missing)
248
+
249
+
250
+ def audit_file(path) -> AuditResult:
251
+ return audit(pathlib.Path(path).read_text(encoding="utf-8"))
252
+
253
+
254
+ def audit_tree(root) -> Dict[pathlib.Path, AuditResult]:
255
+ """Audit every *.html file under a directory (recursive)."""
256
+ root = pathlib.Path(root)
257
+ return {p: audit_file(p) for p in sorted(root.rglob("*.html"))}
258
+
259
+
260
+ class FetchError(ValueError):
261
+ """Raised when a URL is refused by the SSRF guard."""
262
+
263
+
264
+ def _guard_url(url: str) -> str:
265
+ """Refuse URLs that could reach internal/private infrastructure.
266
+
267
+ fetch() is safe on a developer CLI, but this library is also used by
268
+ web frontends ("enter your URL" scan forms). There, an unguarded
269
+ fetch would let a caller probe localhost, link-local metadata
270
+ endpoints, or the private network behind the server.
271
+ """
272
+ parsed = urllib.parse.urlparse(url)
273
+ if parsed.scheme not in ("http", "https"):
274
+ raise FetchError("only http(s) URLs are allowed, got %r" % parsed.scheme)
275
+ host = parsed.hostname
276
+ if not host:
277
+ raise FetchError("URL without host")
278
+ if host in ("localhost",) or host.endswith((".local", ".internal", ".home")):
279
+ raise FetchError("refusing internal hostname %r" % host)
280
+ try:
281
+ infos = socket.getaddrinfo(host, None)
282
+ except socket.gaierror as exc:
283
+ raise FetchError("cannot resolve host %r: %s" % (host, exc))
284
+ seen: set = set()
285
+ for info in infos:
286
+ ip = ipaddress.ip_address(info[4][0])
287
+ if ip in seen:
288
+ continue
289
+ seen.add(ip)
290
+ if (ip.is_private or ip.is_loopback or ip.is_link_local
291
+ or ip.is_reserved or ip.is_multicast or ip.is_unspecified):
292
+ raise FetchError(
293
+ "refusing to fetch private/reserved address %s (host %r)"
294
+ % (ip, host))
295
+ return url
296
+
297
+
298
+ def fetch(url: str) -> AuditResult:
299
+ """Fetch a URL over HTTP(S) and audit the response body.
300
+
301
+ Refuses non-http(s) schemes and any host resolving to a loopback,
302
+ private, link-local, reserved or multicast address (SSRF guard).
303
+ Best-effort: DNS-rebinding TOCTOU is not defended against — never
304
+ expose fetch() to untrusted input without a proxy allowlist.
305
+ """
306
+ _guard_url(url)
307
+ req = urllib.request.Request(url, headers={"User-Agent": "a11y-ad/0.1"})
308
+ with urllib.request.urlopen(req, timeout=30) as r:
309
+ return audit(r.read().decode("utf-8", errors="replace"))
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.4
2
+ Name: a11y-ad
3
+ Version: 0.1.0
4
+ Summary: Browserless WCAG 4.1.2 accessible-name auditor for HTML — resolves aria labels, visible text, <label> bindings and titles, and reports every interactive element with no accessible name.
5
+ Author: goun7
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/goun7/a11y-ad
8
+ Project-URL: Issues, https://github.com/goun7/a11y-ad/issues
9
+ Project-URL: Changelog, https://github.com/goun7/a11y-ad/blob/main/CHANGELOG.md
10
+ Keywords: accessibility,a11y,wcag,wcag22,aria,accessible-name,audit,cli,html,eaa
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Software Development :: Quality Assurance
22
+ Classifier: Topic :: Text Processing :: Markup :: HTML
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Dynamic: license-file
27
+
28
+ # a11y-ad — browserless WCAG 4.1.2 accessible-name auditor
29
+
30
+ `a11y-ad` audits HTML for **missing accessible names** (WCAG 4.1.2 / "Name,
31
+ Role, Value") on every interactive element — no browser, no headless Chrome,
32
+ stdlib only. Built for CI.
33
+
34
+ ## Why another accessibility tool?
35
+
36
+ Most lightweight linters check *only* `aria-label`/`<label>` and flag every
37
+ button with visible text as a critical failure. In one audit run against a
38
+ fully-labelled application, a popular scanner reported **68 "critical" HTML
39
+ accessible-name issues — 0 of them real**, because visible button text,
40
+ `aria-labelledby`, and wrapping `<label>` elements are all valid accessible
41
+ names.
42
+
43
+ `a11y-ad` resolves the name the way assistive technology does, following the
44
+ WCAG 4.1.2 resolution order:
45
+
46
+ ```
47
+ aria-labelledby -> aria-label -> visible text -> <label for=id>
48
+ -> wrapping <label> -> title -> alt (input[type=image])
49
+ ```
50
+
51
+ and reports only the elements that end up with **no name at all**.
52
+
53
+ ## Scope (be honest about automated a11y coverage)
54
+
55
+ Automated tools in general catch roughly 30–50% of WCAG issues; manual
56
+ keyboard/screen-reader testing remains necessary. `a11y-ad` covers exactly
57
+ one failure class — missing accessible names — and does it with zero false
58
+ positives in the resolution cases above. Browser-measured checks (target
59
+ size, focus visibility, contrast, reduced motion) are out of scope for the
60
+ core; see Roadmap.
61
+
62
+ ## Install
63
+
64
+ ```bash
65
+ pip install a11y-ad
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ ```bash
71
+ a11y-ad index.html # single file
72
+ a11y-ad src/ # directory (recursive, *.html)
73
+ a11y-ad https://example.com # URL
74
+ a11y-ad src/ --json # machine-readable
75
+ ```
76
+
77
+ Exit code is `1` when any interactive element lacks a name — use it as a CI
78
+ gate:
79
+
80
+ ```yaml
81
+ # GitHub Actions example
82
+ - run: pip install a11y-ad && a11y-ad dist/
83
+ ```
84
+
85
+ ### JSON payload
86
+
87
+ ```json
88
+ [
89
+ {
90
+ "target": "bad.html",
91
+ "total": 3,
92
+ "missing": ["line 3 <button >", "line 4 <input >"],
93
+ "sources": {"MISSING": 2, "text": 1},
94
+ "ok": false
95
+ }
96
+ ]
97
+ ```
98
+
99
+ ### Library
100
+
101
+ ```python
102
+ from a11y_ad import audit, audit_file, audit_tree, fetch
103
+
104
+ r = audit('<button aria-labelledby="h1">Edit</button>')
105
+ r.ok # True
106
+ r.elements[0] # Element(tag='button', name='...', source='aria-labelledby')
107
+ r.missing # elements with no accessible name
108
+ ```
109
+
110
+ ## Exclusions & semantics
111
+
112
+ - `<a>` without `href` and `<input type="hidden">` are not interactive → skipped.
113
+ - `aria-hidden="true"` counts as *named* (it is intentionally hidden from AT).
114
+ - Elements whose visible text lives in a translation dictionary (filled at
115
+ runtime) will read as *statically* missing; audit the rendered DOM for the
116
+ final word (see Roadmap).
117
+
118
+ ## Security
119
+
120
+ `fetch()` refuses non-http(s) schemes and any host resolving to a loopback,
121
+ private, link-local, reserved or multicast address, so the library can be
122
+ wired into "enter your URL" scan forms without handing callers a probe into
123
+ the host network. The guard is best-effort (no DNS-rebinding defense) — for
124
+ untrusted input at scale, front it with a proxy allowlist.
125
+
126
+ ## Roadmap
127
+
128
+ - `--i18n` runtime layer: apply a key/value dictionary before auditing
129
+ (ported from the battle-tested original).
130
+ - GitHub Action wrapper.
131
+ - Browser-measured WCAG 2.2 checks (2.5.8 target size, 2.4.7 focus,
132
+ 1.4.3 contrast) as an optional `[browser]` extra (Playwright).
133
+
134
+ ## Provenance
135
+
136
+ The resolver is a hardened port of an auditor written for a production
137
+ PWA, where four measurement bugs (void-tag stack shifting, early
138
+ `</span>` closure bypassing a wrapping `<label>`, missing `label[for]`
139
+ map, wrapping labels not recognized) were found via live measurement and
140
+ fixed; their regression scenarios ship as tests in this repository.
141
+
142
+ ## License
143
+
144
+ Apache-2.0
@@ -0,0 +1,18 @@
1
+ CHANGELOG.md
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ pyproject.toml
6
+ src/a11y_ad/__init__.py
7
+ src/a11y_ad/cli.py
8
+ src/a11y_ad/core.py
9
+ src/a11y_ad.egg-info/PKG-INFO
10
+ src/a11y_ad.egg-info/SOURCES.txt
11
+ src/a11y_ad.egg-info/dependency_links.txt
12
+ src/a11y_ad.egg-info/entry_points.txt
13
+ src/a11y_ad.egg-info/top_level.txt
14
+ tests/test_cli.py
15
+ tests/test_core.py
16
+ tests/test_guard.py
17
+ tests/fixtures/bad.html
18
+ tests/fixtures/good.html
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ a11y-ad = a11y_ad.cli:main
@@ -0,0 +1 @@
1
+ a11y_ad
@@ -0,0 +1,6 @@
1
+ <!doctype html>
2
+ <html><body>
3
+ <button><svg viewBox="0 0 8 8"></svg></button>
4
+ <input type="text">
5
+ <a href="/ok">All good link</a>
6
+ </body></html>
@@ -0,0 +1,8 @@
1
+ <!doctype html>
2
+ <html><body>
3
+ <button>Save changes</button>
4
+ <input id="mail" type="email">
5
+ <label for="mail">E-mail address</label>
6
+ <label>Accept<input type="checkbox"></label>
7
+ <button aria-label="Close">X</button>
8
+ </body></html>
@@ -0,0 +1,44 @@
1
+ """CLI tests: exit codes, JSON payload, directory scanning."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from a11y_ad.cli import main
9
+
10
+ FIXTURES = Path(__file__).parent / "fixtures"
11
+
12
+
13
+ def test_clean_file_exits_zero(capsys):
14
+ assert main([str(FIXTURES / "good.html")]) == 0
15
+ out = capsys.readouterr().out
16
+ assert "0 without accessible name" in out
17
+
18
+
19
+ def test_dirty_file_exits_one(capsys):
20
+ assert main([str(FIXTURES / "bad.html")]) == 1
21
+ out = capsys.readouterr().out
22
+ assert "MISSING" in out
23
+
24
+
25
+ def test_directory_scan_and_json(capsys):
26
+ rc = main([str(FIXTURES), "--json"])
27
+ payload = json.loads(capsys.readouterr().out)
28
+ names = {Path(p["target"]).name for p in payload}
29
+ assert names == {"good.html", "bad.html"}
30
+ bad = next(p for p in payload if p["target"].endswith("bad.html"))
31
+ assert bad["ok"] is False and bad["total"] == 3 and len(bad["missing"]) == 2
32
+ good = next(p for p in payload if p["target"].endswith("good.html"))
33
+ assert good["ok"] is True
34
+ assert rc == 1 # one of the files is dirty
35
+
36
+
37
+ def test_missing_file_is_error(capsys):
38
+ assert main(["/nonexistent/x.html"]) == 1
39
+ assert "error" in capsys.readouterr().err
40
+
41
+
42
+ @pytest.mark.parametrize("fixture", ["good.html", "bad.html"])
43
+ def test_fixture_files_exist(fixture):
44
+ assert (FIXTURES / fixture).is_file()
@@ -0,0 +1,131 @@
1
+ """a11y-ad core tests — includes regression scenarios ported from the
2
+ original production-PWA implementation, where four measurement bugs were
3
+ found and fixed during development (see PLAN.md in that project).
4
+ """
5
+
6
+ from a11y_ad import audit
7
+
8
+ # ---------------------------------------------------------------- named
9
+
10
+
11
+ def test_visible_text():
12
+ r = audit("<button>Save</button>")
13
+ assert r.total == 1 and r.ok
14
+ assert r.elements[0].source == "text"
15
+ assert r.elements[0].name == "Save"
16
+
17
+
18
+ def test_nested_inline_text():
19
+ # text may sit two inline elements deep ([-3:] lookback)
20
+ r = audit("<button><span><b>Go</b></span></button>")
21
+ assert r.ok and r.elements[0].source == "text"
22
+
23
+
24
+ def test_aria_label():
25
+ r = audit('<button aria-label="Close dialog">X</button>')
26
+ assert r.ok
27
+ assert r.elements[0].source == "aria-label"
28
+ assert r.elements[0].name == "Close dialog"
29
+
30
+
31
+ def test_aria_labelledby_points_at_heading():
32
+ # aria-labelledby may reference a NON-interactive element (a heading):
33
+ # the id->text map must cover every element, not only interactive ones.
34
+ html = ('<h3 id="sec1">Account settings</h3>'
35
+ '<button aria-labelledby="sec1">Edit</button>')
36
+ r = audit(html)
37
+ assert r.ok
38
+ assert r.elements[0].source == "aria-labelledby"
39
+ assert r.elements[0].name == "Account settings"
40
+
41
+
42
+ def test_label_for():
43
+ html = ('<input id="email" type="text">'
44
+ '<label for="email">Your e-mail</label>')
45
+ r = audit(html)
46
+ assert r.ok
47
+ assert r.elements[0].source == "label[for]"
48
+ assert r.elements[0].name == "Your e-mail"
49
+
50
+
51
+ def test_wrapping_label():
52
+ html = "<label>Newsletter<input type=\"checkbox\"></label>"
53
+ r = audit(html)
54
+ assert r.ok
55
+ assert r.elements[0].source == "wrapping-label"
56
+
57
+
58
+ def test_title_fallback():
59
+ r = audit('<button title="Print page"><svg></svg></button>')
60
+ assert r.ok
61
+ assert r.elements[0].source == "title"
62
+
63
+
64
+ def test_input_image_alt():
65
+ r = audit('<input type="image" alt="Search" src="s.png">')
66
+ assert r.ok
67
+ assert r.elements[0].source == "alt"
68
+
69
+
70
+ def test_aria_hidden_counted_as_named():
71
+ r = audit('<button aria-hidden="true">::</button>')
72
+ assert r.ok
73
+ assert r.elements[0].source == "aria-hidden"
74
+
75
+
76
+ # ---------------------------------------------------------------- missing
77
+
78
+
79
+ def test_missing_button():
80
+ r = audit("<button><svg></svg></button>")
81
+ assert not r.ok
82
+ assert r.missing[0].tag == "button"
83
+ assert r.missing[0].describe().startswith("line 1 <button")
84
+
85
+
86
+ def test_exclusions():
87
+ html = ('<input type="hidden" value="x">'
88
+ '<a id="nohref">plain anchor</a>')
89
+ r = audit(html)
90
+ assert r.total == 0 # both excluded
91
+
92
+
93
+ # ------------------------------------------------- ported regressions
94
+
95
+
96
+ def test_void_tag_does_not_shift_label_frame():
97
+ # original bug #2/#3: <input> is void; if it were pushed on the
98
+ # stack the later <label> frame would be lost and the input would
99
+ # falsely read as missing.
100
+ html = ('<form><input id="q" type="text"></form>'
101
+ '<label for="q">Search term</label>')
102
+ r = audit(html)
103
+ assert r.ok and r.elements[0].source == "label[for]"
104
+
105
+
106
+ def test_span_close_does_not_close_label_early():
107
+ # original bug #4: </span> inside a label must not pop the label
108
+ # off the stack; the input after it still resolves to the wrapping
109
+ # label text.
110
+ html = ("<label>Accept terms<span> (required)</span>"
111
+ "<input type=\"checkbox\"></label>")
112
+ r = audit(html)
113
+ assert r.ok
114
+ assert r.elements[0].source == "wrapping-label"
115
+
116
+
117
+ def test_negative_control_text_really_counts():
118
+ # if the auditor counted nothing, stripping the visible text would
119
+ # not change the result — guard against vacuous green.
120
+ good = audit("<button>Save</button>")
121
+ bad = audit("<button></button>")
122
+ assert good.ok and not bad.ok
123
+ assert len(bad.missing) - len(good.missing) >= 1
124
+
125
+
126
+ def test_sources_breakdown():
127
+ html = ('<button>A</button><button aria-label="B">x</button>'
128
+ "<button></button>")
129
+ r = audit(html)
130
+ assert r.total == 3
131
+ assert r.sources == {"text": 1, "aria-label": 1, "MISSING": 1}
@@ -0,0 +1,36 @@
1
+ """SSRF guard tests — fetch() must refuse internal/private targets."""
2
+
3
+ import pytest
4
+
5
+ from a11y_ad import FetchError
6
+ from a11y_ad.core import _guard_url
7
+
8
+
9
+ @pytest.mark.parametrize("url", [
10
+ "file:///etc/passwd",
11
+ "ftp://example.com/x.html",
12
+ "javascript:alert(1)",
13
+ "http://localhost/x",
14
+ "http://localhost:8080/admin",
15
+ "http://127.0.0.1/x",
16
+ "http://0.0.0.0/x",
17
+ "http://169.254.169.254/latest/meta-data/",
18
+ "http://10.0.0.1/x",
19
+ "http://192.168.1.10/x",
20
+ "http://172.16.0.5/x",
21
+ "http://[::1]/x",
22
+ "http://metadata.internal/x",
23
+ "http://printer.local/x",
24
+ ])
25
+ def test_guard_refuses_internal_targets(url):
26
+ with pytest.raises(FetchError):
27
+ _guard_url(url)
28
+
29
+
30
+ def test_guard_accepts_public_url():
31
+ assert _guard_url("https://example.com/") == "https://example.com/"
32
+
33
+
34
+ def test_guard_rejects_unresolvable_host():
35
+ with pytest.raises(FetchError):
36
+ _guard_url("https://this-host-does-not-exist-a11y-ad.invalid/")