diff --git a/docs/guides/develop-a-renderer.md b/docs/guides/develop-a-renderer.md index 9283409e1..db5ef2389 100644 --- a/docs/guides/develop-a-renderer.md +++ b/docs/guides/develop-a-renderer.md @@ -279,6 +279,23 @@ These checks work on any renderer that marks entities with `data-entity-id` and units with `data-projections-unit`, which the SDK's interaction helpers add for you. +`projections check` runs the same checks on the projection's working tree, its +comparison with `HEAD` and every scenario in the renderer package's +`scenarios.json`. While you work on the renderer, narrow it to what you're +fixing: `--scenario ` checks one scenario (repeat it for more), and naming +only `scenarios.json` scenarios skips extracting and comparing, so a run takes +seconds; `--only ` runs one check by its ID (`opens-fitted`, +`neutral-endpoints`, …). When a scenario fails, the report ends its step with +the command that reruns just its failed checks: + +```text + fail Renderer checks, scenarios.json core-edit: 27 passed, 1 failed, 4 skipped + - Neutral endpoints: At Before, "core" is emphasized: … + Rerun just this: projections check -p turn-cost --scenario core-edit --only neutral-endpoints --trust +``` + +The full run stays the default, and it's what CI should run. + ## 4. Test it in CI You can run the exact same checks in Playwright inside the real host frame using diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 50a0762c3..2b95da484 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -123,6 +123,8 @@ projections check [OPTIONS] | `--png ` | Also write a PNG of the (one) projection's working tree, drawn by its renderer. | | `--from ` | Check this extractor output (what the extractor writes to stdout) for the one projection instead of extracting the working tree; nothing runs, so hand-made extractions can be drawn and checked. | | `--no-render` | Skip the renderer checks, which need Chrome, Chromium or Edge. | +| `--scenario ` | Run the renderer checks on this scenario only, for the one projection: `working-tree`, `head` (HEAD → working tree) or a scenario of its renderer package's scenarios.json. Naming only scenarios.json ones skips extracting and comparing, for a fast loop on renderer changes. Repeat it for several. Default: every scenario. Repeatable. | +| `--only ` | Run only this renderer check, by ID (`opens-fitted`, `neutral-endpoints`, …). Repeat it for several. Default: every check. Repeatable. | | `--browser ` | Chrome, Chromium or Edge executable. Default: PROJECTIONS_BROWSER, else found on PATH or in its usual install location. | | `--timeout ` | Seconds the renderer checks may take on each scenario. Default: `120`. | | `--update` | Write or rewrite the snapshots of comparator tests (never their expectations). | diff --git a/packages/cli/src/check/mod.rs b/packages/cli/src/check/mod.rs index e642bff78..cf8a6f00d 100644 --- a/packages/cli/src/check/mod.rs +++ b/packages/cli/src/check/mod.rs @@ -32,6 +32,10 @@ pub struct Options { pub ids: Vec, /// Run the renderer checks in a headless browser. pub render: bool, + /// The scenarios to run the renderer checks on, by ID; empty for every one. + pub scenarios: Vec, + /// The renderer checks to run, by ID; empty for every one. + pub only: Vec, /// The browser executable, when not found automatically. pub browser: Option, /// Write a PNG of the (single) projection's working tree here. @@ -51,6 +55,14 @@ pub struct Options { pub strict_determinism: bool, } +impl Options { + /// Whether only renderer scenarios are checked, none of them the working tree's or HEAD's, so nothing is + /// extracted. + fn renderer_only(&self) -> bool { + !self.scenarios.is_empty() && !self.scenarios.iter().any(|id| id == "working-tree" || id == "head") + } +} + /// One check's outcome: `pass`, `fail`, `warn` or `skip`. fn step(id: &str, title: &str, status: &str, message: impl Into) -> Value { json!({"id": id, "title": title, "status": status, "message": message.into()}) @@ -89,6 +101,10 @@ pub async fn check(runner: &Runner, options: Options) -> Result { options.from.is_none() || selected.len() + broken.len() == 1, "--from checks one projection's extraction: select it with -p" ); + ensure!( + options.scenarios.is_empty() || selected.len() + broken.len() == 1, + "--scenario names one projection's scenarios: select it with -p" + ); let checker = Checker { runner, has_head: runner.resolve(&root, "HEAD").is_ok(), diff --git a/packages/cli/src/check/projection.rs b/packages/cli/src/check/projection.rs index 95a6cb612..5d227b6af 100644 --- a/packages/cli/src/check/projection.rs +++ b/packages/cli/src/check/projection.rs @@ -13,6 +13,9 @@ use anyhow::Result; use serde_json::{Value, json}; use std::path::{Path, PathBuf}; +/// Why a narrowed run skips a step. +const NARROWED: &str = "--scenario names only renderer scenarios, so nothing is extracted"; + /// What every projection's check shares. pub(super) struct Checker<'a> { pub(super) runner: &'a Runner, @@ -29,7 +32,8 @@ pub(super) struct Checker<'a> { pub(super) struct Rendered<'a> { pub(super) id: &'a str, pub(super) definition: &'a Value, - pub(super) document: &'a Value, + /// The working tree's extraction; none when only renderer scenarios are checked. + pub(super) document: Option<&'a Value>, pub(super) comparison: Option<&'a Value>, pub(super) bundle: Option, } @@ -40,7 +44,14 @@ impl Checker<'_> { let id = definition["id"].as_str().unwrap_or_default().to_owned(); let options = self.options; let mut steps = vec![step("definition", "Definition", "pass", "Valid")]; - let extraction = self.extract(&id, &mut steps); + // Only renderer scenarios are checked: nothing is extracted, compared or tested. + let narrowed = options.renderer_only(); + let extraction = if narrowed { + steps.push(step("extract", self.source(), "skip", NARROWED)); + None + } else { + self.extract(&id, &mut steps) + }; if let (Some(document), None) = (&extraction, &options.from) { steps.push(determinism_step(self.runner, &id, definition, document, options.strict_determinism)); if let Some(step) = scope_step(self.runner, &id) { @@ -62,13 +73,11 @@ impl Checker<'_> { steps.push(parity_step(self.runner, &id, reference)); } // Tests use their own fixtures, so they run even when extraction failed. - steps.push(crate::comparator_tests::check_step( - &self.root, - self.runner, - definition, - options.update, - options.coverage, - )); + steps.push(if narrowed { + step(crate::comparator_tests::STEP, "Comparator tests", "skip", NARROWED) + } else { + crate::comparator_tests::check_step(&self.root, self.runner, definition, options.update, options.coverage) + }); let (renderer, bundle) = renderer_step(&self.root, definition); let renderer_failed = renderer["status"] == "fail"; steps.push(renderer); @@ -79,22 +88,22 @@ impl Checker<'_> { let skipped = |message: String| step("render", "Renderer checks", "skip", message); match (&extraction, &self.executable) { (_, None) => steps.push(skipped("--no-render".into())), - (None, _) => steps.push(skipped("Nothing extracted to render".into())), - (Some(_), _) if renderer_failed => { + (None, _) if !narrowed => steps.push(skipped("Nothing extracted to render".into())), + (_, _) if renderer_failed => { steps.push(skipped("The renderer bundle isn't available".into())); } - (Some(_), _) if bundle.is_some() && self.renderer_withheld(definition) => steps.push(step( + (_, _) if bundle.is_some() && self.renderer_withheld(definition) => steps.push(step( "render", "Renderer checks", "fail", "The custom renderer is repository code that differs from the default branch's, so it runs only with --trust: pass --trust (in VS Code, trust the workspace), or --no-render to skip its checks", )), - (Some(_), Some(Err(error))) => steps.push(skipped(format!("{error:#}. Pass --browser, or --no-render to skip them"))), - (Some(document), Some(Ok(executable))) => { + (_, Some(Err(error))) => steps.push(skipped(format!("{error:#}. Pass --browser, or --no-render to skip them"))), + (document, Some(Ok(executable))) => { let target = Rendered { id: &id, definition, - document, + document: document.as_ref(), comparison: comparison.as_ref(), bundle, }; @@ -233,10 +242,10 @@ impl Rendered<'_> { } /// The scenarios file the check writes, and a custom renderer's own. - pub(super) fn sources(&self, root: &Path, written: PathBuf) -> Vec { + pub(super) fn sources(&self, root: &Path, written: Option) -> Vec { // A custom renderer's own scenarios are checked too: they // exercise comparisons the working tree may not have. - let mut sources = vec![written]; + let mut sources: Vec = written.into_iter().collect(); if let Some(file) = crate::dev_server::package(root, self.definition) .map(|package| package.join("scenarios.json")) .filter(|file| file.is_file()) diff --git a/packages/cli/src/check/render.rs b/packages/cli/src/check/render.rs index 1a1935fb9..9935af045 100644 --- a/packages/cli/src/check/render.rs +++ b/packages/cli/src/check/render.rs @@ -17,27 +17,90 @@ impl Checker<'_> { /// Runs the renderer checks on the projection's scenarios, then writes `--png`. pub(super) async fn render(&self, target: Rendered<'_>, executable: &Path, steps: &mut Vec) -> Result<()> { let directory = tempfile::Builder::new().prefix("projections-check-").tempdir()?; - let path = write_scenarios( - directory.path(), - &self.root, - target.definition, - target.definition["title"].as_str().unwrap_or(target.id), - target.renderer_name()?, - target.document, - target.comparison, - )?; + let path = match target.document { + Some(document) => Some(write_scenarios( + directory.path(), + &self.root, + target.definition, + target.definition["title"].as_str().unwrap_or(target.id), + target.renderer_name()?, + document, + target.comparison, + )?), + None => None, + }; let sources = target.sources(&self.root, path); + if sources.is_empty() { + steps.push(step( + "render", + "Renderer checks", + "fail", + "The renderer package has no scenarios.json for --scenario to name", + )); + return Ok(()); + } let loaded = fixtures::load(&sources, target.bundle.as_slice(), "", true, self.runner.trust); for error in loaded.errors() { steps.push(step("render", "Renderer scenarios", "fail", error)); } - let (keys, titles) = scenario_keys(&loaded.value, self.options.from.is_some()); + let (mut keys, titles, ids) = scenario_keys(&loaded.value, self.options.from.is_some()); + // A scenarios.json scenario with the ID of the check's own (`working-tree`, `head`) can't be named apart. + let mut shared: Vec<&str> = ids + .values() + .filter(|(id, own)| !own && ids.values().any(|(other, mine)| *mine && other == id)) + .map(|(id, _)| id.as_str()) + .collect(); + shared.sort_unstable(); + shared.dedup(); + for id in &shared { + steps.push(step( + "render", + "Renderer scenarios", + "warn", + format!("The renderer package's scenarios.json has a scenario {id}, the ID of the check's own; --scenario {id} names the check's, so rename it to check it alone"), + )); + } + if !self.options.scenarios.is_empty() { + let missing: Vec<&String> = self + .options + .scenarios + .iter() + .filter(|id| !ids.values().any(|(known, _)| known == *id)) + .collect(); + if !missing.is_empty() { + let mut known: Vec<&str> = ids.values().map(|(id, _)| id.as_str()).collect(); + known.sort_unstable(); + known.dedup(); + steps.push(step( + "render", + "Renderer checks", + "fail", + format!( + "No scenario {}: the scenarios are {}", + missing.iter().map(|id| id.as_str()).collect::>().join(", "), + known.join(", ") + ), + )); + } + keys.retain(|key| { + ids.get(key) + .is_some_and(|(id, own)| self.options.scenarios.contains(id) && (*own || !shared.contains(&id.as_str()))) + }); + } + let rerun = Rerun { + projection: target.id, + trust: self.runner.trust, + from: self.options.from.as_deref(), + ids: &ids, + shared: &shared, + }; match renderer_checks( Scenarios { sources: &sources, bundle: target.bundle, trust: self.runner.trust, keys: &keys, + checks: &self.options.only, }, executable, &self.browsers, @@ -46,10 +109,13 @@ impl Checker<'_> { ) .await { - Ok(results) => steps.extend(results.into_iter().map(|(key, checks)| checks_step(&titles, &key, checks))), + Ok(results) => steps.extend(results.into_iter().map(|(key, checks)| checks_step(&titles, &rerun, &key, checks))), Err(error) => steps.push(failed("render", "Renderer checks", &error)), } - self.png(target.document, executable, steps).await + match target.document { + Some(document) => self.png(document, executable, steps).await, + None => Ok(()), + } } /// `--png`: an image of the working tree's extraction, never overwriting a file. @@ -99,9 +165,13 @@ impl Checker<'_> { } } -/// The keys of the loaded scenarios that can be checked, and each one's title. -fn scenario_keys(loaded: &Value, supplied: bool) -> (Vec, HashMap) { +/// Each checked scenario's ID, and whether it is the check's own (the working tree's or HEAD's) or scenarios.json's. +type Ids = HashMap; + +/// The keys of the loaded scenarios that can be checked, and each one's title and the ID `--scenario` names it by. +fn scenario_keys(loaded: &Value, supplied: bool) -> (Vec, HashMap, Ids) { let mut titles = HashMap::new(); + let mut ids = HashMap::new(); let keys = loaded["scenarios"] .as_array() .into_iter() @@ -110,10 +180,17 @@ fn scenario_keys(loaded: &Value, supplied: bool) -> (Vec, HashMap String { @@ -128,8 +205,51 @@ fn scenario_title(scenario: &Value, supplied: bool) -> String { } } -/// One scenario's renderer checks as a step, its failures as details. -fn checks_step(titles: &HashMap, key: &str, checks: Value) -> Value { +/// What a failed scenario's rerun command needs: the projection, whether it ran with trust, the extraction it was +/// given (`--from`), each key's scenario ID and the scenarios.json IDs that are also the check's own. +struct Rerun<'a> { + projection: &'a str, + trust: bool, + from: Option<&'a Path>, + ids: &'a Ids, + shared: &'a [&'a str], +} + +impl Rerun<'_> { + /// The command that checks just these failed checks on just this scenario: the supplied extraction again for the + /// check's own scenario of a `--from` run, and every scenario for one `--scenario` can't name apart. + fn command(&self, key: &str, failed: &[&str]) -> String { + let mut command = format!("projections check -p {}", self.projection); + match (self.ids.get(key), self.from) { + (Some((_, true)), Some(file)) => command.push_str(&format!(" --from {}", shell_word(&file.display().to_string()))), + (Some((id, own)), _) if *own || !self.shared.contains(&id.as_str()) => command.push_str(&format!(" --scenario {id}")), + _ => {} + } + for check in failed { + command.push_str(&format!(" --only {check}")); + } + if self.trust { + command.push_str(" --trust"); + } + command + } +} + +/// A word a POSIX shell reads as one argument: as it is when no character in it is special, else single-quoted. +fn shell_word(word: &str) -> String { + if !word.is_empty() + && word + .chars() + .all(|character| character.is_ascii_alphanumeric() || "-_./:@%+=,".contains(character)) + { + word.to_owned() + } else { + format!("'{}'", word.replace('\'', "'\\''")) + } +} + +/// One scenario's renderer checks as a step, its failures as details and the command that reruns just them. +fn checks_step(titles: &HashMap, rerun: &Rerun<'_>, key: &str, checks: Value) -> Value { let all = checks.as_array().cloned().unwrap_or_default(); let failures: Vec = all .iter() @@ -155,7 +275,62 @@ fn checks_step(titles: &HashMap, key: &str, checks: Value) -> Va ); if !failures.is_empty() { value["details"] = json!(failures); + let failed: Vec<&str> = all + .iter() + .filter(|check| check["status"] == "fail") + .filter_map(|check| check["id"].as_str()) + .collect(); + value["rerun"] = json!(rerun.command(key, &failed)); } value["checks"] = Value::Array(all); value } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_failed_scenario_says_how_to_rerun_just_its_failed_checks() { + let ids = HashMap::from([ + ("check/head".to_owned(), ("head".to_owned(), true)), + ("check/working-tree".to_owned(), ("working-tree".to_owned(), true)), + ("cards/head".to_owned(), ("head".to_owned(), false)), + ]); + let rerun = Rerun { + projection: "access-map", + trust: true, + from: None, + ids: &ids, + shared: &["head"], + }; + let checks = json!([ + {"id": "opens-fitted", "title": "Opens fitted", "status": "fail", "details": ["cut"]}, + {"id": "palette", "title": "Colors", "status": "pass", "details": []}, + {"id": "spacing", "title": "Spacing", "status": "fail", "details": ["off"]}, + ]); + let step = checks_step(&HashMap::new(), &rerun, "check/head", checks); + assert_eq!( + step["rerun"], + "projections check -p access-map --scenario head --only opens-fitted --only spacing --trust" + ); + let passed = checks_step(&HashMap::new(), &rerun, "check/head", json!([{"id": "palette", "status": "pass"}])); + assert!(passed.get("rerun").is_none()); + // A scenarios.json scenario --scenario can't name apart reruns every scenario. + assert_eq!( + rerun.command("cards/head", &["palette"]), + "projections check -p access-map --only palette --trust" + ); + // A supplied extraction is checked again, not the working tree. + let supplied = Rerun { + from: Some(Path::new("edited.json")), + ..rerun + }; + assert_eq!( + supplied.command("check/working-tree", &["palette"]), + "projections check -p access-map --from edited.json --only palette --trust" + ); + assert_eq!(shell_word("fixtures/edited extraction.json"), "'fixtures/edited extraction.json'"); + assert_eq!(shell_word("it's.json"), r"'it'\''s.json'"); + } +} diff --git a/packages/cli/src/check/stage.rs b/packages/cli/src/check/stage.rs index f76ee53ea..77d549858 100644 --- a/packages/cli/src/check/stage.rs +++ b/packages/cli/src/check/stage.rs @@ -22,6 +22,8 @@ pub(super) struct Scenarios<'a> { pub bundle: Option, pub trust: bool, pub keys: &'a [String], + /// The checks to run, by ID; empty for every one. + pub checks: &'a [String], } /// Runs the host's renderer checks on `scenarios` in a headless browser. @@ -31,6 +33,7 @@ pub(super) async fn renderer_checks( bundle, trust, keys, + checks, }: Scenarios<'_>, executable: &Path, browsers: &browser::Pool, @@ -61,6 +64,7 @@ pub(super) async fn renderer_checks( let (served, handle) = (host.clone(), tokio::runtime::Handle::current()); let executable = executable.to_path_buf(); let keys = keys.to_vec(); + let options = if checks.is_empty() { json!({}) } else { json!({"checks": checks}) }; let browsers = browsers.clone(); let results = tokio::task::spawn_blocking(move || -> Result> { let mut browser = browsers.take(browser::LaunchOptions { @@ -78,7 +82,7 @@ pub(super) async fn renderer_checks( let page = browser.open_page(deadline)?; let results = served .attach(&mut browser, &page.session, handle, deadline) - .and_then(|()| run_stage(&mut browser, &page.session, &url, keys, timeout, deadline)); + .and_then(|()| run_stage(&mut browser, &page.session, &url, (keys, &options), timeout, deadline)); browsers.give(browser, page)?; results }) @@ -93,7 +97,7 @@ fn run_stage( browser: &mut browser::Browser, session: &str, url: &str, - keys: Vec, + (keys, options): (Vec, &Value), timeout: Duration, deadline: Instant, ) -> Result> { @@ -110,8 +114,9 @@ fn run_stage( session, deadline, &format!( - "window.projectionsStage.runChecks({}, {{}}).then(results => JSON.stringify(results))", - serde_json::to_string(&key)? + "window.projectionsStage.runChecks({}, {}).then(results => JSON.stringify(results))", + serde_json::to_string(&key)?, + options ), ) .map_err(|error| { diff --git a/packages/cli/src/check/tests.rs b/packages/cli/src/check/tests.rs index 4fe1e7d3b..bbf5cce65 100644 --- a/packages/cli/src/check/tests.rs +++ b/packages/cli/src/check/tests.rs @@ -60,3 +60,26 @@ fn scenarios_present_as_the_definition_does() { assert_eq!(scenario["presentation"], presentation, "{}", scenario["id"]); } } + +#[test] +fn naming_only_renderer_scenarios_skips_extracting() { + let options = |scenarios: &[&str]| super::Options { + ids: Vec::new(), + render: true, + scenarios: scenarios.iter().map(|id| (*id).to_owned()).collect(), + only: Vec::new(), + browser: None, + png: None, + from: None, + timeout: std::time::Duration::from_secs(1), + cancel: std::sync::Arc::default(), + update: false, + coverage: false, + parity: None, + strict_determinism: false, + }; + assert!(!options(&[]).renderer_only()); + assert!(options(&["core-edit"]).renderer_only()); + assert!(!options(&["core-edit", "head"]).renderer_only()); + assert!(!options(&["working-tree"]).renderer_only()); +} diff --git a/packages/cli/src/check/text.rs b/packages/cli/src/check/text.rs index cb865a6a6..eee240b8a 100644 --- a/packages/cli/src/check/text.rs +++ b/packages/cli/src/check/text.rs @@ -35,6 +35,9 @@ fn step_text(text: &mut String, step: &Value) { for detail in step["details"].as_array().into_iter().flatten() { text.push_str(&format!(" - {}\n", detail.as_str().unwrap_or_default())); } + if let Some(rerun) = step["rerun"].as_str() { + text.push_str(&format!(" Rerun just this: {rerun}\n")); + } let Some(error) = step.get("error") else { return; }; diff --git a/packages/cli/src/commands/authoring.rs b/packages/cli/src/commands/authoring.rs index 7c7137858..945696220 100644 --- a/packages/cli/src/commands/authoring.rs +++ b/packages/cli/src/commands/authoring.rs @@ -95,6 +95,15 @@ pub struct Check { /// Skip the renderer checks, which need Chrome, Chromium or Edge #[arg(long, conflicts_with = "png")] pub no_render: bool, + /// Run the renderer checks on this scenario only, for the one projection: `working-tree`, `head` (HEAD → working + /// tree) or a scenario of its renderer package's scenarios.json. Naming only scenarios.json ones skips extracting + /// and comparing, for a fast loop on renderer changes. Repeat it for several [default: every scenario] + #[arg(long = "scenario", value_name = "ID", conflicts_with_all = ["no_render", "png", "from"])] + pub scenarios: Vec, + /// Run only this renderer check, by ID (`opens-fitted`, `neutral-endpoints`, …). Repeat it for several [default: + /// every check] + #[arg(long = "only", value_name = "CHECK", conflicts_with = "no_render")] + pub only: Vec, /// Chrome, Chromium or Edge executable. Default: PROJECTIONS_BROWSER, else found on PATH or in its usual install location #[arg(long, value_name = "PATH")] pub browser: Option, @@ -479,6 +488,8 @@ pub async fn check(directory: &Path, args: Check) -> Result<()> { check::Options { ids: args.projections, render: !args.no_render, + scenarios: args.scenarios, + only: args.only, browser: args.browser, png: args.png, from: args.from, diff --git a/packages/cli/src/commands/help/check.after-help.md b/packages/cli/src/commands/help/check.after-help.md index 7b0b92aa9..de9555094 100644 --- a/packages/cli/src/commands/help/check.after-help.md +++ b/packages/cli/src/commands/help/check.after-help.md @@ -2,6 +2,8 @@ Examples: projections check --trust projections check -p service-map --no-render the fast loop: definition, extraction and comparator tests + projections check -p cards --trust --scenario empty the renderer's fast loop: one scenarios.json scenario, nothing extracted + projections check -p cards --trust --scenario head --only opens-fitted one renderer check on HEAD → working tree projections check -p service-map --no-render --update write comparator tests' snapshots projections check -p service-map --no-render --coverage which comparator rules the tests run projections check -p service-map --trust --png /tmp/service-map.png diff --git a/packages/cli/src/tools/catalog.rs b/packages/cli/src/tools/catalog.rs index 4160253cd..dcaec7184 100644 --- a/packages/cli/src/tools/catalog.rs +++ b/packages/cli/src/tools/catalog.rs @@ -109,6 +109,8 @@ pub fn catalog() -> Vec { json!({ "projections": projection_ids("The projections to check; default the current view's (current_view), else every one the working tree defines"), "render": {"type": "boolean", "description": "Also run the renderer checks in a headless browser (slower; default false)"}, + "scenarios": {"type": "array", "items": {"type": "string", "minLength": 1, "maxLength": 200}, "maxItems": 20, "description": "With render, run the renderer checks on these scenarios only, for one projection: working-tree, head (HEAD → working tree) or its renderer package's scenarios.json IDs. Naming only scenarios.json ones skips extracting and comparing, for a fast loop on a renderer change"}, + "checks": {"type": "array", "items": {"type": "string", "minLength": 1, "maxLength": 100}, "maxItems": 40, "description": "With render, run only these renderer checks, by ID (opens-fitted, neutral-endpoints, …); a failed scenario's report names the command that reruns just its failed checks"}, }), &[], ), diff --git a/packages/cli/src/tools/checks.rs b/packages/cli/src/tools/checks.rs index 646743d7c..0ffc022cd 100644 --- a/packages/cli/src/tools/checks.rs +++ b/packages/cli/src/tools/checks.rs @@ -69,17 +69,27 @@ pub(super) async fn prepare(service: &Service, input: &Value) -> Answer { pub(super) async fn check(service: &Service, input: &Value) -> Answer { let runner = service.runner().without_trials(); - let ids: Vec = input["projections"] - .as_array() - .into_iter() - .flatten() - .filter_map(|id| id.as_str().map(str::to_owned)) - .collect(); + let strings = |key: &str| -> Vec { + input[key] + .as_array() + .into_iter() + .flatten() + .filter_map(|item| item.as_str().map(str::to_owned)) + .collect() + }; + let ids = strings("projections"); let cancel = runner.cancel.clone(); let _cancel = OnDrop(Some(move || cancel.store(true, std::sync::atomic::Ordering::SeqCst))); + if input["render"] != true && !(strings("scenarios").is_empty() && strings("checks").is_empty()) { + return Err(Failure::from( + "scenarios and checks narrow the renderer checks, which run only with render: pass render: true", + )); + } let options = crate::check::Options { ids, render: input["render"] == true, + scenarios: strings("scenarios"), + only: strings("checks"), browser: None, png: None, from: None, @@ -100,7 +110,13 @@ pub(super) async fn check(service: &Service, input: &Value) -> Answer { .as_array() .into_iter() .flatten() - .map(|step| json!({"id": step["id"], "title": step["title"], "status": step["status"], "message": step["message"]})) + .map(|step| { + let mut value = json!({"id": step["id"], "title": step["title"], "status": step["status"], "message": step["message"]}); + if let Some(rerun) = step.get("rerun") { + value["rerun"] = rerun.clone(); + } + value + }) .collect(); json!({"id": projection["id"], "title": projection["title"], "ok": projection["ok"], "steps": steps}) }) diff --git a/packages/integrations/vscode/package.json b/packages/integrations/vscode/package.json index 9d5c2b95c..adcfbb5f4 100644 --- a/packages/integrations/vscode/package.json +++ b/packages/integrations/vscode/package.json @@ -985,6 +985,16 @@ "inputSchema": { "additionalProperties": false, "properties": { + "checks": { + "description": "With render, run only these renderer checks, by ID (opens-fitted, neutral-endpoints, …); a failed scenario's report names the command that reruns just its failed checks", + "items": { + "maxLength": 100, + "minLength": 1, + "type": "string" + }, + "maxItems": 40, + "type": "array" + }, "projections": { "description": "The projections to check; default the current view's (current_view), else every one the working tree defines", "items": { @@ -1001,6 +1011,16 @@ "description": "Also run the renderer checks in a headless browser (slower; default false)", "type": "boolean" }, + "scenarios": { + "description": "With render, run the renderer checks on these scenarios only, for one projection: working-tree, head (HEAD → working tree) or its renderer package's scenarios.json IDs. Naming only scenarios.json ones skips extracting and comparing, for a fast loop on a renderer change", + "items": { + "maxLength": 200, + "minLength": 1, + "type": "string" + }, + "maxItems": 20, + "type": "array" + }, "folder": { "type": "string", "description": "The workspace folder to act on, by name or path, when several are open; default the active editor's folder, else the projection tab's, else the first" diff --git a/packages/renderers/testing/src/checks/runner.ts b/packages/renderers/testing/src/checks/runner.ts index e4947efdc..055d5f42c 100644 --- a/packages/renderers/testing/src/checks/runner.ts +++ b/packages/renderers/testing/src/checks/runner.ts @@ -29,6 +29,8 @@ const run: Checks = { /** Runs the checks in order against one subject. A failure to load or measure fails that check, not the run. */ export async function runChecks(driver: CheckDriver, subject: StageSubject, options: CheckOptions = {}): Promise { + const unknown = (options.checks ?? []).filter(id => !(allChecks as readonly string[]).includes(id)) + if (unknown.length) throw new Error(`No renderer check is named ${unknown.join(', ')}; the checks are ${allChecks.join(', ')}`) const results: CheckResult[] = [] let modes: readonly ComparisonMode[] = progressModes try { diff --git a/packages/renderers/testing/test/helpers.test.mjs b/packages/renderers/testing/test/helpers.test.mjs index d564330af..57ac8e7d2 100644 --- a/packages/renderers/testing/test/helpers.test.mjs +++ b/packages/renderers/testing/test/helpers.test.mjs @@ -807,3 +807,10 @@ test('a paint difference names the part only one side draws, when the parts they 'its paint changes (div 0: background-color: rgb(255, 255, 255) → rgb(1, 1, 1))', ) }) + +test('runChecks names the checks when asked for one that does not exist', async () => { + await assert.rejects( + runChecks({}, {mode: 'extraction'}, {checks: ['opens-fitted', 'no-such-check']}), + /No renderer check is named no-such-check; the checks are neutral-endpoints, /u, + ) +})