auditmysite 1.7.2

Resource-efficient WCAG 2.2 AA Accessibility Checker in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Invariant tests for the report model — each test pins a known-correct
//! property so regressions are caught immediately rather than via manual
//! release review.

use crate::audit::normalized::normalize;
use crate::audit::AuditReport;
use crate::cli::WcagLevel;
use crate::output::json::UnifiedReport;
use crate::taxonomy::Severity;
use crate::wcag::{Violation, WcagResults};

fn make_report(wcag_results: WcagResults) -> AuditReport {
    AuditReport::new(
        "https://example.com".to_string(),
        WcagLevel::AA,
        wcag_results,
        100,
    )
}

fn make_security_from_headers(
    headers: crate::security::SecurityHeaders,
) -> crate::security::SecurityAnalysis {
    use crate::security::{
        calculate_security_score, generate_security_issues, SecurityAnalysis, SslInfo,
    };

    // No HSTS bonus so the Low-penalty from a missing header is not cancelled out.
    let ssl = SslInfo {
        https: true,
        valid_certificate: true,
        has_hsts: false,
        ..Default::default()
    };
    let issues = generate_security_issues(&headers, true);
    let score = calculate_security_score(&headers, &ssl, &issues);
    SecurityAnalysis {
        score,
        grade: String::new(),
        headers,
        ssl,
        issues,
        recommendations: vec![],
        protection: Default::default(),
        sourcemap_leaks: Default::default(),
    }
}

// ─── Serialization invariants ─────────────────────────────────────────────────

#[test]
fn ux_score_propagated_to_summary() {
    use crate::accessibility::AXTree;
    use crate::ux::analyze_ux;

    let mut report = make_report(WcagResults::new());
    report.ux = Some(analyze_ux(&AXTree::new()));
    let normalized = normalize(&report);
    let unified = UnifiedReport::single(&normalized, &report);

    assert!(
        unified.summary.ux_score.is_some(),
        "summary.ux_score must be Some when UX module is active"
    );
    let ux_entry = normalized
        .normalized
        .module_scores
        .iter()
        .find(|m| m.name == "UX")
        .unwrap();
    assert_eq!(unified.summary.ux_score, Some(ux_entry.score));
}

#[test]
fn journey_score_propagated_to_summary() {
    use crate::accessibility::AXTree;
    use crate::journey::analyze_journey;

    let mut report = make_report(WcagResults::new());
    report.journey = Some(analyze_journey(&AXTree::new()));
    let normalized = normalize(&report);
    let unified = UnifiedReport::single(&normalized, &report);

    assert!(
        unified.summary.journey_score.is_some(),
        "summary.journey_score must be Some when Journey module is active"
    );
    let journey_entry = normalized
        .normalized
        .module_scores
        .iter()
        .find(|m| m.name == "Journey")
        .unwrap();
    assert_eq!(unified.summary.journey_score, Some(journey_entry.score));
}

/// Plan 29, D2: a letter grade claims the module's value counts. Only the
/// weighted modules may carry one — "Dark Mode: F" sat next to an F for
/// excluding screen-reader users and read as the same kind of verdict.
#[test]
fn only_weighted_modules_carry_a_letter_grade() {
    use crate::accessibility::AXTree;
    use crate::journey::analyze_journey;
    use crate::ux::analyze_ux;

    let mut report = make_report(WcagResults::new());
    report.ux = Some(analyze_ux(&AXTree::new()));
    report.journey = Some(analyze_journey(&AXTree::new()));
    let normalized = normalize(&report).normalized;

    assert!(
        normalized.module_scores.len() >= 3,
        "fixture must cover both weighted and indicator modules"
    );
    for entry in &normalized.module_scores {
        assert!(!entry.band.is_empty(), "{} carries no band", entry.name);
        assert_eq!(
            entry.grade.is_some(),
            entry.weight_pct > 0,
            "{} has weight {} but grade {:?}",
            entry.name,
            entry.weight_pct,
            entry.grade,
        );
    }
}

/// Plan 29, D4: "share of checks that did not complain" is not a measurement
/// of the page — adding a check that usually passes lifts every site. Content
/// Visibility therefore carries no module score at all.
#[test]
fn content_visibility_carries_no_module_score() {
    let report = make_report(WcagResults::new());
    let normalized = normalize(&report).normalized;

    assert!(
        !normalized
            .module_scores
            .iter()
            .any(|m| m.name == "Content Visibility"),
        "Content Visibility is reported through its counts, not as a score"
    );
}

