barrierlab-cli 0.1.0

Accessibility audit of a web page from its source, without a browser.
use std::io::{Read, Write};
use std::net::TcpListener;
use std::process::Command;

fn run(args: &[&str]) -> (i32, String) {
    let out = Command::new(env!("CARGO_BIN_EXE_barrierlab"))
        .args(args)
        .env("NO_COLOR", "1")
        .output()
        .expect("run barrierlab");
    (
        out.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&out.stdout).into_owned(),
    )
}

/// Serves `tests/fixtures/site.css` at `/site.css` and 404 for everything
/// else, on an ephemeral local port. Returns the base URL.
fn serve() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
    let port = listener.local_addr().unwrap().port();
    std::thread::spawn(move || {
        for stream in listener.incoming().flatten() {
            let mut stream = stream;
            let mut buf = [0u8; 2048];
            let n = stream.read(&mut buf).unwrap_or(0);
            let req = String::from_utf8_lossy(&buf[..n]);
            let (status, body) = if req.starts_with("GET /site.css ") {
                ("200 OK", include_str!("fixtures/site.css"))
            } else {
                ("404 Not Found", "not found")
            };
            let _ = write!(
                stream,
                "HTTP/1.1 {status}\r\ncontent-type: text/css\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
        }
    });
    format!("http://127.0.0.1:{port}/")
}

fn json(args: &[&str]) -> (i32, serde_json::Value) {
    let (code, out) = run(args);
    (code, serde_json::from_str(&out).expect("json"))
}

fn rule_outcomes(v: &serde_json::Value, rule: &str) -> Vec<String> {
    v["findings"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|f| f["rule_id"] == rule)
        .map(|f| f["outcome"].as_str().unwrap().to_string())
        .collect()
}

#[test]
fn reports_defects_and_exits_one() {
    let (code, text) = run(&["examples/page.html"]);
    assert_eq!(code, 1);
    assert!(text.contains("images/alt-missing"), "{text}");
    assert!(text.contains("links/name-missing"), "{text}");
    assert!(text.contains("contrast/text-insufficient"), "{text}");
}

#[test]
fn json_output_carries_the_report() {
    let (_, v) = json(&["--json", "examples/page.html"]);
    assert!(v["summary"]["fail"].as_u64().unwrap() >= 5);
}

#[test]
fn missing_file_exits_two() {
    let (code, _) = run(&["no/such/file.html"]);
    assert_eq!(code, 2);
}

#[test]
fn linked_sheet_is_fetched_through_base_url() {
    let base = serve();
    let (code, v) = json(&["--json", "--base-url", &base, "tests/fixtures/linked.html"]);
    assert_eq!(code, 1);
    assert!(
        rule_outcomes(&v, "contrast/text-insufficient").contains(&"fail".to_string()),
        "{v}"
    );
    assert!(v["inputs"].as_array().is_none_or(|i| i.is_empty()), "{v}");
}

#[test]
fn local_file_without_base_url_notes_the_missing_sheet() {
    let (code, v) = json(&["--json", "tests/fixtures/linked.html"]);
    let notes = v["inputs"].as_array().expect("inputs");
    assert_eq!(notes.len(), 1, "{v}");
    assert_eq!(notes[0]["kind"], "stylesheet_unavailable");
    assert_eq!(notes[0]["subject"], "site.css");
    assert!(notes[0]["detail"].as_str().unwrap().contains("--base-url"));
    // Contrast is untested, not passed and not failed.
    assert!(!rule_outcomes(&v, "contrast/text-insufficient").contains(&"fail".to_string()));
    assert!(!rule_outcomes(&v, "contrast/text-insufficient").contains(&"pass".to_string()));
    assert_eq!(code, 0, "{v}");
}

#[test]
fn unreachable_sheet_is_a_note_with_the_reason() {
    let base = serve();
    let (code, v) = json(&["--json", "--base-url", &base, "tests/fixtures/missing.html"]);
    let notes = v["inputs"].as_array().expect("inputs");
    assert_eq!(notes.len(), 1, "{v}");
    assert_eq!(notes[0]["subject"], "missing.css");
    assert!(notes[0]["detail"].as_str().unwrap().contains("404"), "{v}");
    assert!(!rule_outcomes(&v, "contrast/text-insufficient").contains(&"fail".to_string()));
    assert_eq!(code, 0);
}

