diff --git a/Cargo.lock b/Cargo.lock index a69ced2..dedac95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1002,6 +1002,7 @@ dependencies = [ "jiff", "mockito", "open", + "percent-encoding", "predicates", "pulldown-cmark", "rand 0.10.3", diff --git a/Cargo.toml b/Cargo.toml index 08e41c1..4062dfb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ toml = "1" dirs = "7" thiserror = "2" url = "2" +percent-encoding = "2" pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] } comfy-table = "8" open = "5" diff --git a/docs/GUIDE.md b/docs/GUIDE.md index e6ba68c..95cd2e9 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1111,7 +1111,9 @@ geekcli snapshot / --selector ".card" --nth 2 --out third-card.png ``` Output is `{"path", "url", "width", "height", "full", "bytes", "browser"}`; -`-q` prints just the file path. Only public pages render: the browser +`-q` prints just the file path. `--mobile` fixes the viewport, so it +cannot be combined with `--width`, `--height` or `--scale` (that is a usage +error); the same holds for `inspect`. Only public pages render: the browser runs without a login, so a draft or scheduled post is a 404 (§5); snapshot it after publishing. After a content change, snapshot the page and look at it before moving on; unstyled @@ -1141,7 +1143,10 @@ geekcli inspect / --mobile --assert "document.querySelector('.mobile-menu')?.che Every successful query prints JSON with the URL, viewport and value. `--assert` exits 1 if its expression is false, which makes it suitable for agent and CI checks. `--js` is a browser-side escape hatch; prefer selector -queries and assertions when they express the check. +queries and assertions when they express the check. Values JSON cannot hold +(`NaN`, `Infinity`, `-0`, a BigInt) come back as strings such as `"NaN"`, +and an invalid CSS selector fails with `browser query failed` whichever +selector option you used. ## 21. Writing content that renders diff --git a/src/commands/inspect.rs b/src/commands/inspect.rs index 3c81254..50239be 100644 --- a/src/commands/inspect.rs +++ b/src/commands/inspect.rs @@ -6,6 +6,7 @@ use std::path::PathBuf; use clap::{ArgGroup, Args}; +use headless_chrome::protocol::cdp::Runtime; use serde_json::{json, Value}; use super::{snapshot, Context}; @@ -58,8 +59,8 @@ pub struct InspectArgs { /// Viewport height in CSS pixels #[arg(long, default_value_t = 900, value_name = "PX")] pub height: u32, - /// Phone emulation (390x844, touch, device scale 2) - #[arg(long, conflicts_with_all = ["width", "height"])] + /// Phone emulation (390x844, touch, device scale 2); not with --width/--height/--scale + #[arg(long, conflicts_with_all = ["width", "height", "scale"])] pub mobile: bool, /// Device scale factor; 2 doubles the pixel size for sharper text #[arg(long, default_value_t = 1, value_name = "N")] @@ -98,8 +99,15 @@ pub fn run(ctx: &Context, args: &InspectArgs) -> Result<()> { let mut doc = snapshot::visit(&browser, &capture, |tab| { if let Some(selector) = &args.text { let value = element(tab, selector)? - .get_inner_text() - .map_err(|error| browser_error(&error))?; + .call_js_fn( + "function() { return this.innerText ?? this.textContent ?? ''; }", + vec![], + false, + ) + .map_err(|error| browser_error(&error))? + .value + .and_then(|v| v.as_str().map(str::to_string)) + .ok_or_else(|| Error::Other("element did not return text".into()))?; Ok(json!({"operation": "text", "selector": selector, "value": value})) } else if let Some(selector) = &args.html { let value = element(tab, selector)? @@ -126,15 +134,20 @@ pub fn run(ctx: &Context, args: &InspectArgs) -> Result<()> { let value = selector_count(tab, selector)?; Ok(json!({"operation": "count", "selector": selector, "value": value})) } else if let Some(selector) = &args.exists { - let value = tab.find_element(selector).is_ok(); + let value = match tab.find_element(selector) { + Ok(_) => true, + Err(error) if snapshot::is_no_element_found(&error) => false, + Err(error) => return Err(browser_error(&error)), + }; Ok(json!({"operation": "exists", "selector": selector, "value": value})) } else if let Some(selector) = &args.visible { - let value = tab - .find_element(selector) - .ok() - .map(|element| element.is_visible().map_err(|error| browser_error(&error))) - .transpose()? - .unwrap_or(false); + let value = match tab.find_element(selector) { + Ok(element) => element + .is_visible() + .map_err(|error| browser_error(&error))?, + Err(error) if snapshot::is_no_element_found(&error) => false, + Err(error) => return Err(browser_error(&error)), + }; Ok(json!({"operation": "visible", "selector": selector, "value": value})) } else if let Some(expression) = &args.js { let value = evaluate(tab, expression)?; @@ -162,25 +175,87 @@ fn element<'a>( tab: &'a headless_chrome::Tab, selector: &str, ) -> Result> { - tab.find_element(selector) - .map_err(|_| Error::Other(format!("no element matches selector `{selector}`"))) + tab.find_element(selector).map_err(|error| { + if snapshot::is_no_element_found(&error) { + Error::Other(format!("no element matches selector `{selector}`")) + } else { + browser_error(&error) + } + }) } fn selector_count(tab: &headless_chrome::Tab, selector: &str) -> Result { let selector = serde_json::to_string(selector) .map_err(|e| Error::Other(format!("cannot encode selector: {e}")))?; + // A bad selector throws in the page; report it the way the other + // selector operations do, not as a JavaScript error. let value = evaluate( tab, &format!("document.querySelectorAll({selector}).length"), - )?; + ) + .map_err(|error| match error { + Error::Other(message) => Error::Other(format!( + "browser query failed: {}", + message + .strip_prefix("JavaScript error: ") + .unwrap_or(&message) + )), + other => other, + })?; value .as_u64() .ok_or_else(|| Error::Other("the browser did not return a selector count".into())) } fn evaluate(tab: &headless_chrome::Tab, expression: &str) -> Result { - tab.evaluate(expression, true) - .map_err(|error| browser_error(&error))? + let ret = tab + .call_method(Runtime::Evaluate { + expression: expression.to_string(), + return_by_value: Some(true), + await_promise: Some(true), + generate_preview: Some(false), + silent: Some(false), + include_command_line_api: Some(false), + user_gesture: Some(false), + object_group: None, + context_id: None, + throw_on_side_effect: None, + timeout: None, + disable_breaks: None, + repl_mode: None, + allow_unsafe_eval_blocked_by_csp: None, + unique_context_id: None, + serialization_options: None, + }) + .map_err(|error| browser_error(&error))?; + decode_eval_result(ret) +} + +fn decode_eval_result(ret: Runtime::EvaluateReturnObject) -> Result { + if let Some(details) = ret.exception_details { + let detail = details.exception.as_ref().and_then(|e| { + e.description + .as_deref() + .filter(|s| !s.is_empty()) + .map(str::to_string) + .or_else(|| e.value.as_ref().map(ToString::to_string)) + }); + let message = match (details.text.is_empty(), detail) { + (false, Some(d)) => format!("JavaScript error: {}: {d}", details.text), + (false, None) => format!("JavaScript error: {}", details.text), + (true, Some(d)) => format!("JavaScript error: {d}"), + (true, None) => "JavaScript evaluation failed".to_string(), + }; + return Err(Error::Other(message)); + } + if ret.result.subtype == Some(Runtime::RemoteObjectSubtype::Null) { + return Ok(Value::Null); + } + // NaN, ±Infinity, -0 and BigInts have no JSON form; report them as text. + if let Some(raw) = ret.result.unserializable_value { + return Ok(Value::String(raw)); + } + ret.result .value .ok_or_else(|| Error::Other("JavaScript did not return a JSON value".into())) } @@ -188,3 +263,131 @@ fn evaluate(tab: &headless_chrome::Tab, expression: &str) -> Result { fn browser_error(error: &anyhow::Error) -> Error { Error::Other(format!("browser query failed: {error}")) } + +#[cfg(test)] +mod tests { + use clap::Parser as _; + + use super::*; + use crate::cli::Cli; + + fn remote_object( + kind: Runtime::RemoteObjectType, + subtype: Option, + value: Option, + description: Option<&str>, + ) -> Runtime::RemoteObject { + Runtime::RemoteObject { + Type: kind, + subtype, + class_name: None, + value, + unserializable_value: None, + description: description.map(str::to_string), + deep_serialized_value: None, + object_id: None, + preview: None, + custom_preview: None, + } + } + + #[test] + fn decode_eval_result_handles_json_null_undefined_and_exceptions() { + let obj = Runtime::EvaluateReturnObject { + result: remote_object( + Runtime::RemoteObjectType::Object, + None, + Some(json!({"a": 1})), + None, + ), + exception_details: None, + }; + assert_eq!(decode_eval_result(obj).ok(), Some(json!({"a": 1}))); + + let arr = Runtime::EvaluateReturnObject { + result: remote_object( + Runtime::RemoteObjectType::Object, + Some(Runtime::RemoteObjectSubtype::Array), + Some(json!([1, 2])), + None, + ), + exception_details: None, + }; + assert_eq!(decode_eval_result(arr).ok(), Some(json!([1, 2]))); + + let null = Runtime::EvaluateReturnObject { + result: remote_object( + Runtime::RemoteObjectType::Object, + Some(Runtime::RemoteObjectSubtype::Null), + None, + None, + ), + exception_details: None, + }; + assert_eq!(decode_eval_result(null).ok(), Some(Value::Null)); + + let thrown_true = Runtime::EvaluateReturnObject { + result: remote_object( + Runtime::RemoteObjectType::Boolean, + None, + Some(Value::Bool(true)), + None, + ), + exception_details: Some(Runtime::ExceptionDetails { + exception_id: 1, + text: "Uncaught".into(), + line_number: 0, + column_number: 0, + script_id: None, + url: None, + stack_trace: None, + exception: Some(remote_object( + Runtime::RemoteObjectType::Boolean, + None, + Some(Value::Bool(true)), + None, + )), + execution_context_id: None, + }), + }; + assert!(matches!( + decode_eval_result(thrown_true), + Err(Error::Other(msg)) if msg.contains("Uncaught") && msg.contains("true") + )); + + let undef = Runtime::EvaluateReturnObject { + result: remote_object(Runtime::RemoteObjectType::Undefined, None, None, None), + exception_details: None, + }; + assert!(matches!(decode_eval_result(undef), Err(Error::Other(_)))); + } + + #[test] + fn decode_eval_result_reports_unserializable_numbers_as_strings() { + for (kind, raw) in [ + (Runtime::RemoteObjectType::Number, "NaN"), + (Runtime::RemoteObjectType::Number, "-Infinity"), + (Runtime::RemoteObjectType::Number, "-0"), + (Runtime::RemoteObjectType::Bigint, "12n"), + ] { + let mut result = remote_object(kind, None, None, None); + result.unserializable_value = Some(raw.to_string()); + let ret = Runtime::EvaluateReturnObject { + result, + exception_details: None, + }; + assert_eq!( + decode_eval_result(ret).ok(), + Some(Value::String(raw.to_string())) + ); + } + } + + #[test] + fn mobile_conflicts_with_scale() { + assert!(Cli::try_parse_from([ + "geekcli", "inspect", "/", "--text", "h1", "--mobile", "--scale", "1" + ]) + .is_err()); + } +} diff --git a/src/commands/snapshot.rs b/src/commands/snapshot.rs index 8fb0a33..2220d1a 100644 --- a/src/commands/snapshot.rs +++ b/src/commands/snapshot.rs @@ -50,8 +50,8 @@ pub struct SnapshotArgs { /// Zero-based match to capture when --selector matches more than one element #[arg(long, default_value_t = 0, requires = "selector", value_name = "N")] pub nth: usize, - /// Phone emulation (390x844, touch, device scale 2) - #[arg(long, conflicts_with_all = ["width", "height"])] + /// Phone emulation (390x844, touch, device scale 2); not with --width/--height/--scale + #[arg(long, conflicts_with_all = ["width", "height", "scale"])] pub mobile: bool, /// Device scale factor; 2 doubles the pixel size for sharper text #[arg(long, default_value_t = 1, value_name = "N")] @@ -71,10 +71,7 @@ pub fn run(ctx: &Context, args: &SnapshotArgs) -> Result<()> { } else { (args.width, args.height, args.scale.max(1)) }; - let out = args - .out - .clone() - .unwrap_or_else(|| default_out(&args.target)); + let out = args.out.clone().unwrap_or_else(|| default_out(&url)); let browser_path = find_browser(args.browser.as_deref())?; if ctx.printer.format == crate::output::Format::Table { @@ -213,9 +210,13 @@ pub fn render( ) -> Result> { visit(browser_path, capture, |tab| { let clip = if let Some(selector) = selector { - let elements = tab - .find_elements(selector) - .map_err(|_| Error::Other(format!("no element matches selector `{selector}`")))?; + let elements = tab.find_elements(selector).map_err(|error| { + if is_no_element_found(&error) { + Error::Other(format!("no element matches selector `{selector}`")) + } else { + Error::Other(format!("browser query failed: {error}")) + } + })?; let Some(element) = elements.get(nth) else { return Err(Error::Other(format!( "selector `{selector}` matched {} element(s); --nth {nth} is out of range", @@ -243,26 +244,31 @@ pub fn render( }) } -/// A site-relative path becomes an absolute URL on the current site. +/// A site-relative path becomes an absolute URL on the current site. A full +/// URL is accepted in any letter case and comes back normalized +/// (`HTTPS://…` → `https://…`). pub fn resolve_url(client: &crate::client::Client, target: &str) -> String { let target = target.trim(); - if target.starts_with("http://") || target.starts_with("https://") { - return target.to_string(); + let lower = target.to_ascii_lowercase(); + if lower.starts_with("http://") || lower.starts_with("https://") { + return url::Url::parse(target).map_or_else(|_| target.to_string(), String::from); } client.site_url(target) } /// `/blog/my-post/` → `snapshot-blog-my-post.png`; `/` → `snapshot-home.png`. pub fn default_out(target: &str) -> PathBuf { - let path = target - .trim() - .trim_start_matches("https://") - .trim_start_matches("http://"); - let path = path.find('/').map_or("", |i| &path[i..]); - let slug: String = path - .split(['?', '#']) - .next() - .unwrap_or_default() + let trimmed = target.trim(); + let parsed = url::Url::parse(trimmed) + .ok() + .filter(|u| matches!(u.scheme(), "http" | "https")); + let raw_path = match &parsed { + Some(url) => url.path(), + None => trimmed.split(['?', '#']).next().unwrap_or_default(), + }; + // `Url::path()` is percent-encoded; slug the characters it stands for. + let raw_path = percent_encoding::percent_decode_str(raw_path).decode_utf8_lossy(); + let slug: String = raw_path .trim_matches('/') .chars() .map(|c| { @@ -394,16 +400,72 @@ fn playwright_chromium(cache: &Path, suffix: &str) -> Vec { builds.into_iter().map(|b| b.join(suffix)).collect() } +pub(crate) fn is_no_element_found(error: &anyhow::Error) -> bool { + error + .downcast_ref::() + .is_some() +} + +fn parse_pathext(raw: Option<&str>) -> Vec { + let exts: Vec = raw + .unwrap_or_default() + .split(';') + .map(|ext| ext.trim().trim_start_matches('.')) + .filter(|ext| !ext.is_empty()) + .map(str::to_string) + .collect(); + if exts.is_empty() { + vec!["EXE".to_string()] + } else { + exts + } +} + +fn path_candidates(dir: &Path, name: &str, pathext: Option<&str>) -> Vec { + if Path::new(name).extension().is_none() { + if let Some(raw) = pathext { + return parse_pathext(Some(raw)) + .into_iter() + .map(|ext| dir.join(format!("{name}.{ext}"))) + .collect(); + } + } + vec![dir.join(name)] +} + +fn find_on_dirs(dirs: &[PathBuf], name: &str, pathext: Option<&str>) -> Option { + if let Some(found) = dirs + .iter() + .flat_map(|dir| path_candidates(dir, name, pathext)) + .find(|p| p.is_file()) + { + return Some(found); + } + if pathext.is_some() && Path::new(name).extension().is_none() { + return dirs.iter().map(|dir| dir.join(name)).find(|p| p.is_file()); + } + None +} + fn on_path(name: &str) -> Option { let path = std::env::var_os("PATH")?; - std::env::split_paths(&path) - .map(|dir| dir.join(name)) - .find(|p| p.is_file()) + let dirs: Vec = std::env::split_paths(&path).collect(); + let pathext = if cfg!(windows) { + Some(std::env::var("PATHEXT").unwrap_or_default()) + } else { + None + }; + find_on_dirs(&dirs, name, pathext.as_deref()) } #[cfg(test)] mod tests { + use clap::Parser as _; + use super::*; + use crate::cli::Cli; + use crate::client::Client; + use crate::config::Target; #[test] fn default_output_names() { @@ -416,6 +478,132 @@ mod tests { default_out("https://x.com/buying/?a=1"), PathBuf::from("snapshot-buying.png") ); + assert_eq!( + default_out("HTTPS://x.com/buying/?a=1"), + PathBuf::from("snapshot-buying.png") + ); + assert_eq!( + default_out("https://x.com?next=/buying"), + PathBuf::from("snapshot-home.png") + ); + assert_eq!(default_out("buying"), PathBuf::from("snapshot-buying.png")); + // A resolved URL's path is percent-encoded; the slug must not show it. + assert_eq!( + default_out("https://x.com/search%20results/"), + PathBuf::from("snapshot-search-results.png") + ); + assert_eq!( + default_out("https://x.com/blog/caf%C3%A9/"), + PathBuf::from("snapshot-blog-caf.png") + ); + assert_eq!( + default_out("blog/my-post"), + PathBuf::from("snapshot-blog-my-post.png") + ); + assert_eq!( + default_out("buying?a=1#frag"), + PathBuf::from("snapshot-buying.png") + ); + } + + #[test] + fn resolve_url_is_case_insensitive_for_http_schemes() -> Result<()> { + let client = Client::new( + &Target { + domain: "www.example.com".into(), + base_url: "https://www.example.com".into(), + api_key: None, + }, + 0, + false, + )?; + // Accepted in any case, printed and visited with the scheme lowercased. + assert_eq!( + resolve_url(&client, "HTTPS://example.com/a"), + "https://example.com/a" + ); + assert_eq!( + resolve_url(&client, "Http://example.com/a"), + "http://example.com/a" + ); + assert_eq!( + resolve_url(&client, "/buying"), + "https://www.example.com/buying" + ); + Ok(()) + } + + #[test] + fn path_candidates_handles_windows_pathext() { + let dir = Path::new("/bin"); + assert_eq!( + path_candidates(dir, "chrome", None), + vec![PathBuf::from("/bin/chrome")] + ); + assert_eq!( + path_candidates(dir, "chrome", Some(".EXE;; .CMD ;.BAT")), + vec![ + PathBuf::from("/bin/chrome.EXE"), + PathBuf::from("/bin/chrome.CMD"), + PathBuf::from("/bin/chrome.BAT"), + ] + ); + assert_eq!( + path_candidates(dir, "chrome", Some(";")), + vec![PathBuf::from("/bin/chrome.EXE")] + ); + assert_eq!( + path_candidates(dir, "chrome", Some(" ; ; . ")), + vec![PathBuf::from("/bin/chrome.EXE")] + ); + assert_eq!( + path_candidates(dir, "chrome.exe", Some(".EXE;.CMD")), + vec![PathBuf::from("/bin/chrome.exe")] + ); + } + + #[test] + fn find_on_dirs_prefers_pathext_across_path_over_earlier_extensionless_shim( + ) -> std::io::Result<()> { + let root = tempfile::tempdir()?; + let dir1 = root.path().join("dir1"); + let dir2 = root.path().join("dir2"); + std::fs::create_dir(&dir1)?; + std::fs::create_dir(&dir2)?; + std::fs::write(dir1.join("chrome"), b"")?; + std::fs::write(dir2.join("chrome.EXE"), b"")?; + + let search_dirs = [dir1.clone(), dir2.clone()]; + assert_eq!( + find_on_dirs(&search_dirs, "chrome", Some(".EXE;.CMD")), + Some(dir2.join("chrome.EXE")) + ); + assert_eq!( + find_on_dirs(&search_dirs, "chrome", Some(";")), + Some(dir2.join("chrome.EXE")) + ); + assert_eq!( + find_on_dirs(std::slice::from_ref(&dir1), "chrome", Some(".EXE")), + Some(dir1.join("chrome")) + ); + assert_eq!( + find_on_dirs(&search_dirs, "chrome", None), + Some(dir1.join("chrome")) + ); + Ok(()) + } + + #[test] + fn is_no_element_found_distinguishes_missing_from_other_errors() { + let missing = anyhow::Error::new(headless_chrome::browser::tab::NoElementFound {}); + let invalid = anyhow::anyhow!("DOM Error while querying"); + assert!(is_no_element_found(&missing)); + assert!(!is_no_element_found(&invalid)); + } + + #[test] + fn mobile_conflicts_with_scale() { + assert!(Cli::try_parse_from(["geekcli", "snapshot", "--mobile", "--scale", "1"]).is_err()); } #[test] diff --git a/tests/inspect.rs b/tests/inspect.rs index a9e99b7..e1a356f 100644 --- a/tests/inspect.rs +++ b/tests/inspect.rs @@ -10,6 +10,7 @@ use serde_json::Value; const PAGE: &str = r#"