/// Same rule one level down: an SEO signal category publishes how many of its
/// checks passed and how many there are, never a bare percentage.
#[test]
fn seo_signal_categories_publish_their_denominator() {
    use crate::seo::profile::build_content_profile;

    let seo = crate::seo::SeoAnalysis::default();
    let profile = build_content_profile(&seo, "en");
    assert!(
        !profile.signal_strength.categories.is_empty(),
        "fixture must produce signal categories"
    );
    for cat in &profile.signal_strength.categories {
        assert!(cat.total > 0, "{} has no checks", cat.name);
        assert_eq!(
            cat.total as usize,
            cat.checks.len(),
            "{} reports a total its own check list does not back",
            cat.name
        );
        assert!(
            cat.passed <= cat.total,
            "{} passed more than it has",
            cat.name
        );
    }
}

/// Plan 29, D3: an indicator that re-reads another module's result says so.
/// Without it, a reader takes SEO, AI Visibility and Source Quality agreeing
/// for three independent assessments.
#[test]
fn derived_indicators_name_the_modules_they_re_read() {
    use crate::accessibility::AXTree;
    use crate::journey::analyze_journey;
    use crate::ux::analyze_ux;

    let mut report = make_report(WcagResults::new());
    report.ux = Some(analyze_ux(&AXTree::new()));
    report.journey = Some(analyze_journey(&AXTree::new()));
    let normalized = normalize(&report).normalized;

    for entry in &normalized.module_scores {
        assert_eq!(
            entry.derived_from,
            crate::taxonomy::module_derived_from(&entry.name),
            "{} disagrees with the derived-from table",
            entry.name,
        );
        assert!(
            entry.derived_from.is_empty() || entry.weight_pct == 0,
            "{} carries weight although it only re-reads other modules",
            entry.name,
        );
    }
    let ux = normalized
        .module_scores
        .iter()
        .find(|m| m.name == "UX")
        .expect("UX entry");
    assert_eq!(ux.derived_from, vec!["accessibility".to_string()]);
}

/// Plan 29, D3: the accessibility result is reported by the Accessibility
/// module. Folding it into Source Quality's authority dimension and into the
/// AI citability score let one finding move four displayed numbers.
#[test]
fn accessibility_does_not_feed_source_quality_or_ai_visibility() {
    use crate::ai_visibility::analyze_ai_visibility;
    use crate::source_quality::analyze_source_quality;

    let mut clean = make_report(WcagResults::new());
    clean.accessibility.score = 100.0;
    let mut broken = make_report(WcagResults::new());
    broken.accessibility.score = 5.0;

    assert_eq!(
        analyze_source_quality(&clean).authority.score,
        analyze_source_quality(&broken).authority.score,
        "the accessibility score still moves Source Quality's authority dimension"
    );
    assert_eq!(
        analyze_ai_visibility(&clean).citation.dimension.score,
        analyze_ai_visibility(&broken).citation.dimension.score,
        "the accessibility score still moves the AI citability score"
    );
}

/// Plan 29, D1: the headline classification describes accessibility. It used
/// to hang off the weighted overall score, so an accessibility score of 20
/// reached the cover as a 39 that five other modules had lifted.
#[test]
fn grade_and_certificate_follow_the_accessibility_score() {
    use crate::audit::AccessibilityScorer;

    let mut report = make_report(WcagResults::new());
    report.accessibility.score = 30.0;
    // A module set that pulls the weighted overall well above accessibility.
    report.discoverability.seo = Some(crate::seo::SeoAnalysis {
        score: 100,
        ..Default::default()
    });
    let normalized = normalize(&report).normalized;

    assert!(
        normalized.overall_score > normalized.score,
        "fixture must separate the two scores: overall {} vs accessibility {}",
        normalized.overall_score,
        normalized.score,
    );
    assert_eq!(
        normalized.grade,
        AccessibilityScorer::calculate_grade(normalized.score as f32),
    );
    // The certificate may be risk-gated downwards, never lifted by the other
    // modules: the score-based value is its ceiling.
    let ceiling = AccessibilityScorer::calculate_certificate(normalized.score as f32);
    let from_overall = AccessibilityScorer::calculate_certificate(normalized.overall_score as f32);
    assert_ne!(
        ceiling, from_overall,
        "fixture must make the two bases disagree"
    );
    assert_ne!(
        normalized.certificate, from_overall,
        "certificate must not follow the weighted overall score"
    );
}

// ─── Performance measurement_warnings serialization ──────────────────────────