#[test]
fn fail_on_review_turns_review_findings_into_exit_one() {
    let page = "tests/fixtures/missing.html";
    let (_, v) = json(&["--json", page]);
    assert!(v["summary"]["review"].as_u64().unwrap() > 0, "{v}");
    assert_eq!(run(&[page]).0, 0);
    assert_eq!(run(&["--fail-on", "review", page]).0, 1);
}

#[test]
fn bad_flag_values_exit_two() {
    for args in [
        &["--fail-on", "never", "examples/page.html"][..],
        &["--width", "wide", "examples/page.html"],
        &["--base-url", "ftp://x/", "examples/page.html"],
        &["--width"],
    ] {
        assert_eq!(run(args).0, 2, "{args:?}");
    }
}

#[test]
fn dark_and_width_reach_the_environment() {
    // --dark and a narrow --width each switch on a media block with poor contrast.
    let dir = std::env::temp_dir().join(format!("barrierlab-env-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let page = dir.join("env.html");
    std::fs::write(
        &page,
        r#"<!doctype html><html lang="en"><head><title>t</title><style>
        p { color: #000; background: #fff; }
        @media (prefers-color-scheme: dark) { p { color: #777; background: #888; } }
        @media (max-width: 600px) { p { color: #aaa; background: #fff; } }
        </style></head><body><main><h1>t</h1><p>Some text here.</p></main></body></html>"#,
    )
    .unwrap();
    let page = page.to_str().unwrap();
    let light = json(&["--json", page]).1;
    let dark = json(&["--json", "--dark", page]).1;
    let narrow = json(&["--json", "--width", "500", page]).1;
    std::fs::remove_dir_all(&dir).ok();
    let rule = "contrast/text-insufficient";
    assert!(
        !rule_outcomes(&light, rule).contains(&"fail".to_string()),
        "{light}"
    );
    assert!(
        rule_outcomes(&dark, rule).contains(&"fail".to_string()),
        "{dark}"
    );
    assert!(
        rule_outcomes(&narrow, rule).contains(&"fail".to_string()),
        "{narrow}"
    );
}

#[test]
fn version_prints_without_fetching() {
    let (code, out) = run(&["--version"]);
    assert_eq!(code, 0);
    assert_eq!(
        out.trim(),
        format!("barrierlab {}", env!("CARGO_PKG_VERSION"))
    );
}

#[test]
fn json_findings_carry_a_stable_id() {
    let (_, a) = json(&["--json", "examples/page.html"]);
    let (_, b) = json(&["--json", "examples/page.html"]);
    let findings = a["findings"].as_array().unwrap();
    assert!(!findings.is_empty());
    for f in findings {
        let id = f["id"].as_str().expect("id");
        assert!(id.starts_with("F-") && id.len() == 10, "{id}");
        assert_eq!(f.as_object().unwrap().keys().next().unwrap(), "id");
    }
    // Same input, same ids.
    let ids = |v: &serde_json::Value| -> Vec<String> {
        v["findings"]
            .as_array()
            .unwrap()
            .iter()
            .map(|f| f["id"].as_str().unwrap().to_owned())
            .collect()
    };
    assert_eq!(ids(&a), ids(&b));
}

#[test]
fn score_and_coverage_are_separate_fields() {
    let (_, v) = json(&["--json", "--score", "wcag-strict", "examples/page.html"]);
    let s = &v["score"];
    assert_eq!(s["profile"], "wcag_strict");
    assert!(s["score"].as_f64().unwrap() < 100.0);
    assert!(s["coverage"].as_f64().unwrap() > 0.0);
    assert!(!s["breakdown"].as_array().unwrap().is_empty());
    assert!(v.get("gate").is_none());

    let (_, text) = run(&["--score", "balanced", "examples/page.html"]);
    assert!(
        text.contains("Score:") && text.contains("Coverage:"),
        "{text}"
    );
}

#[test]
fn gate_policy_decides_the_exit_code() {
    let dir = scratch("gate");
    let strict = dir.join("policy.json");
    std::fs::write(&strict, r#"{"min_score":99.9}"#).unwrap();
    let (code, v) = json(&[
        "--json",
        "--gate-policy",
        strict.to_str().unwrap(),
        "examples/page.html",
    ]);
    assert_eq!(v["gate"]["decision"], "fail");
    assert_eq!(v["gate"]["reasons"][0]["check"], "score");
    assert_eq!(code, 1);

    // `--gate` alone: balanced profile and the default policy.
    let (_, v) = json(&["--json", "--gate", "examples/page.html"]);
    assert_eq!(v["score"]["profile"], "balanced");
    assert!(v["gate"]["decision"].is_string());
}

#[test]
fn unknown_score_profile_is_a_usage_error() {
    let (code, _) = run(&["--score", "lenient", "examples/page.html"]);
    assert_eq!(code, 2);
}

fn scratch(name: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("barrierlab-test-{name}-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

fn white_png(dir: &std::path::Path, name: &str, speck: bool) -> String {
    let (w, h) = (400u32, 300u32);
    let mut data = vec![255u8; (w * h * 4) as usize];
    if speck {
        for y in 100..140 {
            for x in 100..140 {
                let i = ((y * w + x) * 4) as usize;
                data[i..i + 3].copy_from_slice(&[0, 0, 0]);
            }
        }
    }
    let img = pixel_diff::RgbaImage::new(w, h, data).unwrap();
    let path = dir.join(name);
    std::fs::write(
        &path,
        pixel_diff::png_codec::encode_png(img.as_view()).unwrap(),
    )
    .unwrap();
    path.to_str().unwrap().to_string()
}

#[test]
fn visual_reports_geometry_findings_baseline_and_evidence() {
    let dir = scratch("visual");
    let shot = white_png(&dir, "shot.png", true);
    let base = white_png(&dir, "base.png", false);
    let boxes = dir.join("boxes.json");
    std::fs::write(
        &boxes,
        r#"{"viewport":{"x":0,"y":0,"width":400,"height":300},"device_pixel_ratio":1,"boxes":[
            {"node_id":"a","rect":{"x":10,"y":10,"width":120,"height":30},"is_text":true,
             "text_color":{"r":0,"g":0,"b":0,"a":255}},
            {"node_id":"b","rect":{"x":20,"y":20,"width":120,"height":30},"is_text":true}]}"#,
    )
    .unwrap();
    let ev = dir.join("ev");
    let (code, v) = json(&[
        "visual",
        &shot,
        boxes.to_str().unwrap(),
        "--baseline",
        &base,
        "--evidence-dir",
        ev.to_str().unwrap(),
        "--score",
        "visual-focus",
        "--fail-on",
        "review",
        "--json",
    ]);
    assert_eq!(code, 1);
    assert_eq!(rule_outcomes(&v, "visual/text-overlap"), ["review"]);
    assert_eq!(rule_outcomes(&v, "visual/regression"), ["review"]);
    assert_eq!(v["score"]["profile"], "visual_focus");
    assert!(v["score"]["coverage"].as_f64().unwrap() > 0.0);
    assert!(ev.join("overlay.png").is_file() && ev.join("crop-1.png").is_file());
    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(ev.join("manifest.json")).unwrap()).unwrap();
    assert_eq!(manifest["items"].as_array().unwrap().len(), 1);
    assert_eq!(manifest["viewport"], serde_json::json!([400, 300]));

    // Without a baseline nothing was compared: not run, never a pass.
    let (_, v) = json(&["visual", &shot, boxes.to_str().unwrap(), "--json"]);
    let run = v["rule_runs"]
        .as_array()
        .unwrap()
        .iter()
        .find(|r| r["rule_id"] == "visual/regression")
        .unwrap();
    assert!(run["not_run"].is_string() || run["not_run"].is_object());
}