From 97d1335caf05952ef8cc336f905f42541488d660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:10:27 -0800 Subject: [PATCH 1/5] craft-testkit: skip or fail a test that lacks a program, a corpus or the craft-fonts faces Add the skip module to craft-testkit, for the Craft apps and the craft-libs crates to take as a dev-dependency. - skip(reason, required_var) prints one "SKIPPED: " line to stderr and returns false, or fails the test when the variable is exactly 1. Unset, empty, 0, true, " 1" and "1\n" all skip. - or_skip!(probe, var) binds the Ok value of a Result or skips and returns; or_skip!(probe, var, value) returns the given value, for a test that returns a Result. - craft_fonts(present, required) takes both values from the caller's build; craft_fonts_cover(text, faces) checks that one face maps every character of the text that is not whitespace. A carriage return or line feed in a reason is printed as \r or \n, so one skip is one line. The module is native only and does not change the process environment; its tests that read a variable run the test binary again as a child process. --- Cargo.lock | 3 + README.md | 4 +- crates/testkit/Cargo.toml | 5 +- crates/testkit/README.md | 59 ++++++ crates/testkit/src/lib.rs | 6 + crates/testkit/src/skip.rs | 379 +++++++++++++++++++++++++++++++++++++ 6 files changed, 454 insertions(+), 2 deletions(-) create mode 100644 crates/testkit/src/skip.rs diff --git a/Cargo.lock b/Cargo.lock index c8aee49f29..182a0deb6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2573,6 +2573,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "skrifa 0.47.0", +] [[package]] name = "craft-text" diff --git a/README.md b/README.md index adbb6c120e..6b015e678c 100644 --- a/README.md +++ b/README.md @@ -347,7 +347,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit `color` and `write`; re-exports them for existing users. - [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals - out of range, and `std::time::Instant` in code the web build runs. Not published. + out of range, and `std::time::Instant` in code the web build runs. Its `skip` module prints a + `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the test when + the variable the caller names is exactly `1`. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..de033a3259 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -5,10 +5,13 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Source-level platform regression guards and verification utilities for the Craft application suite" +description = "Source-level platform regression guards, skip-or-fail helpers and verification utilities for the Craft application suite" publish = false [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +skrifa = { version = "0.47", default-features = false, features = ["std"] } + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..1e4cfc02f8 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -27,6 +27,54 @@ Source-level guards provide deterministic syntactic evidence about codebase stru Source guards serve as fast, zero-dependency regression gates in application test suites, complementing platform integration tests and CI workflows. +## skip + +The `skip` module is not built for `wasm32`. A test that needs something a test environment may lack +(a program, a corpus file, the craft-fonts faces) skips or fails under one rule: + +- When the variable the caller names is exactly `1`, the absence fails the test. No skip line is + printed. +- Otherwise, including when the variable is unset, empty, `0`, `true`, ` 1` or `1` followed by a + line feed, the helper prints `SKIPPED: ` and one line feed to stderr, and the test + returns and passes. Carriage returns and line feeds in the reason are printed as `\r` and `\n`. + +The caller passes the name its repository uses today, such as `CRAFT_MEDIA_REQUIRE_ORACLES`, +`CRAFT_PDF_ORACLES_REQUIRED`, `PDFCRAFT_ORACLES_REQUIRED` or `FILMCRAFT_REQUIRE_ORACLES`. +`skip::REQUIRED_VAR` (`CRAFT_TEST_REQUIRED`) is the default name. + +```rust +use craft_testkit::skip::{REQUIRED_VAR, craft_fonts, skip}; + +#[test] +fn renders_with_qpdf() { + let qpdf = craft_testkit::or_skip!(find_qpdf(), REQUIRED_VAR); + // ... +} + +#[test] +fn draws_japanese() { + if !craft_fonts(HAS_CRAFT_FONTS, CRAFT_FONTS_REQUIRED) { + return; + } + // ... +} +``` + +`or_skip!` evaluates a `Result` once, binds the `Ok` value, and on `Err` skips with the error's +`Display` text as the reason. The two-argument form returns `()`; a test that returns a `Result` +passes the value to return as the third argument, for example `Ok(())`. + +`craft_fonts(present, required)` takes both values from the caller's build: a build constant, an +`option_env!` value, or the table `craft-fonts-build` generates. A required failure names +`CRAFT_FONTS_REQUIRED=1`. + +`craft_fonts_cover(text, faces)` returns `true` when one face maps every character of `text` that +is not whitespace. Each face is font data with its index in a collection (`0` for a single font). A +face that does not parse covers nothing, and coverage is not combined across faces. + +The module does not change the process environment. Its tests that read a real variable run the +test binary again as a child process with that variable set. + ## Consumer Adoption Examples ### 1. PhotoCraft: Adopt `wgsl_float_literals` and `predefined_quit` @@ -83,6 +131,11 @@ fn no_std_instant_in_code_the_web_build_runs() { | Module | Source | Path | Commit | |---|---|---|---| | `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | +| `skip` | storytold/lightcraft | `crates/testkit/src/lib.rs` (`skip!`, `record`) | `7ebbb17a82` | +| `skip` | storytold/pdfcraft | `crates/oracle/src/lib.rs` (`or_skip!`, `REQUIRED_VAR`) | `ee9bf28126` | +| `skip` | storytold/filmcraft | `crates/testkit/src/lib.rs` (`require_*!`), `crates/testkit/src/oracle.rs` (`skip`) | `cff7e1442e` | +| `skip` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` (`skip`, `skip_with`) | `75a654f4f8` | +| `skip` | storytold/gridcraft | `crates/ui-egui/src/theme.rs` (`craft_fonts_cover`) | `06c2b1440b` | ## Migration @@ -90,3 +143,9 @@ fn no_std_instant_in_code_the_web_build_runs() { |---|---|---|---| | PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | | FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | +| LightCraft | `skip` | `lightcraft-testkit`'s `skip!`, which keeps its JSON skip log on top of `skip` | Not started | +| PdfCraft | `skip` | `pdfcraft-oracle`'s `or_skip!`, which reads any value of `PDFCRAFT_ORACLES_REQUIRED` | Not started | +| FilmCraft | `skip` | `filmcraft-testkit`'s `require_*!` and `skip`, which accept `1`, `true`, `yes` and `on` | Not started | +| GridCraft | `skip` | `craft_fonts_cover`, which reads GridCraft's embedded face table | Not started | +| craft-libs `craft-media-testkit` | `skip` | `skip` and `skip_with`, which accept `1`, `true`, `yes` and `on` | Not started | +| craft-libs `pdf` tests | `skip` | `or_skip!` in `crates/pdf/tests/cos/oracle.rs`, which reads any value of `CRAFT_PDF_ORACLES_REQUIRED` | Not started | diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..4f989f2694 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,10 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! [`skip`] decides what a test does when something it needs is missing (a program, a corpus, +//! the craft-fonts faces): it prints one `SKIPPED:` line and returns, or fails the test when the +//! variable the caller names is exactly `1`. It is not built for `wasm32`. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -26,6 +30,8 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(not(target_arch = "wasm32"))] +pub mod skip; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/src/skip.rs b/crates/testkit/src/skip.rs new file mode 100644 index 0000000000..183db3b97d --- /dev/null +++ b/crates/testkit/src/skip.rs @@ -0,0 +1,379 @@ +//! Skip-or-fail for a test that needs something a test environment may lack: a program, a corpus +//! file, the craft-fonts faces. +//! +//! An optional absence prints one line to stderr, `SKIPPED: `, and the test returns and +//! passes. When the variable the caller names is exactly `1`, the absence fails the test instead +//! and no skip line is printed. Unset, empty, `0`, `true`, ` 1` and `1\n` all leave the test +//! optional. The caller passes the name its repository uses, such as `CRAFT_MEDIA_REQUIRE_ORACLES` +//! or `CRAFT_PDF_ORACLES_REQUIRED`; [`REQUIRED_VAR`] is the default name. +//! +//! ```no_run +//! use craft_testkit::skip::{REQUIRED_VAR, skip}; +//! +//! fn find_qpdf() -> Result { +//! Err("qpdf is not on PATH".into()) +//! } +//! +//! // A test returning `()`: bind the program or return. +//! let qpdf = craft_testkit::or_skip!(find_qpdf(), REQUIRED_VAR); +//! # let _ = qpdf; +//! +//! // The same rule without a `Result` to match on. +//! let gpu_available = false; +//! if !gpu_available && !skip("no GPU adapter", REQUIRED_VAR) { +//! return; +//! } +//! ``` +//! +//! A reason that holds a carriage return or a line feed is printed with them written as `\r` and +//! `\n`, so one skip is one line. Each line is written with one call while stderr is locked, so +//! lines from tests running in parallel do not mix; their order is not fixed. + +use std::ffi::OsStr; + +/// The default name of the variable that makes a skip fail the test. +pub const REQUIRED_VAR: &str = "CRAFT_TEST_REQUIRED"; + +/// The variable `craft-fonts-build` reads, named by [`craft_fonts`] when it fails a test. +pub const FONTS_REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED"; + +/// Whether the variable `var` is set to exactly `1`. Any other value, a value that is not valid +/// Unicode, and an unset variable return `false`. +pub fn required(var: &str) -> bool { + is_required_value(std::env::var_os(var).as_deref()) +} + +fn is_required_value(value: Option<&OsStr>) -> bool { + value == Some(OsStr::new("1")) +} + +/// Skip the calling test: print `SKIPPED: ` and return `false`, or fail the test when +/// `required_var` is exactly `1`. The caller returns from the test itself: +/// `if !skip(reason, var) { return; }`. +pub fn skip(reason: &str, required_var: &str) -> bool { + skip_with(required(required_var), reason, required_var) +} + +/// Fail the test when `required` is set, otherwise print the skip line and return `false`. It +/// fails the test with a panic. +#[allow(clippy::panic)] +fn skip_with(required: bool, reason: &str, required_var: &str) -> bool { + if required { + panic!("{reason}, and {required_var}=1 forbids skipping this test"); + } + eprint!("{}", skip_line(reason)); + false +} + +/// The skip line for `reason`, with its carriage returns and line feeds escaped, ending in one +/// line feed. +fn skip_line(reason: &str) -> String { + let mut line = String::with_capacity("SKIPPED: \n".len() + reason.len()); + line.push_str("SKIPPED: "); + for c in reason.chars() { + match c { + '\r' => line.push_str("\\r"), + '\n' => line.push_str("\\n"), + c => line.push(c), + } + } + line.push('\n'); + line +} + +/// Whether a test that needs the craft-fonts faces can run. Returns `true` when `present` is set. +/// Without the faces it prints a skip line and returns `false`, or fails the test when `required` +/// is set. The caller passes both values from its build: a build constant, an `option_env!` +/// value, or the table `craft-fonts-build` generates. +pub fn craft_fonts(present: bool, required: bool) -> bool { + present || skip_with(required, "craft-fonts faces unavailable (build with CRAFT_FONTS_DIR)", FONTS_REQUIRED_VAR) +} + +/// Whether one of `faces` maps every character of `text` that is not whitespace. Each face is +/// font data and the index of the face in a collection (`0` for a single font). A face that does +/// not parse covers nothing, and the characters must all come from the same face. Each combining +/// mark is a character of its own. Text that is empty or only whitespace is covered when at least +/// one face parses. +pub fn craft_fonts_cover(text: &str, faces: &[(&[u8], u32)]) -> bool { + use skrifa::MetadataProvider as _; + faces.iter().any(|&(data, index)| { + let Ok(font) = skrifa::FontRef::from_index(data, index) else { + return false; + }; + let map = font.charmap(); + text.chars().filter(|c| !c.is_whitespace()).all(|c| map.map(c).is_some()) + }) +} + +/// Binds the `Ok` value of a `Result` probe, or skips the calling test under the rule of +/// [`skip`](crate::skip::skip) and returns from it. The probe is evaluated once, and its error is +/// the skip reason, so the error type implements `Display`. +/// +/// `or_skip!(probe, var)` returns `()` and belongs in a test returning `()`. +/// `or_skip!(probe, var, value)` returns `value`, for example `Ok(())` in a test that returns a +/// `Result`. +#[macro_export] +macro_rules! or_skip { + ($probe:expr, $required_var:expr) => { + $crate::or_skip!($probe, $required_var, ()) + }; + ($probe:expr, $required_var:expr, $ret:expr) => { + match $probe { + ::core::result::Result::Ok(value) => value, + ::core::result::Result::Err(absent) => { + let _ = $crate::skip::skip(&::std::string::ToString::to_string(&absent), $required_var); + return $ret; + } + } + }; +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + use std::process::{Command, Output}; + + /// The case the child process runs; unset in an ordinary test run. + const CHILD_CASE: &str = "CRAFT_TESTKIT_SKIP_CHILD"; + /// A variable no test sets, for skips that must stay optional. + const NEVER_SET: &str = "CRAFT_TESTKIT_SKIP_NEVER_SET"; + + /// Runs `child` below in a new process of this test binary, with `REQUIRED_VAR` set to + /// `required` or removed, so no test changes this process's environment. + fn run_child(case: &str, required: Option<&str>) -> Output { + let exe = std::env::current_exe().expect("the test binary's path"); + let mut cmd = Command::new(exe); + cmd.args(["skip::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); + match required { + Some(value) => cmd.env(REQUIRED_VAR, value), + None => cmd.env_remove(REQUIRED_VAR), + }; + cmd.output().expect("run the test binary") + } + + fn stderr(out: &Output) -> String { + String::from_utf8_lossy(&out.stderr).into_owned() + } + + #[test] + fn child() { + let Some(case) = std::env::var_os(CHILD_CASE) else { + return; + }; + match case.to_str() { + Some("skip") => { + assert!(!skip("probe absent", REQUIRED_VAR)); + eprintln!("returned from skip"); + } + Some("or_skip") => { + let value: u32 = crate::or_skip!(Err::("probe absent"), REQUIRED_VAR); + eprintln!("ran on with {value}"); + } + Some("threads") => std::thread::scope(|s| { + for i in 0..8 { + s.spawn(move || skip(&format!("thread {i}\r\nsecond half"), REQUIRED_VAR)); + } + }), + other => panic!("unknown child case {other:?}"), + } + } + + /// Unset, empty, `0`, `true`, a leading space and a trailing line feed are optional; only + /// exactly `1` is required. + #[test] + fn only_exactly_1_is_required() { + assert!(!is_required_value(None)); + for value in ["", "0", "true", "TRUE", "yes", "on", " 1", "1 ", "1\n", "01", "11"] { + assert!(!is_required_value(Some(OsStr::new(value))), "{value:?}"); + } + assert!(is_required_value(Some(OsStr::new("1")))); + } + + #[cfg(unix)] + #[test] + fn a_value_that_is_not_unicode_is_optional() { + use std::os::unix::ffi::OsStrExt as _; + assert!(!is_required_value(Some(OsStr::from_bytes(b"1\xff")))); + assert!(!is_required_value(Some(OsStr::from_bytes(b"\xff")))); + } + + /// Absence is never silent, and which of the two loud forms it takes is decided by the + /// variable: exactly `1` fails the test, and `0` (fatal under the any-value rule) skips. + #[test] + fn a_missing_oracle_is_fatal_exactly_when_it_is_required() { + let var = "CRAFT_PDF_ORACLES_REQUIRED"; + assert!(!skip_with(is_required_value(Some(OsStr::new("0"))), "qpdf is not on PATH", var)); + assert!(!skip_with(is_required_value(Some(OsStr::new(""))), "qpdf is not on PATH", var)); + + let failed = std::panic::catch_unwind(|| skip_with(is_required_value(Some(OsStr::new("1"))), "qpdf is not on PATH", var)); + let message = failed.expect_err("a required absence fails the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.contains("qpdf is not on PATH"), "{message}"); + assert!(message.contains("CRAFT_PDF_ORACLES_REQUIRED=1"), "{message}"); + } + + #[test] + fn a_skip_line_is_one_line_with_its_reason_escaped() { + assert_eq!(skip_line("qpdf is not on PATH"), "SKIPPED: qpdf is not on PATH\n"); + let line = skip_line("first\r\nsecond\nthird\r"); + assert_eq!(line, "SKIPPED: first\\r\\nsecond\\nthird\\r\n"); + assert_eq!(line.lines().count(), 1); + assert_eq!(skip_line(""), "SKIPPED: \n"); + } + + /// The variable is read from the environment, and only exactly `1` fails the test. + #[test] + fn skip_reads_its_variable_from_the_environment() { + for value in [None, Some(""), Some("0"), Some("true"), Some(" 1")] { + let out = run_child("skip", value); + let err = stderr(&out); + assert!(out.status.success(), "{value:?}: {err}"); + assert_eq!(err.matches("SKIPPED: probe absent\n").count(), 1, "{value:?}: {err}"); + assert!(err.contains("returned from skip"), "{value:?}: {err}"); + } + let out = run_child("skip", Some("1")); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("probe absent, and CRAFT_TEST_REQUIRED=1 forbids skipping this test"), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("returned from skip"), "{err}"); + } + + #[test] + fn or_skip_returns_from_the_test_when_optional_and_fails_when_required() { + let out = run_child("or_skip", None); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: probe absent\n"), "{err}"); + assert!(!err.contains("ran on"), "{err}"); + + let out = run_child("or_skip", Some("1")); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_TEST_REQUIRED=1"), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("ran on"), "{err}"); + } + + #[test] + fn skip_lines_from_parallel_threads_stay_whole() { + let out = run_child("threads", None); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + let mut lines: Vec<&str> = err.lines().filter(|l| l.contains("SKIPPED") || l.contains("second half")).collect(); + lines.sort_unstable(); + let expected: Vec = (0..8).map(|i| format!("SKIPPED: thread {i}\\r\\nsecond half")).collect(); + assert_eq!(lines, expected, "{err}"); + } + + #[test] + fn or_skip_yields_the_value_and_evaluates_the_probe_once() { + let probes = Cell::new(0); + let probe = || { + probes.set(probes.get() + 1); + Ok::(7) + }; + let value = crate::or_skip!(probe(), NEVER_SET); + assert_eq!(value, 7); + assert_eq!(probes.get(), 1); + } + + #[test] + fn or_skip_returns_the_given_value_from_a_result_test() { + fn run(probes: &Cell) -> Result { + let value: u32 = crate::or_skip!( + { + probes.set(probes.get() + 1); + Err::("probe absent".into()) + }, + NEVER_SET, + Ok(0) + ); + Ok(value + 1) + } + let probes = Cell::new(0); + assert_eq!(run(&probes), Ok(0)); + assert_eq!(probes.get(), 1); + } + + #[test] + fn craft_fonts_runs_skips_or_fails() { + assert!(craft_fonts(true, false)); + assert!(craft_fonts(true, true)); + assert!(!craft_fonts(false, false)); + let failed = std::panic::catch_unwind(|| craft_fonts(false, true)); + let message = failed.expect_err("missing required faces fail the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.contains("CRAFT_FONTS_REQUIRED=1"), "{message}"); + } + + /// A font holding only a format 12 `cmap` table that maps each range of code points. + fn face(ranges: &[(u32, u32)]) -> Vec { + let subtable_len = 16 + 12 * ranges.len() as u32; + let mut data = Vec::new(); + data.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + for v in [1u16, 16, 0, 0] { + data.extend_from_slice(&v.to_be_bytes()); + } + data.extend_from_slice(b"cmap"); + for v in [0u32, 28, 12 + subtable_len] { + data.extend_from_slice(&v.to_be_bytes()); + } + for v in [0u16, 1, 3, 10] { + data.extend_from_slice(&v.to_be_bytes()); + } + data.extend_from_slice(&12u32.to_be_bytes()); + data.extend_from_slice(&12u16.to_be_bytes()); + data.extend_from_slice(&0u16.to_be_bytes()); + for v in [subtable_len, 0, ranges.len() as u32] { + data.extend_from_slice(&v.to_be_bytes()); + } + let mut glyph = 1u32; + for &(start, end) in ranges { + for v in [start, end, glyph] { + data.extend_from_slice(&v.to_be_bytes()); + } + glyph += end - start + 1; + } + data + } + + #[test] + fn craft_fonts_cover_the_advertised_scripts() { + let latin_greek_cyrillic = face(&[(0x41, 0x5A), (0x61, 0x7A), (0x391, 0x3C9), (0x410, 0x44F)]); + let faces: &[(&[u8], u32)] = &[(&latin_greek_cyrillic, 0)]; + for sample in ["Craft", "Αλφα", "Привет", "Craft Αλφα Привет"] { + assert!(craft_fonts_cover(sample, faces), "{sample}"); + } + assert!(!craft_fonts_cover("日本", faces)); + assert!(!craft_fonts_cover("Craft!", faces)); + } + + #[test] + fn coverage_needs_one_face_that_parses_and_maps_every_character() { + let a = face(&[(u32::from('A'), u32::from('A'))]); + let b = face(&[(u32::from('B'), u32::from('B'))]); + let e = face(&[(u32::from('e'), u32::from('e'))]); + let e_acute = face(&[(u32::from('e'), u32::from('e')), (0x301, 0x301)]); + let garbage: &[u8] = b"not a font"; + + assert!(!craft_fonts_cover("", &[])); + assert!(!craft_fonts_cover("A", &[])); + assert!(!craft_fonts_cover("", &[(garbage, 0)])); + assert!(!craft_fonts_cover("A", &[(garbage, 0)])); + assert!(!craft_fonts_cover("A", &[(&a, 1)]), "a single font has no face 1"); + + assert!(craft_fonts_cover("", &[(&a, 0)])); + assert!(craft_fonts_cover(" \t\n\u{3000}", &[(&a, 0)])); + assert!(craft_fonts_cover(" A A ", &[(&a, 0)])); + assert!(craft_fonts_cover("A", &[(garbage, 0), (&a, 0)])); + + assert!(craft_fonts_cover("A", &[(&a, 0), (&b, 0)])); + assert!(craft_fonts_cover("B", &[(&a, 0), (&b, 0)])); + assert!(!craft_fonts_cover("AB", &[(&a, 0), (&b, 0)]), "each face covers only part of the text"); + + assert!(!craft_fonts_cover("e\u{301}", &[(&e, 0)]), "the combining mark is not mapped"); + assert!(craft_fonts_cover("e\u{301}", &[(&e_acute, 0)])); + } +} From 843018f742e8c09c27e55e3c425717a0646b8c1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:17:10 -0800 Subject: [PATCH 2/5] craft-testkit: fail a skip on a required variable that is not empty, 0 or 1 skip and or_skip! now read the required variable as follows: unset, empty and 0 skip the test, 1 fails it, and any other value, including true, yes, " 1", "1\n" and a value that is not valid Unicode, fails the test as a configuration error that names the variable and its value. skip::required returns Result with the same rule. The README's skip section lists the values in a table, and the migration notes say which values change for apps that read any value or accept true, yes and on today. --- README.md | 3 +- crates/testkit/README.md | 21 +++-- crates/testkit/src/lib.rs | 3 +- crates/testkit/src/skip.rs | 163 ++++++++++++++++++++++++++++++------- 4 files changed, 152 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index c51d119ff9..8606ce1f68 100644 --- a/README.md +++ b/README.md @@ -374,7 +374,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged copies of a valid input, and fails the test with the case that panicked or did not finish. Its `skip` module prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts - faces, or fails the test when the variable the caller names is exactly `1`. Not published. + faces, or fails the test when the variable the caller names is `1`. Any other value of that + variable except empty or `0` fails the test as a configuration error. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 235b74c09d..90020921ef 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -221,11 +221,17 @@ Changes from `craft-media-testkit`'s `hammer`: The `skip` module is not built for `wasm32`. A test that needs something a test environment may lack (a program, a corpus file, the craft-fonts faces) skips or fails under one rule: -- When the variable the caller names is exactly `1`, the absence fails the test. No skip line is - printed. -- Otherwise, including when the variable is unset, empty, `0`, `true`, ` 1` or `1` followed by a - line feed, the helper prints `SKIPPED: ` and one line feed to stderr, and the test - returns and passes. Carriage returns and line feeds in the reason are printed as `\r` and `\n`. +The variable is read only when something is missing. + +| Value | Result | +|---|---| +| Not set, empty or `0` | The helper prints `SKIPPED: ` and one line feed to stderr, and the test returns and passes. Carriage returns and line feeds in the reason are printed as `\r` and `\n`. | +| `1` | The test fails. No skip line is printed. | +| Any other value, such as `true`, `yes`, ` 1` or `1` followed by a line feed | The test fails with the reason and the variable's name and value. No skip line is printed. | +| Not Unicode | The test fails with the reason and the variable's name. No skip line is printed. | + +`skip::required(var)` returns the same decision without failing the test: `Ok(false)`, `Ok(true)`, +or a `RequiredError` that names the variable. The caller passes the name its repository uses today, such as `CRAFT_MEDIA_REQUIRE_ORACLES`, `CRAFT_PDF_ORACLES_REQUIRED`, `PDFCRAFT_ORACLES_REQUIRED` or `FILMCRAFT_REQUIRE_ORACLES`. @@ -345,3 +351,8 @@ cases change, and keep the test names. | GridCraft | `craft_fonts_cover`, which reads GridCraft's embedded face table | Not started | | craft-libs `craft-media-testkit` | `skip` and `skip_with`, which accept `1`, `true`, `yes` and `on` | Not started | | craft-libs `pdf` tests | `or_skip!` in `crates/pdf/tests/cos/oracle.rs`, which reads any value of `CRAFT_PDF_ORACLES_REQUIRED` | Not started | + +After an adoption, an app that reads any value as required skips on an empty value or `0`, and +fails as a configuration error on every other value except `1`. An app that accepts `true`, `yes` +and `on` fails on those values as a configuration error. +Each adoption says which values change and keeps the variable name. diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 1ecd5f531f..64e04021f3 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -27,7 +27,8 @@ //! //! [`skip`] decides what a test does when something it needs is missing (a program, a corpus, //! the craft-fonts faces): it prints one `SKIPPED:` line and returns, or fails the test when the -//! variable the caller names is exactly `1`. It is not built for `wasm32`. +//! variable the caller names is `1`. A value other than unset, empty, `0` or `1` fails the test as +//! a configuration error. It is not built for `wasm32`. //! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! diff --git a/crates/testkit/src/skip.rs b/crates/testkit/src/skip.rs index 183db3b97d..58530a3eca 100644 --- a/crates/testkit/src/skip.rs +++ b/crates/testkit/src/skip.rs @@ -2,10 +2,12 @@ //! file, the craft-fonts faces. //! //! An optional absence prints one line to stderr, `SKIPPED: `, and the test returns and -//! passes. When the variable the caller names is exactly `1`, the absence fails the test instead -//! and no skip line is printed. Unset, empty, `0`, `true`, ` 1` and `1\n` all leave the test -//! optional. The caller passes the name its repository uses, such as `CRAFT_MEDIA_REQUIRE_ORACLES` -//! or `CRAFT_PDF_ORACLES_REQUIRED`; [`REQUIRED_VAR`] is the default name. +//! passes. When the variable the caller names is `1`, the absence fails the test instead and no +//! skip line is printed. Unset, empty and `0` leave the test optional. Any other value, such as +//! `true`, ` 1`, `1\n` or a value that is not valid Unicode, is a configuration error: the absence +//! fails the test with the variable's name and value. The caller passes the name its repository +//! uses, such as `CRAFT_MEDIA_REQUIRE_ORACLES` or `CRAFT_PDF_ORACLES_REQUIRED`; [`REQUIRED_VAR`] is +//! the default name. //! //! ```no_run //! use craft_testkit::skip::{REQUIRED_VAR, skip}; @@ -30,6 +32,7 @@ //! lines from tests running in parallel do not mix; their order is not fixed. use std::ffi::OsStr; +use std::fmt; /// The default name of the variable that makes a skip fail the test. pub const REQUIRED_VAR: &str = "CRAFT_TEST_REQUIRED"; @@ -37,21 +40,60 @@ pub const REQUIRED_VAR: &str = "CRAFT_TEST_REQUIRED"; /// The variable `craft-fonts-build` reads, named by [`craft_fonts`] when it fails a test. pub const FONTS_REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED"; -/// Whether the variable `var` is set to exactly `1`. Any other value, a value that is not valid -/// Unicode, and an unset variable return `false`. -pub fn required(var: &str) -> bool { - is_required_value(std::env::var_os(var).as_deref()) +/// A value of the required variable that is not unset, empty, `0` or `1`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RequiredError { + /// The value is not valid Unicode. + NotUnicode { variable: String }, + /// The value is valid Unicode but not empty, `0` or `1`. + BadValue { variable: String, value: String }, } -fn is_required_value(value: Option<&OsStr>) -> bool { - value == Some(OsStr::new("1")) +impl fmt::Display for RequiredError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + const FIX: &str = "set it to 1 to fail a test that lacks a prerequisite, or leave it unset, empty or 0 to skip the test"; + match self { + Self::NotUnicode { variable } => write!(f, "{variable} is not valid Unicode; {FIX}"), + Self::BadValue { variable, value } => write!(f, "{variable}={value:?} is not empty, 0 or 1; {FIX}"), + } + } +} + +impl std::error::Error for RequiredError {} + +/// Whether the variable `var` makes a missing prerequisite fail the test. Unset, empty and `0` +/// return `Ok(false)`, and `1` returns `Ok(true)`. Any other value, including one that is not +/// valid Unicode, returns an error that names the variable. +pub fn required(var: &str) -> Result { + parse_required(var, std::env::var_os(var).as_deref()) +} + +fn parse_required(variable: &str, value: Option<&OsStr>) -> Result { + let Some(value) = value else { + return Ok(false); + }; + if value.is_empty() || value == OsStr::new("0") { + return Ok(false); + } + if value == OsStr::new("1") { + return Ok(true); + } + Err(match value.to_str() { + Some(text) => RequiredError::BadValue { variable: variable.to_owned(), value: text.to_owned() }, + None => RequiredError::NotUnicode { variable: variable.to_owned() }, + }) } /// Skip the calling test: print `SKIPPED: ` and return `false`, or fail the test when -/// `required_var` is exactly `1`. The caller returns from the test itself: +/// `required_var` is `1`. A value of `required_var` that [`required`] rejects fails the test with +/// the reason and the error. The caller returns from the test itself: /// `if !skip(reason, var) { return; }`. +#[allow(clippy::panic)] pub fn skip(reason: &str, required_var: &str) -> bool { - skip_with(required(required_var), reason, required_var) + match required(required_var) { + Ok(required) => skip_with(required, reason, required_var), + Err(error) => panic!("{reason}, and {error}"), + } } /// Fail the test when `required` is set, otherwise print the skip line and return `false`. It @@ -142,6 +184,11 @@ mod tests { /// Runs `child` below in a new process of this test binary, with `REQUIRED_VAR` set to /// `required` or removed, so no test changes this process's environment. fn run_child(case: &str, required: Option<&str>) -> Output { + run_child_os(case, required.map(OsStr::new)) + } + + /// [`run_child`] with a value that need not be valid Unicode. + fn run_child_os(case: &str, required: Option<&OsStr>) -> Output { let exe = std::env::current_exe().expect("the test binary's path"); let mut cmd = Command::new(exe); cmd.args(["skip::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); @@ -179,34 +226,59 @@ mod tests { } } - /// Unset, empty, `0`, `true`, a leading space and a trailing line feed are optional; only - /// exactly `1` is required. - #[test] - fn only_exactly_1_is_required() { - assert!(!is_required_value(None)); - for value in ["", "0", "true", "TRUE", "yes", "on", " 1", "1 ", "1\n", "01", "11"] { - assert!(!is_required_value(Some(OsStr::new(value))), "{value:?}"); + /// Values other than unset, empty, `0` and `1`. + const INVALID: [&str; 10] = ["true", "TRUE", "yes", "on", " 1", "1 ", "1\n", "01", "11", " "]; + + /// A value that is not valid Unicode: a lone surrogate on Windows, a byte that is not UTF-8 + /// elsewhere. + fn not_unicode() -> std::ffi::OsString { + #[cfg(windows)] + { + use std::os::windows::ffi::OsStringExt as _; + std::ffi::OsString::from_wide(&[u16::from(b'1'), 0xD800]) + } + #[cfg(not(windows))] + { + use std::os::unix::ffi::OsStringExt as _; + std::ffi::OsString::from_vec(b"1\xff".to_vec()) } - assert!(is_required_value(Some(OsStr::new("1")))); } - #[cfg(unix)] + /// Unset, empty and `0` are optional, `1` is required, and every other value is an error that + /// names the variable and the value. #[test] - fn a_value_that_is_not_unicode_is_optional() { - use std::os::unix::ffi::OsStrExt as _; - assert!(!is_required_value(Some(OsStr::from_bytes(b"1\xff")))); - assert!(!is_required_value(Some(OsStr::from_bytes(b"\xff")))); + fn only_unset_empty_0_and_1_are_valid() { + let var = "CRAFT_PDF_ORACLES_REQUIRED"; + assert_eq!(parse_required(var, None), Ok(false)); + assert_eq!(parse_required(var, Some(OsStr::new(""))), Ok(false)); + assert_eq!(parse_required(var, Some(OsStr::new("0"))), Ok(false)); + assert_eq!(parse_required(var, Some(OsStr::new("1"))), Ok(true)); + for value in INVALID { + let error = parse_required(var, Some(OsStr::new(value))); + assert_eq!(error, Err(RequiredError::BadValue { variable: var.into(), value: value.into() }), "{value:?}"); + } + let message = RequiredError::BadValue { variable: var.into(), value: "1\n".into() }.to_string(); + assert!(message.starts_with("CRAFT_PDF_ORACLES_REQUIRED=\"1\\n\" is not empty, 0 or 1; "), "{message}"); + assert_eq!(message.lines().count(), 1, "{message}"); + } + + #[test] + fn a_value_that_is_not_unicode_is_an_error() { + let value = not_unicode(); + assert_eq!(parse_required(REQUIRED_VAR, Some(&value)), Err(RequiredError::NotUnicode { variable: REQUIRED_VAR.into() })); + let message = RequiredError::NotUnicode { variable: REQUIRED_VAR.into() }.to_string(); + assert!(message.starts_with("CRAFT_TEST_REQUIRED is not valid Unicode; "), "{message}"); } /// Absence is never silent, and which of the two loud forms it takes is decided by the - /// variable: exactly `1` fails the test, and `0` (fatal under the any-value rule) skips. + /// variable: `1` fails the test, and `0` (fatal under the any-value rule) skips. #[test] fn a_missing_oracle_is_fatal_exactly_when_it_is_required() { let var = "CRAFT_PDF_ORACLES_REQUIRED"; - assert!(!skip_with(is_required_value(Some(OsStr::new("0"))), "qpdf is not on PATH", var)); - assert!(!skip_with(is_required_value(Some(OsStr::new(""))), "qpdf is not on PATH", var)); + assert!(!skip_with(parse_required(var, Some(OsStr::new("0"))) == Ok(true), "qpdf is not on PATH", var)); + assert!(!skip_with(parse_required(var, Some(OsStr::new(""))) == Ok(true), "qpdf is not on PATH", var)); - let failed = std::panic::catch_unwind(|| skip_with(is_required_value(Some(OsStr::new("1"))), "qpdf is not on PATH", var)); + let failed = std::panic::catch_unwind(|| skip_with(parse_required(var, Some(OsStr::new("1"))) == Ok(true), "qpdf is not on PATH", var)); let message = failed.expect_err("a required absence fails the test"); let message = message.downcast_ref::().expect("a formatted message"); assert!(message.contains("qpdf is not on PATH"), "{message}"); @@ -222,10 +294,11 @@ mod tests { assert_eq!(skip_line(""), "SKIPPED: \n"); } - /// The variable is read from the environment, and only exactly `1` fails the test. + /// The variable is read from the environment: unset, empty and `0` skip, and `1` fails the + /// test. #[test] fn skip_reads_its_variable_from_the_environment() { - for value in [None, Some(""), Some("0"), Some("true"), Some(" 1")] { + for value in [None, Some(""), Some("0")] { let out = run_child("skip", value); let err = stderr(&out); assert!(out.status.success(), "{value:?}: {err}"); @@ -240,6 +313,34 @@ mod tests { assert!(!err.contains("returned from skip"), "{err}"); } + /// Any other value fails the test with the reason, the variable and the value, and prints no + /// skip line. + #[test] + fn an_invalid_variable_fails_the_test() { + for value in ["true", "yes", " 1", "1\n"] { + let out = run_child("skip", Some(value)); + let err = stderr(&out); + assert!(!out.status.success(), "{value:?}: {err}"); + let expected = format!("probe absent, and CRAFT_TEST_REQUIRED={value:?} is not empty, 0 or 1; "); + assert!(err.contains(&expected), "{value:?}: {err}"); + assert!(!err.contains("SKIPPED:"), "{value:?}: {err}"); + assert!(!err.contains("returned from skip"), "{value:?}: {err}"); + } + + let out = run_child_os("skip", Some(¬_unicode())); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("probe absent, and CRAFT_TEST_REQUIRED is not valid Unicode; "), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + + let out = run_child("or_skip", Some("true")); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_TEST_REQUIRED=\"true\" is not empty, 0 or 1"), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("ran on"), "{err}"); + } + #[test] fn or_skip_returns_from_the_test_when_optional_and_fails_when_required() { let out = run_child("or_skip", None); From b6c5cf4fb326725f05b194503422faa22572384f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:42:15 -0800 Subject: [PATCH 3/5] craft-testkit: fail a skip on a required variable set to 0 When a prerequisite is missing, only an unset or empty variable now skips the test, and `1` fails it. `0` joins the other values that fail the test as a configuration error, in `skip::required`, `skip` and `or_skip!`. The error text no longer lists `0` as a skip value. The tests check `0` as an invalid value directly and through `skip` and `or_skip!` in a child process. The crate docs, its README and the root README's `craft-testkit` entry list the new values. --- README.md | 2 +- crates/testkit/README.md | 8 +++--- crates/testkit/src/lib.rs | 4 +-- crates/testkit/src/skip.rs | 56 +++++++++++++++++++------------------- 4 files changed, 35 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 8606ce1f68..ac68a960f8 100644 --- a/README.md +++ b/README.md @@ -375,7 +375,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit copies of a valid input, and fails the test with the case that panicked or did not finish. Its `skip` module prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the test when the variable the caller names is `1`. Any other value of that - variable except empty or `0` fails the test as a configuration error. Not published. + variable except empty fails the test as a configuration error. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 90020921ef..e16c23e2eb 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -225,9 +225,9 @@ The variable is read only when something is missing. | Value | Result | |---|---| -| Not set, empty or `0` | The helper prints `SKIPPED: ` and one line feed to stderr, and the test returns and passes. Carriage returns and line feeds in the reason are printed as `\r` and `\n`. | +| Not set or empty | The helper prints `SKIPPED: ` and one line feed to stderr, and the test returns and passes. Carriage returns and line feeds in the reason are printed as `\r` and `\n`. | | `1` | The test fails. No skip line is printed. | -| Any other value, such as `true`, `yes`, ` 1` or `1` followed by a line feed | The test fails with the reason and the variable's name and value. No skip line is printed. | +| Any other value, such as `0`, `true`, `yes`, ` 1` or `1` followed by a line feed | The test fails with the reason and the variable's name and value. No skip line is printed. | | Not Unicode | The test fails with the reason and the variable's name. No skip line is printed. | `skip::required(var)` returns the same decision without failing the test: `Ok(false)`, `Ok(true)`, @@ -352,7 +352,7 @@ cases change, and keep the test names. | craft-libs `craft-media-testkit` | `skip` and `skip_with`, which accept `1`, `true`, `yes` and `on` | Not started | | craft-libs `pdf` tests | `or_skip!` in `crates/pdf/tests/cos/oracle.rs`, which reads any value of `CRAFT_PDF_ORACLES_REQUIRED` | Not started | -After an adoption, an app that reads any value as required skips on an empty value or `0`, and -fails as a configuration error on every other value except `1`. An app that accepts `true`, `yes` +After an adoption, an app that reads any value as required skips on an empty value, and fails as +a configuration error on every other value except `1`, `0` included. An app that accepts `true`, `yes` and `on` fails on those values as a configuration error. Each adoption says which values change and keeps the variable name. diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 64e04021f3..de08d95fd5 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -27,8 +27,8 @@ //! //! [`skip`] decides what a test does when something it needs is missing (a program, a corpus, //! the craft-fonts faces): it prints one `SKIPPED:` line and returns, or fails the test when the -//! variable the caller names is `1`. A value other than unset, empty, `0` or `1` fails the test as -//! a configuration error. It is not built for `wasm32`. +//! variable the caller names is `1`. A value other than unset, empty or `1` fails the test as a +//! configuration error. It is not built for `wasm32`. //! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! diff --git a/crates/testkit/src/skip.rs b/crates/testkit/src/skip.rs index 58530a3eca..c9938fa7fb 100644 --- a/crates/testkit/src/skip.rs +++ b/crates/testkit/src/skip.rs @@ -3,7 +3,7 @@ //! //! An optional absence prints one line to stderr, `SKIPPED: `, and the test returns and //! passes. When the variable the caller names is `1`, the absence fails the test instead and no -//! skip line is printed. Unset, empty and `0` leave the test optional. Any other value, such as +//! skip line is printed. Unset and empty leave the test optional. Any other value, such as `0`, //! `true`, ` 1`, `1\n` or a value that is not valid Unicode, is a configuration error: the absence //! fails the test with the variable's name and value. The caller passes the name its repository //! uses, such as `CRAFT_MEDIA_REQUIRE_ORACLES` or `CRAFT_PDF_ORACLES_REQUIRED`; [`REQUIRED_VAR`] is @@ -40,29 +40,29 @@ pub const REQUIRED_VAR: &str = "CRAFT_TEST_REQUIRED"; /// The variable `craft-fonts-build` reads, named by [`craft_fonts`] when it fails a test. pub const FONTS_REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED"; -/// A value of the required variable that is not unset, empty, `0` or `1`. +/// A value of the required variable that is not unset, empty or `1`. #[derive(Clone, Debug, PartialEq, Eq)] pub enum RequiredError { /// The value is not valid Unicode. NotUnicode { variable: String }, - /// The value is valid Unicode but not empty, `0` or `1`. + /// The value is valid Unicode but not empty or `1`. BadValue { variable: String, value: String }, } impl fmt::Display for RequiredError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - const FIX: &str = "set it to 1 to fail a test that lacks a prerequisite, or leave it unset, empty or 0 to skip the test"; + const FIX: &str = "set it to 1 to fail a test that lacks a prerequisite, or leave it unset or empty to skip the test"; match self { Self::NotUnicode { variable } => write!(f, "{variable} is not valid Unicode; {FIX}"), - Self::BadValue { variable, value } => write!(f, "{variable}={value:?} is not empty, 0 or 1; {FIX}"), + Self::BadValue { variable, value } => write!(f, "{variable}={value:?} is not empty or 1; {FIX}"), } } } impl std::error::Error for RequiredError {} -/// Whether the variable `var` makes a missing prerequisite fail the test. Unset, empty and `0` -/// return `Ok(false)`, and `1` returns `Ok(true)`. Any other value, including one that is not +/// Whether the variable `var` makes a missing prerequisite fail the test. Unset and empty return +/// `Ok(false)`, and `1` returns `Ok(true)`. Any other value, including `0` and a value that is not /// valid Unicode, returns an error that names the variable. pub fn required(var: &str) -> Result { parse_required(var, std::env::var_os(var).as_deref()) @@ -72,7 +72,7 @@ fn parse_required(variable: &str, value: Option<&OsStr>) -> Result Date: Sun, 22 Nov 2026 00:46:24 -0800 Subject: [PATCH 4/5] craft-testkit: reject a required variable name that cannot be read `skip::required`, `skip` and `or_skip!` now return or fail with `RequiredError::BadName` when the variable name is empty or holds `=` or a NUL character, before the environment is read. The `deadline` and `hostile` modules already reject such names the same way. --- crates/testkit/README.md | 3 +++ crates/testkit/src/skip.rs | 35 +++++++++++++++++++++++++++++++---- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index e16c23e2eb..af07435694 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -230,6 +230,9 @@ The variable is read only when something is missing. | Any other value, such as `0`, `true`, `yes`, ` 1` or `1` followed by a line feed | The test fails with the reason and the variable's name and value. No skip line is printed. | | Not Unicode | The test fails with the reason and the variable's name. No skip line is printed. | +A variable name that is empty or holds `=` or a NUL character also fails the test, before the +environment is read. + `skip::required(var)` returns the same decision without failing the test: `Ok(false)`, `Ok(true)`, or a `RequiredError` that names the variable. diff --git a/crates/testkit/src/skip.rs b/crates/testkit/src/skip.rs index c9938fa7fb..566894bb72 100644 --- a/crates/testkit/src/skip.rs +++ b/crates/testkit/src/skip.rs @@ -31,7 +31,7 @@ //! `\n`, so one skip is one line. Each line is written with one call while stderr is locked, so //! lines from tests running in parallel do not mix; their order is not fixed. -use std::ffi::OsStr; +use std::ffi::{OsStr, OsString}; use std::fmt; /// The default name of the variable that makes a skip fail the test. @@ -40,9 +40,11 @@ pub const REQUIRED_VAR: &str = "CRAFT_TEST_REQUIRED"; /// The variable `craft-fonts-build` reads, named by [`craft_fonts`] when it fails a test. pub const FONTS_REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED"; -/// A value of the required variable that is not unset, empty or `1`. +/// A required variable name that cannot be read, or a value that is not unset, empty or `1`. #[derive(Clone, Debug, PartialEq, Eq)] pub enum RequiredError { + /// The variable name is empty or holds `=` or a NUL character. + BadName { variable: String }, /// The value is not valid Unicode. NotUnicode { variable: String }, /// The value is valid Unicode but not empty or `1`. @@ -53,6 +55,7 @@ impl fmt::Display for RequiredError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { const FIX: &str = "set it to 1 to fail a test that lacks a prerequisite, or leave it unset or empty to skip the test"; match self { + Self::BadName { variable } => write!(f, "{variable:?} cannot name a variable: it is empty or holds `=` or a NUL character"), Self::NotUnicode { variable } => write!(f, "{variable} is not valid Unicode; {FIX}"), Self::BadValue { variable, value } => write!(f, "{variable}={value:?} is not empty or 1; {FIX}"), } @@ -63,9 +66,18 @@ impl std::error::Error for RequiredError {} /// Whether the variable `var` makes a missing prerequisite fail the test. Unset and empty return /// `Ok(false)`, and `1` returns `Ok(true)`. Any other value, including `0` and a value that is not -/// valid Unicode, returns an error that names the variable. +/// valid Unicode, returns an error that names the variable. A name that is empty or holds `=` or a +/// NUL character returns an error before the environment is read. pub fn required(var: &str) -> Result { - parse_required(var, std::env::var_os(var).as_deref()) + required_with(var, |name| std::env::var_os(name)) +} + +/// [`required`] with the variable lookup passed in. +fn required_with(variable: &str, lookup: impl FnOnce(&str) -> Option) -> Result { + if variable.is_empty() || variable.contains(['=', '\0']) { + return Err(RequiredError::BadName { variable: variable.to_owned() }); + } + parse_required(variable, lookup(variable).as_deref()) } fn parse_required(variable: &str, value: Option<&OsStr>) -> Result { @@ -269,6 +281,21 @@ mod tests { assert!(message.starts_with("CRAFT_TEST_REQUIRED is not valid Unicode; "), "{message}"); } + #[test] + fn bad_variable_names_are_rejected_before_reading() { + for name in ["", "A=B", "A\0B"] { + let result = required_with(name, |_| panic!("the variable was read")); + assert_eq!(result, Err(RequiredError::BadName { variable: name.to_owned() }), "{name:?}"); + assert_eq!(required(name), Err(RequiredError::BadName { variable: name.to_owned() }), "{name:?}"); + + let failed = std::panic::catch_unwind(|| skip("probe absent", name)); + let message = failed.expect_err("a bad name fails the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.starts_with("probe absent, and "), "{message}"); + assert!(message.ends_with(" cannot name a variable: it is empty or holds `=` or a NUL character"), "{message}"); + } + } + /// Absence is never silent, and which of the two loud forms it takes is decided by the /// variable: `1` fails the test, and unset or empty skips. #[test] From 38141745386c0ec1bbb54b28e1f0a436b4c88fb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:32:15 -0800 Subject: [PATCH 5/5] craft-testkit: take skrifa from the workspace, behind the font-coverage feature skip::craft_fonts_cover and its tests need the new font-coverage feature, so a crate that dev-depends on craft-testkit no longer builds skrifa unless it asks for the feature. skrifa comes from the workspace dependency. skip::required is the one parser for a required variable: unset or empty is optional, 1 is required, and every other value is a configuration error. --- crates/testkit/Cargo.toml | 6 +++++- crates/testkit/README.md | 10 ++++++---- crates/testkit/src/lib.rs | 3 ++- crates/testkit/src/skip.rs | 6 +++++- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 246116ee58..554dadb1b7 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -8,10 +8,14 @@ repository.workspace = true description = "Source-level platform regression guards, test deadlines, hostile-input helpers, a reentrant test lock and skip-or-fail helpers for the Craft application suite" publish = false +[features] +# `font-coverage`: `skip::craft_fonts_cover`, which parses font data with skrifa. +font-coverage = ["dep:skrifa"] + [dependencies] [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -skrifa = { version = "0.47", default-features = false, features = ["std"] } +skrifa = { workspace = true, optional = true } [target.'cfg(unix)'.dependencies] rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } diff --git a/crates/testkit/README.md b/crates/testkit/README.md index f5e214a36a..23238ff29f 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -255,7 +255,8 @@ A variable name that is empty or holds `=` or a NUL character also fails the tes environment is read. `skip::required(var)` returns the same decision without failing the test: `Ok(false)`, `Ok(true)`, -or a `RequiredError` that names the variable. +or a `RequiredError` that names the variable. Every module of this crate that reads a required +variable reads it with `skip::required`, so one rule applies to all of them. The caller passes the name its repository uses today, such as `CRAFT_MEDIA_REQUIRE_ORACLES`, `CRAFT_PDF_ORACLES_REQUIRED`, `PDFCRAFT_ORACLES_REQUIRED` or `FILMCRAFT_REQUIRE_ORACLES`. @@ -287,9 +288,10 @@ passes the value to return as the third argument, for example `Ok(())`. `option_env!` value, or the table `craft-fonts-build` generates. A required failure names `CRAFT_FONTS_REQUIRED=1`. -`craft_fonts_cover(text, faces)` returns `true` when one face maps every character of `text` that -is not whitespace. Each face is font data with its index in a collection (`0` for a single font). A -face that does not parse covers nothing, and coverage is not combined across faces. +`craft_fonts_cover(text, faces)` needs the `font-coverage` feature, which adds skrifa. It returns +`true` when one face maps every character of `text` that is not whitespace. Each face is font data +with its index in a collection (`0` for a single font). A face that does not parse covers nothing, +and coverage is not combined across faces. The module does not change the process environment. Its tests that read a real variable run the test binary again as a child process with that variable set. diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 66656046c6..3e858a50ab 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -35,7 +35,8 @@ //! [`skip`] decides what a test does when something it needs is missing (a program, a corpus, //! the craft-fonts faces): it prints one `SKIPPED:` line and returns, or fails the test when the //! variable the caller names is `1`. A value other than unset, empty or `1` fails the test as a -//! configuration error. It is not built for `wasm32`. +//! configuration error. [`skip::required`] reads such a variable under this rule for any caller. +//! It is not built for `wasm32`. `skip::craft_fonts_cover` needs the `font-coverage` feature. //! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! diff --git a/crates/testkit/src/skip.rs b/crates/testkit/src/skip.rs index 566894bb72..934c7df6e2 100644 --- a/crates/testkit/src/skip.rs +++ b/crates/testkit/src/skip.rs @@ -147,7 +147,8 @@ pub fn craft_fonts(present: bool, required: bool) -> bool { /// font data and the index of the face in a collection (`0` for a single font). A face that does /// not parse covers nothing, and the characters must all come from the same face. Each combining /// mark is a character of its own. Text that is empty or only whitespace is covered when at least -/// one face parses. +/// one face parses. Needs the `font-coverage` feature. +#[cfg(feature = "font-coverage")] pub fn craft_fonts_cover(text: &str, faces: &[(&[u8], u32)]) -> bool { use skrifa::MetadataProvider as _; faces.iter().any(|&(data, index)| { @@ -437,6 +438,7 @@ mod tests { } /// A font holding only a format 12 `cmap` table that maps each range of code points. + #[cfg(feature = "font-coverage")] fn face(ranges: &[(u32, u32)]) -> Vec { let subtable_len = 16 + 12 * ranges.len() as u32; let mut data = Vec::new(); @@ -468,6 +470,7 @@ mod tests { } #[test] + #[cfg(feature = "font-coverage")] fn craft_fonts_cover_the_advertised_scripts() { let latin_greek_cyrillic = face(&[(0x41, 0x5A), (0x61, 0x7A), (0x391, 0x3C9), (0x410, 0x44F)]); let faces: &[(&[u8], u32)] = &[(&latin_greek_cyrillic, 0)]; @@ -479,6 +482,7 @@ mod tests { } #[test] + #[cfg(feature = "font-coverage")] fn coverage_needs_one_face_that_parses_and_maps_every_character() { let a = face(&[(u32::from('A'), u32::from('A'))]); let b = face(&[(u32::from('B'), u32::from('B'))]);