#[test]
fn measurement_warnings_present_in_json_when_set() {
    use crate::audit::PerformanceResults;
    use crate::performance::{PerformanceGrade, PerformanceScore, WebVitals};

    let mut report = make_report(WcagResults::new());
    report = report.with_performance(PerformanceResults {
        vitals: WebVitals::default(),
        score: PerformanceScore {
            overall: 72,
            grade: PerformanceGrade::Silver,
            lcp_score: None,
            fcp_score: None,
            cls_score: None,
            interactivity_score: None,
            si_score: None,
            metrics_available: 0,
            size_penalty: None,
            js_penalty: None,
            request_penalty: None,
            dom_penalty: None,
            is_capped: None,
        },
        render_blocking: None,
        content_weight: None,
        third_party: None,
        critical_chain: None,
        minification: None,
        animations: None,
        coverage: None,
        measurement_warnings: vec!["tbt_zero_heavy_page".to_string()],
    });
    let normalized = crate::audit::normalize(&report);
    let unified = UnifiedReport::single(&normalized, &report);
    let json_str = unified.to_json(false).unwrap();
    let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();

    let warnings = &json["pages"][0]["detail"]["modules"]["performance"]["measurement_warnings"];
    assert!(
        warnings.is_array(),
        "measurement_warnings must be an array in JSON when set"
    );
    assert_eq!(
        warnings[0].as_str(),
        Some("tbt_zero_heavy_page"),
        "first warning key must be 'tbt_zero_heavy_page'"
    );
}

// ─── Accessibility score invariants ──────────────────────────────────────────

#[test]
fn critical_violation_caps_accessibility_score() {
    use crate::audit::AccessibilityScorer;

    let violations = vec![Violation::new(
        "4.1.2",
        "Name, Role, Value",
        WcagLevel::A,
        Severity::Critical,
        "Button has no accessible name",
        "btn1",
    )];
    let score = AccessibilityScorer::calculate_score(&violations);
    assert!(
        score <= 49.0,
        "accessibility_score must be ≤ 49 when critical violations exist, got {}",
        score
    );
}

#[test]
fn severity_counts_low_nonzero_with_low_finding() {
    let mut results = WcagResults::new();
    results.add_violation(Violation::new(
        "2.4.8",
        "Location",
        WcagLevel::AAA,
        Severity::Low,
        "No location breadcrumb",
        "n1",
    ));

    let report = make_report(results);
    let normalized = normalize(&report);

    assert!(
        normalized.normalized.severity_counts.low > 0,
        "severity_counts.low must be > 0 when a Low-severity rule fires, got {}",
        normalized.normalized.severity_counts.low
    );
}

#[test]
fn severity_counts_low_not_upgraded_by_taxonomy_floor() {
    // Rule 1.3.1 has taxonomy.severity = High, but rules may deliberately
    // generate Severity::Low for minor cases (empty list). Before #288 the
    // taxonomy floor max(Low, High) = High silently upgraded these to High,
    // making severity_counts.low always 0 in practice.
    let mut results = WcagResults::new();
    results.add_violation(Violation::new(
        "1.3.1",
        "Info and Relationships",
        WcagLevel::A,
        Severity::Low,
        "List element has no list items",
        "n1",
    ));

    let report = make_report(results);
    let normalized = normalize(&report);

    assert_eq!(
        normalized.normalized.severity_counts.low, 1,
        "Low violation of a Medium/High taxonomy rule must not be upgraded (#288)"
    );
    assert_eq!(
        normalized.normalized.severity_counts.high, 0,
        "taxonomy floor must not silently upgrade Low to High (#288)"
    );
}

// ─── Security score invariants ────────────────────────────────────────────────

#[test]
fn security_score_below_100_without_permissions_policy() {
    use crate::security::SecurityHeaders;

    let headers = SecurityHeaders {
        content_security_policy: Some("default-src 'self'".to_string()),
        x_content_type_options: Some("nosniff".to_string()),
        x_frame_options: Some("DENY".to_string()),
        referrer_policy: Some("strict-origin".to_string()),
        strict_transport_security: Some("max-age=31536000".to_string()),
        cross_origin_opener_policy: Some("same-origin".to_string()),
        cross_origin_resource_policy: Some("same-origin".to_string()),
        permissions_policy: None,
        ..Default::default()
    };

    let mut report = make_report(WcagResults::new());
    report.security = Some(make_security_from_headers(headers));
    let normalized = normalize(&report);
    let security_entry = normalized
        .normalized
        .module_scores
        .iter()
        .find(|m| m.name == "Security")
        .unwrap();
    assert!(
        security_entry.score < 100,
        "security_score must be < 100 when Permissions-Policy is missing, got {}",
        security_entry.score
    );
}