Atlanta homes

Contact us
one
two
+Logo "#; fn command(server: &Server, dir: &tempfile::TempDir) -> Command { @@ -77,3 +78,133 @@ fn inspect_returns_rendered_dom_values() { .code(1) .stderr(predicate::str::contains("assertion failed")); } + +#[test] +fn inspect_js_returns_objects_arrays_and_null_and_fails_on_exceptions() { + if find_browser(None).is_err() { + eprintln!("skipping: no Chrome installed"); + return; + } + let mut server = Server::new(); + server + .mock("GET", "/") + .with_header("content-type", "text/html") + .with_body(PAGE) + .expect_at_least(5) + .create(); + let dir = tempfile::tempdir().unwrap(); + + let obj = command(&server, &dir) + .args(["inspect", "/", "--js", "({a: 1})", "--wait", "10"]) + .assert() + .success(); + let obj: Value = serde_json::from_slice(&obj.get_output().stdout).unwrap(); + assert_eq!(obj["value"], serde_json::json!({"a": 1})); + + let arr = command(&server, &dir) + .args(["inspect", "/", "--js", "[1, 2]", "--wait", "10"]) + .assert() + .success(); + let arr: Value = serde_json::from_slice(&arr.get_output().stdout).unwrap(); + assert_eq!(arr["value"], serde_json::json!([1, 2])); + + let null = command(&server, &dir) + .args([ + "inspect", + "/", + "--js", + "document.querySelector('.missing')", + "--wait", + "10", + ]) + .assert() + .success(); + let null: Value = serde_json::from_slice(&null.get_output().stdout).unwrap(); + assert_eq!(null["value"], Value::Null); + + command(&server, &dir) + .args(["inspect", "/", "--assert", "throw true", "--wait", "10"]) + .assert() + .code(1) + .stderr( + predicate::str::contains("JavaScript error") + .and(predicate::str::contains("assertion failed").not()), + ); + + command(&server, &dir) + .args(["inspect", "/", "--count", "div[", "--wait", "10"]) + .assert() + .code(1) + // Same wording as --exists/--visible/--text for a bad selector. + .stderr( + predicate::str::contains("browser query failed") + .and(predicate::str::contains("JavaScript error").not()), + ); +} + +#[test] +fn inspect_text_reads_svg_elements_without_panicking() { + if find_browser(None).is_err() { + eprintln!("skipping: no Chrome installed"); + return; + } + let mut server = Server::new(); + server + .mock("GET", "/") + .with_header("content-type", "text/html") + .with_body(PAGE) + .expect_at_least(1) + .create(); + let dir = tempfile::tempdir().unwrap(); + + let svg = command(&server, &dir) + .args(["inspect", "/", "--text", "svg", "--wait", "10"]) + .assert() + .success(); + let svg: Value = serde_json::from_slice(&svg.get_output().stdout).unwrap(); + assert_eq!(svg["value"], "Logo"); +} + +#[test] +fn inspect_exists_and_visible_fail_on_invalid_selectors() { + if find_browser(None).is_err() { + eprintln!("skipping: no Chrome installed"); + return; + } + let mut server = Server::new(); + server + .mock("GET", "/") + .with_header("content-type", "text/html") + .with_body(PAGE) + .expect_at_least(4) + .create(); + let dir = tempfile::tempdir().unwrap(); + + let missing_exists = command(&server, &dir) + .args(["inspect", "/", "--exists", ".missing", "--wait", "10"]) + .assert() + .success(); + let missing_exists: Value = + serde_json::from_slice(&missing_exists.get_output().stdout).unwrap(); + assert_eq!(missing_exists["value"], false); + + let missing_visible = command(&server, &dir) + .args(["inspect", "/", "--visible", ".missing", "--wait", "10"]) + .assert() + .success(); + let missing_visible: Value = + serde_json::from_slice(&missing_visible.get_output().stdout).unwrap(); + assert_eq!(missing_visible["value"], false); + + command(&server, &dir) + .args(["inspect", "/", "--exists", "div[", "--wait", "10"]) + .assert() + .code(1) + .stderr(predicate::str::contains("browser query failed")); + + command(&server, &dir) + .args(["inspect", "/", "--visible", "div[", "--wait", "10"]) + .assert() + .code(1) + .stderr(predicate::str::contains("browser query failed")); +} diff --git a/tests/snapshot.rs b/tests/snapshot.rs index 73fb04a..1138c86 100644 --- a/tests/snapshot.rs +++ b/tests/snapshot.rs @@ -120,3 +120,79 @@ fn missing_browser_is_a_clear_error() { .code(3) .stderr(predicate::str::contains("browser not found")); } + +#[test] +fn invalid_selector_reports_browser_error_instead_of_no_match() { + if find_browser(None).is_err() { + eprintln!("skipping: no Chrome installed"); + return; + } + let mut server = Server::new(); + server + .mock("GET", "/") + .with_header("content-type", "text/html") + .with_body(PAGE) + .expect_at_least(1) + .create(); + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("bad.png"); + let mut cmd = Command::cargo_bin("geekcli").unwrap(); + cmd.env_clear() + .env( + "SYSTEMROOT", + std::env::var("SYSTEMROOT").unwrap_or_default(), + ) + .env("PATH", std::env::var("PATH").unwrap_or_default()) + .env("HOME", std::env::var("HOME").unwrap_or_default()) + .env("GEEKCLI_SITE", "www.test.local") + .env("GEEKCLI_BASE_URL", server.url()) + .env("GEEKCLI_CONFIG_DIR", dir.path()) + .args([ + "snapshot", + "/", + "--selector", + "div[", + "--wait", + "10", + "--out", + ]) + .arg(&out) + .assert() + .code(1) + .stderr( + predicate::str::contains("browser query failed") + .and(predicate::str::contains("no element matches selector").not()), + ); +} + +#[test] +fn bare_relative_target_writes_matching_default_output_file() { + if find_browser(None).is_err() { + eprintln!("skipping: no Chrome installed"); + return; + } + let mut server = Server::new(); + server + .mock("GET", "/buying") + .with_header("content-type", "text/html") + .with_body(PAGE) + .expect_at_least(1) + .create(); + let dir = tempfile::tempdir().unwrap(); + let mut cmd = Command::cargo_bin("geekcli").unwrap(); + cmd.current_dir(dir.path()) + .env_clear() + .env( + "SYSTEMROOT", + std::env::var("SYSTEMROOT").unwrap_or_default(), + ) + .env("PATH", std::env::var("PATH").unwrap_or_default()) + .env("HOME", std::env::var("HOME").unwrap_or_default()) + .env("GEEKCLI_SITE", "www.test.local") + .env("GEEKCLI_BASE_URL", server.url()) + .env("GEEKCLI_CONFIG_DIR", dir.path()) + .args(["snapshot", "buying", "--wait", "10"]) + .assert() + .success(); + assert!(dir.path().join("snapshot-buying.png").is_file()); +}