#[test]
fn security_score_below_100_without_coop() {
    use crate::security::SecurityHeaders;

    let headers = SecurityHeaders {
        content_security_policy: Some("default-src 'self'".to_string()),
        x_content_type_options: Some("nosniff".to_string()),
        x_frame_options: Some("DENY".to_string()),
        referrer_policy: Some("strict-origin".to_string()),
        strict_transport_security: Some("max-age=31536000".to_string()),
        permissions_policy: Some("camera=()".to_string()),
        cross_origin_resource_policy: Some("same-origin".to_string()),
        cross_origin_opener_policy: None,
        ..Default::default()
    };

    let mut report = make_report(WcagResults::new());
    report.security = Some(make_security_from_headers(headers));
    let normalized = normalize(&report);
    let security_entry = normalized
        .normalized
        .module_scores
        .iter()
        .find(|m| m.name == "Security")
        .unwrap();
    assert!(
        security_entry.score < 100,
        "security_score must be < 100 when COOP is missing, got {}",
        security_entry.score
    );
}

#[test]
fn security_score_below_100_without_corp() {
    use crate::security::SecurityHeaders;

    let headers = SecurityHeaders {
        content_security_policy: Some("default-src 'self'".to_string()),
        x_content_type_options: Some("nosniff".to_string()),
        x_frame_options: Some("DENY".to_string()),
        referrer_policy: Some("strict-origin".to_string()),
        strict_transport_security: Some("max-age=31536000".to_string()),
        permissions_policy: Some("camera=()".to_string()),
        cross_origin_opener_policy: Some("same-origin".to_string()),
        cross_origin_resource_policy: None,
        ..Default::default()
    };

    let mut report = make_report(WcagResults::new());
    report.security = Some(make_security_from_headers(headers));
    let normalized = normalize(&report);
    let security_entry = normalized
        .normalized
        .module_scores
        .iter()
        .find(|m| m.name == "Security")
        .unwrap();
    assert!(
        security_entry.score < 100,
        "security_score must be < 100 when CORP is missing, got {}",
        security_entry.score
    );
}

// ─── Report consistency invariants ────────────────────────────────────────────

#[test]
fn summary_severity_counts_matches_accessibility_module() {
    let mut results = WcagResults::new();
    results.add_violation(Violation::new(
        "1.1.1",
        "Non-text Content",
        WcagLevel::A,
        Severity::High,
        "Missing alt",
        "n1",
    ));
    results.add_violation(Violation::new(
        "1.4.3",
        "Contrast",
        WcagLevel::AA,
        Severity::Medium,
        "Low contrast",
        "n2",
    ));

    let report = make_report(results);
    let normalized = normalize(&report);
    let unified = UnifiedReport::single(&normalized, &report);
    let json_str = unified.to_json(true).unwrap();
    let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();

    let summary_counts = &json["summary"]["severity_counts"];
    let module_counts = &json["pages"][0]["detail"]["modules"]["accessibility"]["severity_counts"];

    assert_eq!(
        summary_counts["high"], module_counts["high"],
        "summary.severity_counts.high must match modules.accessibility.severity_counts.high"
    );
    assert_eq!(
        summary_counts["medium"], module_counts["medium"],
        "summary.severity_counts.medium must match modules.accessibility.severity_counts.medium"
    );
    assert_eq!(
        summary_counts["total"], module_counts["total"],
        "summary.severity_counts.total must match modules.accessibility.severity_counts.total"
    );
}

#[test]
fn fix_guidance_is_always_present() {
    // Single report with findings: fix_guidance must be a non-null array
    let mut results = WcagResults::new();
    results.add_violation(Violation::new(
        "1.1.1",
        "Non-text Content",
        WcagLevel::A,
        Severity::High,
        "Missing alt",
        "n1",
    ));
    let report = make_report(results);
    let normalized = normalize(&report);
    let unified = UnifiedReport::single(&normalized, &report);
    let json_str = unified.to_json(false).unwrap();
    let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();

    let guidance = &json["pages"][0]["detail"]["fix_guidance"];
    assert!(
        guidance.is_array(),
        "fix_guidance must be an array, got: {}",
        guidance
    );
    assert!(
        !guidance.as_array().unwrap().is_empty(),
        "fix_guidance must not be empty when findings exist"
    );

    // Single report with NO findings: fix_guidance must still be a present empty array
    let report_clean = make_report(WcagResults::new());
    let normalized_clean = normalize(&report_clean);
    let unified_clean = UnifiedReport::single(&normalized_clean, &report_clean);
    let json_clean: serde_json::Value =
        serde_json::from_str(&unified_clean.to_json(false).unwrap()).unwrap();

    let guidance_clean = &json_clean["pages"][0]["detail"]["fix_guidance"];
    assert!(
        guidance_clean.is_array(),
        "fix_guidance must always be an array, even when empty"
    );
}