From d3716719f40a6cc8ae0614065e519294594fbfc2 Mon Sep 17 00:00:00 2001 From: Dominic Fahey Date: Wed, 25 Nov 2026 08:54:11 -0500 Subject: [PATCH 1/3] fix(search): parse criteria with & in values and pasted URLs without a scheme MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - a single key=value keeps `&` in its value (`subdivision=Town & Country`); only a stray `&` at either end is dropped - `www.example.com?city=Miami` and `example.com/search/?…` parse as URLs instead of producing a key like `www.example.com?city` - empty keys (`=Miami`, `?=Miami&…`) and URLs with no query string are usage errors instead of being dropped or accepted Applies to `search check|run|url` and pages' `--search-criteria`. Co-Authored-By: Claude Opus 5.5 --- src/commands/search.rs | 251 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 238 insertions(+), 13 deletions(-) diff --git a/src/commands/search.rs b/src/commands/search.rs index 70997b6..afd117f 100644 --- a/src/commands/search.rs +++ b/src/commands/search.rs @@ -195,6 +195,30 @@ pub fn run(ctx: &Context, cmd: SearchCommand) -> Result<()> { // ---------------------------------------------------------------- criteria +/// Whether `prefix` looks like a bare `host` or `host:port` (domain with a dot, +/// `localhost`, or an IPv4/IPv6 literal) with no path, query, fragment, or userinfo. +fn looks_like_host(prefix: &str) -> bool { + let Ok(url) = url::Url::parse(&format!("https://{prefix}")) else { + return false; + }; + if !url.username().is_empty() + || url.password().is_some() + || url.path() != "/" + || url.query().is_some() + || url.fragment().is_some() + { + return false; + } + match url.host() { + Some(url::Host::Ipv4(_) | url::Host::Ipv6(_)) => true, + Some(url::Host::Domain(d)) => { + d.eq_ignore_ascii_case("localhost") + || (d.contains('.') && d.split('.').all(|label| !label.is_empty())) + } + None => false, + } +} + /// Turn CLI items into a query. Accepts `key=value` items and, as a /// convenience, a whole query string or URL copied from the site. pub fn parse_criteria(items: &[String]) -> Result { @@ -204,30 +228,71 @@ pub fn parse_criteria(items: &[String]) -> Result { if item.is_empty() { continue; } - let looks_like_url = item.starts_with('?') - || item.starts_with("http://") - || item.starts_with("https://") - || (item.starts_with('/') && item.contains('?')) - || (item.contains('&') && item.contains('=')); - if looks_like_url { - let qs = match item.find('?') { - Some(idx) => &item[idx + 1..], - None => item, + let before_frag = item.split('#').next().unwrap_or_default(); + let starts_with_scheme = item + .get(..7) + .is_some_and(|p| p.eq_ignore_ascii_case("http://")) + || item + .get(..8) + .is_some_and(|p| p.eq_ignore_ascii_case("https://")); + let bare_parts: Vec<&str> = before_frag.split('&').filter(|s| !s.is_empty()).collect(); + let is_bare_query = !starts_with_scheme + && bare_parts.len() >= 2 + && bare_parts.iter().all(|s| { + s.split_once('=') + .is_some_and(|(k, _)| !k.is_empty() && !k.chars().any(char::is_whitespace)) + }); + let schemeless_url_qs = if starts_with_scheme { + None + } else { + before_frag.split_once('?').and_then(|(prefix, rest)| { + let is_url_prefix = prefix.is_empty() + || prefix.starts_with('/') + || (!prefix.contains('=') + && !prefix.chars().any(char::is_whitespace) + && (prefix.contains('/') || looks_like_host(prefix))); + is_url_prefix.then_some(rest) + }) + }; + let qs = if starts_with_scheme { + let Some((_, qs)) = before_frag.split_once('?') else { + return Err(Error::Usage(format!( + "URL '{item}' has no query string criteria" + ))); }; - let qs = qs.split('#').next().unwrap_or_default(); + Some(qs) + } else if let Some(rest) = schemeless_url_qs { + Some(rest) + } else if is_bare_query { + Some(before_frag) + } else { + None + }; + if let Some(qs) = qs { for (k, v) in url::form_urlencoded::parse(qs.as_bytes()) { - if !k.is_empty() { - query.push((k.to_string(), v.to_string())); + if k.is_empty() { + return Err(Error::Usage(format!( + "'{item}' has a criterion with an empty key (`={v}`); every value needs a field name" + ))); } + query.push((k.to_string(), v.to_string())); } continue; } + // one pair with a stray `&` copied along (`city=Miami&`, `&city=Miami`) + let item = item.trim_matches('&').trim(); let Some((k, v)) = item.split_once('=') else { return Err(Error::Usage(format!( "expected key=value, got '{item}' (run `geekcli search fields` for the field names)" ))); }; - query.push((k.trim().to_string(), v.trim().to_string())); + let k = k.trim(); + if k.is_empty() { + return Err(Error::Usage(format!( + "expected key=value with a non-empty key, got '{item}' (run `geekcli search fields` for the field names)" + ))); + } + query.push((k.to_string(), v.trim().to_string())); } if query.is_empty() { return Err(Error::Usage("no criteria given".into())); @@ -1516,4 +1581,164 @@ mod tests { assert!(!is_numeric_list(&list(&["all"]))); assert!(!is_numeric_list(&list(&["Miami", "33458"]))); } + #[test] + fn parse_criteria_preserves_ampersand_in_values() { + let q = parse_criteria(&["subdivision=Town & Country".into()]).unwrap_or_default(); + assert_eq!( + q, + vec![("subdivision".to_string(), "Town & Country".to_string())] + ); + let q = parse_criteria(&["features=55+ & Pool".into()]).unwrap_or_default(); + assert_eq!(q, vec![("features".to_string(), "55+ & Pool".to_string())]); + let q = parse_criteria(&["city=Miami&type=res".into()]).unwrap_or_default(); + assert_eq!( + q, + vec![ + ("city".to_string(), "Miami".to_string()), + ("type".to_string(), "res".to_string()) + ] + ); + let q = + parse_criteria(&["HTTPS://www.example.com/search/results/?city=Miami&type=res".into()]) + .unwrap_or_default(); + assert_eq!( + q, + vec![ + ("city".to_string(), "Miami".to_string()), + ("type".to_string(), "res".to_string()) + ] + ); + } + + #[test] + fn parse_criteria_rejects_urls_without_query_string() { + for bad in [ + "https://www.example.com/search/results/a/", + "HTTP://www.example.com/search/results/a/", + "https://www.example.com/search/results/a/#?fake=1", + ] { + assert!( + matches!(parse_criteria(&[bad.into()]), Err(Error::Usage(_))), + "expected usage error for {bad:?}" + ); + } + } + + #[test] + fn parse_criteria_rejects_empty_keys() { + for bad in [ + "=Miami", + "=", + " =Miami", + // inside a pasted URL or query string too, not silently dropped + "?=Miami&city=X", + "https://www.example.com/search/results/?=Miami&city=X", + ] { + assert!( + matches!(parse_criteria(&[bad.into()]), Err(Error::Usage(_))), + "expected usage error for {bad:?}" + ); + } + } + + #[test] + fn parse_criteria_handles_schemeless_urls_and_preserves_question_marks_in_values() { + let q = parse_criteria(&["www.example.com/search/results/?city=Miami&type=res".into()]) + .unwrap_or_default(); + assert_eq!( + q, + vec![ + ("city".to_string(), "Miami".to_string()), + ("type".to_string(), "res".to_string()), + ] + ); + let q = parse_criteria(&["www.example.com/search/results/?city=Miami".into()]) + .unwrap_or_default(); + assert_eq!(q, vec![("city".to_string(), "Miami".to_string())]); + let q = parse_criteria(&["www.example.com/search/results/?city=Key+Biscayne#top".into()]) + .unwrap_or_default(); + assert_eq!(q, vec![("city".to_string(), "Key Biscayne".to_string())]); + let q = parse_criteria(&["note=what?".into()]).unwrap_or_default(); + assert_eq!(q, vec![("note".to_string(), "what?".to_string())]); + let q = parse_criteria(&["url=https://a.com/x?y=1".into()]).unwrap_or_default(); + assert_eq!( + q, + vec![("url".to_string(), "https://a.com/x?y=1".to_string())] + ); + } + + #[test] + fn parse_criteria_handles_pathless_schemeless_urls_and_negatives() { + let q = parse_criteria(&["www.example.com?city=Miami&type=res".into()]).unwrap_or_default(); + assert_eq!( + q, + vec![ + ("city".to_string(), "Miami".to_string()), + ("type".to_string(), "res".to_string()), + ] + ); + let q = parse_criteria(&["www.example.com?city=Miami".into()]).unwrap_or_default(); + assert_eq!(q, vec![("city".to_string(), "Miami".to_string())]); + let q = + parse_criteria(&["example.com:8080?city=Key+Biscayne#top".into()]).unwrap_or_default(); + assert_eq!(q, vec![("city".to_string(), "Key Biscayne".to_string())]); + let q = parse_criteria(&["localhost:8000?city=Miami".into()]).unwrap_or_default(); + assert_eq!(q, vec![("city".to_string(), "Miami".to_string())]); + let q = parse_criteria(&["127.0.0.1:8000?city=Miami".into()]).unwrap_or_default(); + assert_eq!(q, vec![("city".to_string(), "Miami".to_string())]); + let q = parse_criteria(&["[::1]:8000?city=Miami".into()]).unwrap_or_default(); + assert_eq!(q, vec![("city".to_string(), "Miami".to_string())]); + + // Preservation / negative cases + let q = parse_criteria(&["note=what?".into()]).unwrap_or_default(); + assert_eq!(q, vec![("note".to_string(), "what?".to_string())]); + let q = parse_criteria(&["url=https://a.com/x?y=1".into()]).unwrap_or_default(); + assert_eq!( + q, + vec![("url".to_string(), "https://a.com/x?y=1".to_string())] + ); + let q = parse_criteria(&["subdivision=Town & Country".into()]).unwrap_or_default(); + assert_eq!( + q, + vec![("subdivision".to_string(), "Town & Country".to_string())] + ); + let q = parse_criteria(&["foo?bar=1".into()]).unwrap_or_default(); + assert_eq!(q, vec![("foo?bar".to_string(), "1".to_string())]); + + // Empty query string after `?` on a host-only prefix yields Usage("no criteria given") + assert!(matches!( + parse_criteria(&["www.example.com?".into()]), + Err(Error::Usage(ref msg)) if msg == "no criteria given" + )); + } + + #[test] + fn parse_criteria_handles_fragments_and_trailing_ampersand() { + let q = parse_criteria(&["city=Miami&type=res#a&b".into()]).unwrap_or_default(); + assert_eq!( + q, + vec![ + ("city".to_string(), "Miami".to_string()), + ("type".to_string(), "res".to_string()), + ] + ); + let q = parse_criteria(&["address=Suite #1&b=2".into()]).unwrap_or_default(); + assert_eq!(q, vec![("address".to_string(), "Suite #1&b=2".to_string())]); + // A stray leading/trailing `&` on one pair is dropped; the value + // stays literal (`+` is not decoded to a space). + let q = parse_criteria(&["features=55+&".into()]).unwrap_or_default(); + assert_eq!(q, vec![("features".to_string(), "55+".to_string())]); + let q = parse_criteria(&["city=Miami&".into()]).unwrap_or_default(); + assert_eq!(q, vec![("city".to_string(), "Miami".to_string())]); + let q = parse_criteria(&["&city=Miami".into()]).unwrap_or_default(); + assert_eq!(q, vec![("city".to_string(), "Miami".to_string())]); + let q = parse_criteria(&["city=Miami&type=res&".into()]).unwrap_or_default(); + assert_eq!( + q, + vec![ + ("city".to_string(), "Miami".to_string()), + ("type".to_string(), "res".to_string()), + ] + ); + } } From b5527dc10207551147936f270e292fd4edf18c20 Mon Sep 17 00:00:00 2001 From: Dominic Fahey Date: Wed, 25 Nov 2026 08:57:18 -0500 Subject: [PATCH 2/3] fix(search): check zip values and never report a value check that did not happen - zip codes are checked against the site's values; other numeric fields (min/max ranges, price and beds presets, numeric multiselects, non-zip numeric autocomplete values) are still skipped as presets - fixed catalog lists (fields not marked `dynamic`) are taken as complete, so the autocomplete index is not fetched for them - if the autocomplete index cannot be read, the field is left unchecked (`value_check_error`; `--strict` exits 1) rather than warning from a partial list - a field given only `all` is not listed in `values_checked` Co-Authored-By: Claude Opus 5.5 --- src/commands/search.rs | 73 +++++-- tests/search.rs | 457 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 516 insertions(+), 14 deletions(-) diff --git a/src/commands/search.rs b/src/commands/search.rs index afd117f..a67c3d4 100644 --- a/src/commands/search.rs +++ b/src/commands/search.rs @@ -902,7 +902,13 @@ pub const AUTOCOMPLETE_PATH: &str = "api/v2/search/autocomplete-options/"; /// all cities, unlike the advanced form's choice list that follows the /// default county. fn autocomplete_index(ctx: &Context) -> Result { - Ok(ctx.client.site_get(AUTOCOMPLETE_PATH, &Query::new())?.body) + let body = ctx.client.site_get(AUTOCOMPLETE_PATH, &Query::new())?.body; + if !body.is_array() { + return Err(Error::Other( + "the autocomplete index response was not a JSON array".into(), + )); + } + Ok(body) } /// Sorted, de-duplicated values for one field from the autocomplete index. @@ -1007,15 +1013,15 @@ fn closest(value: &str, candidates: &[String], limit: usize) -> Vec { // ------------------------------------------------------------------- check -/// A choice list made only of numbers (prices, beds, square feet) is a set -/// of presets, not the only values the search takes. +/// A choice list made only of finite numbers (prices, beds, square feet) is a +/// set of presets, not the only values the search takes. fn is_numeric_list(values: &[String]) -> bool { let mut any = false; for v in values { if v.is_empty() || v.eq_ignore_ascii_case("all") { continue; } - if v.replace(',', "").parse::().is_err() { + if !v.replace(',', "").parse::().is_ok_and(f64::is_finite) { return false; } any = true; @@ -1023,6 +1029,30 @@ fn is_numeric_list(values: &[String]) -> bool { any } +/// Whether `field` is a postal/ZIP code field whose numeric values are discrete +/// codes rather than numeric range presets. +fn is_zip_field(field: &str) -> bool { + matches!(field, "zip" | "zipcode" | "zip_code" | "postal_code") +} + +/// Whether a field is a numeric range/preset field (e.g. `min_max_field`, +/// `list_price_min`, `beds_min`) rather than a discrete code list like `zip`. +fn is_numeric_preset(field: &str, rows: &[&Value], static_candidates: &[String]) -> bool { + let is_min_max = rows.iter().any(|r| { + r.get("widget").and_then(Value::as_str) == Some("min_max_field") + || r.get("flags") + .and_then(Value::as_array) + .is_some_and(|f| f.iter().any(|v| v.as_str() == Some("min_max_field"))) + }); + if is_min_max || field.ends_with("_min") || field.ends_with("_max") { + return true; + } + if is_zip_field(field) { + return false; + } + is_numeric_list(static_candidates) +} + /// Result of comparing criteria values with the site's choices. #[derive(Default)] struct ValueCheck { @@ -1067,6 +1097,7 @@ fn check_values(ctx: &Context, query: &Query, ignored: &[String]) -> ValueCheck } }; let mut index: Option = None; + let mut autocomplete_failed = false; for (field, values) in by_field { let rows = field_rows(&fields.rows, &field); // the site takes true/1/yes for yes-no fields, not just the listed values @@ -1080,33 +1111,42 @@ fn check_values(ctx: &Context, query: &Query, ignored: &[String]) -> ValueCheck .iter() .map(|c| cell(&c["value"])) .collect(); + if is_numeric_preset(&field, &rows, &candidates) { + continue; + } // the form submits `all` for "no preference" on any listed field - let values: Vec = if candidates.is_empty() { - values - } else { - values.into_iter().filter(|v| v != "all").collect() - }; - if is_numeric_list(&candidates) { + let values: Vec = values.into_iter().filter(|v| v != "all").collect(); + if values.is_empty() { + // nothing to compare, so the field was not checked continue; } - let settled = !candidates.is_empty() && values.iter().all(|v| candidates.contains(v)); + let static_catalog_complete = fields.source == FieldSource::Catalog + && !candidates.is_empty() + && rows + .iter() + .all(|r| r.get("dynamic").and_then(Value::as_bool) != Some(true)); + let settled = static_catalog_complete + || (!candidates.is_empty() && values.iter().all(|v| candidates.contains(v))); if !settled { - if index.is_none() { + if index.is_none() && !autocomplete_failed { match autocomplete_index(ctx) { Ok(body) => index = Some(body), Err(e) => { result.error = Some(format!("could not read the autocomplete index: {e}")); - index = Some(Value::Null); + autocomplete_failed = true; } } } + if autocomplete_failed { + continue; + } if let Some(body) = &index { candidates.extend(autocomplete_values(body, &field)); } } candidates.sort(); candidates.dedup(); - if candidates.is_empty() || is_numeric_list(&candidates) { + if candidates.is_empty() || (!is_zip_field(&field) && is_numeric_list(&candidates)) { continue; } for value in &values { @@ -1580,7 +1620,12 @@ mod tests { assert!(is_numeric_list(&list(&["all", "100000", "1,000,000"]))); assert!(!is_numeric_list(&list(&["all"]))); assert!(!is_numeric_list(&list(&["Miami", "33458"]))); + assert!(!is_numeric_list(&list(&["NaN"]))); + assert!(!is_numeric_list(&list(&["inf"]))); + assert!(!is_numeric_list(&list(&["-infinity"]))); + assert!(!is_numeric_list(&list(&["100", "NaN"]))); } + #[test] fn parse_criteria_preserves_ampersand_in_values() { let q = parse_criteria(&["subdivision=Town & Country".into()]).unwrap_or_default(); diff --git a/tests/search.rs b/tests/search.rs index e9ddee5..056aaf7 100644 --- a/tests/search.rs +++ b/tests/search.rs @@ -928,3 +928,460 @@ fn check_validates_values_against_the_catalog() { serde_json::json!(["city", "type", "subdivision"]) ); } + +#[test] +fn check_validates_zip_from_autocomplete_and_keeps_numeric_presets() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + let catalog = r#"[ +{"id":"zip","label":"Zip","widget":"multiselect","flags":["dynamic"],"choices":[]}, +{"id":"list_price","label":"Price","widget":"min_max_field","flags":["min_max_field"],"choices":[{"label":"$1,000,000","val":1000000}]}, +{"id":"beds","label":"Beds","widget":"min_max_field","flags":["min_max_field"],"choices":[{"label":"2","val":2},{"label":"3","val":3}]} +]"#; + let index_body = r#"[{"field":"zip","value":"33131"},{"field":"zip","value":"02138"}]"#; + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body(catalog) + .create(); + server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_body(index_body) + .create(); + + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::UrlEncoded("zip".into(), "99999".into())) + .with_body(r#"{"description":"d","criteria":{"zip":["99999"]}}"#) + .create(); + let assert = cmd(&server, &dir) + .args(["search", "check", "zip=99999", "--strict"]) + .assert() + .code(5); + let doc = parse(&assert.get_output().stdout); + assert_eq!(doc["values_checked"], serde_json::json!(["zip"])); + let warnings = doc["value_warnings"].as_array().unwrap(); + assert_eq!(warnings.len(), 1, "{doc}"); + assert_eq!(warnings[0]["field"], "zip"); + assert_eq!(warnings[0]["kind"], "unknown_value"); + let suggestions = warnings[0]["suggestions"].as_array().unwrap(); + assert!( + suggestions.contains(&serde_json::json!("33131")) + && suggestions.contains(&serde_json::json!("02138")), + "{doc}" + ); + let err: Value = serde_json::from_slice(&assert.get_output().stderr).unwrap(); + assert_eq!(err["error"]["code"], "value_mismatch"); + + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("list_price_min".into(), "250000".into()), + Matcher::UrlEncoded("beds_min".into(), "3".into()), + Matcher::UrlEncoded("zip".into(), "33131".into()), + ])) + .with_body( + r#"{"description":"d","criteria":{"list_price_min":["250000"],"beds_min":["3"],"zip":["33131"]}}"#, + ) + .create(); + let out = cmd(&server, &dir) + .args([ + "search", + "check", + "list_price_min=250000", + "beds_min=3", + "zip=33131", + "--strict", + ]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let doc = parse(&out); + assert_eq!(doc["values_checked"], serde_json::json!(["zip"])); + assert_eq!(doc["value_warnings"], serde_json::json!([])); +} + +#[test] +fn check_validates_zip_with_static_form_choices() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_status(404) + .create(); + server + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body( + r#"{"primary":[{"attr":"zip","label":"Zip","widget_type":"select","choices":[["33131","33131"],["02138","02138"]]}],"secondary":[]}"#, + ) + .create(); + server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_body("[]") + .create(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"zip":["99999"]}}"#) + .create(); + let assert = cmd(&server, &dir) + .args(["search", "check", "zip=99999", "--strict"]) + .assert() + .code(5); + let err: Value = serde_json::from_slice(&assert.get_output().stderr).unwrap(); + assert_eq!(err["error"]["code"], "value_mismatch"); +} + +#[test] +fn check_strict_exits_1_when_autocomplete_fails_on_unsettled_field() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"city":["Mclean"]}}"#) + .create(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_status(404) + .create(); + server + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body(FORM) + .create(); + server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_status(500) + .create(); + + let assert = cmd(&server, &dir) + .args(["search", "check", "city=Mclean", "--strict"]) + .assert() + .code(1); + let doc = parse(&assert.get_output().stdout); + assert_eq!(doc["value_warnings"], serde_json::json!([])); + assert_eq!(doc["values_checked"], serde_json::json!([])); + let err: Value = serde_json::from_slice(&assert.get_output().stderr).unwrap(); + assert_eq!(err["error"]["code"], "value_check_unavailable"); + + let assert = cmd(&server, &dir) + .args(["search", "check", "city=Mclean"]) + .assert() + .success() + .stderr(predicate::str::contains("values not checked")); + let doc = parse(&assert.get_output().stdout); + assert_eq!(doc["value_warnings"], serde_json::json!([])); +} + +#[test] +fn check_skips_empty_min_max_catalog_field_without_fetching_autocomplete() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"beds_min":["3"]}}"#) + .create(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body( + r#"[{"id":"beds","label":"Beds","widget":"min_max_field","flags":["min_max_field"],"choices":[]}]"#, + ) + .create(); + let index = server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_status(500) + .expect(0) + .create(); + + let out = cmd(&server, &dir) + .args(["search", "check", "beds_min=3", "--strict"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + index.assert(); + let doc = parse(&out); + assert_eq!(doc["value_warnings"], serde_json::json!([])); +} + +#[test] +fn check_allows_all_on_dynamic_catalog_field_without_fetching_autocomplete() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"city":["all"]}}"#) + .create(); + mock_catalog(&mut server); + let index = server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_status(500) + .expect(0) + .create(); + + let out = cmd(&server, &dir) + .args(["search", "check", "city=all", "--strict"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + index.assert(); + let doc = parse(&out); + assert_eq!(doc["value_warnings"], serde_json::json!([])); +} + +#[test] +fn check_does_not_list_a_field_as_checked_when_its_only_value_is_all() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"type":["all"]}}"#) + .create(); + mock_catalog(&mut server); + + let out = cmd(&server, &dir) + .args(["search", "check", "type=all"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let doc = parse(&out); + // `all` means "no preference": nothing was compared + assert_eq!(doc["values_checked"], serde_json::json!([]), "{doc}"); +} + +#[test] +fn check_does_not_emit_partial_warnings_when_autocomplete_fails() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"city":["McLean"]}}"#) + .create(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_status(404) + .create(); + server + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body( + r#"{"primary":[{"attr":"city","label":"City","widget_type":"multiselect","choices":[["all","All"],["Mclean","Mclean"],["Miami","Miami"]]}],"secondary":[]}"#, + ) + .create(); + server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_status(500) + .create(); + + let assert = cmd(&server, &dir) + .args(["search", "check", "city=McLean"]) + .assert() + .success() + .stderr(predicate::str::contains("values not checked")); + let doc = parse(&assert.get_output().stdout); + assert_eq!(doc["values_checked"], serde_json::json!([])); + assert_eq!(doc["value_warnings"], serde_json::json!([])); + assert!(doc["value_check_error"].is_string(), "{doc}"); + + let assert = cmd(&server, &dir) + .args(["search", "check", "city=McLean", "--strict"]) + .assert() + .code(1); + let err: Value = serde_json::from_slice(&assert.get_output().stderr).unwrap(); + assert_eq!(err["error"]["code"], "value_check_unavailable"); + + let mut server2 = Server::new(); + server2 + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"type":["RES"],"city":["McLean"]}}"#) + .create(); + server2 + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body(CATALOG) + .create(); + server2 + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_status(500) + .create(); + + let assert = cmd(&server2, &dir) + .args(["search", "check", "type=RES", "city=McLean"]) + .assert() + .success() + .stderr(predicate::str::contains("values not checked")); + let doc = parse(&assert.get_output().stdout); + assert_eq!(doc["values_checked"], serde_json::json!(["type"])); + let warnings = doc["value_warnings"].as_array().unwrap(); + assert_eq!(warnings.len(), 1, "{doc}"); + assert_eq!(warnings[0]["field"], "type"); + assert_eq!(warnings[0]["kind"], "case_mismatch"); + assert!(doc["value_check_error"].is_string(), "{doc}"); + + let assert = cmd(&server2, &dir) + .args(["search", "check", "type=RES", "city=McLean", "--strict"]) + .assert() + .code(5); + let err: Value = serde_json::from_slice(&assert.get_output().stderr).unwrap(); + assert_eq!(err["error"]["code"], "value_mismatch"); + let fields = err["error"]["fields"].as_object().unwrap(); + assert!(fields.contains_key("type"), "{err}"); + assert!(!fields.contains_key("city"), "{err}"); +} + +#[test] +fn check_skips_numeric_multiselect_catalog_presets() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::UrlEncoded("garage".into(), "4".into())) + .with_body(r#"{"description":"d","criteria":{"garage":["4"]}}"#) + .create(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body( + r#"[{"id":"garage","label":"Garage","widget":"multiselect","flags":[],"choices":[{"label":"1","val":1},{"label":"2","val":2},{"label":"3","val":3}]}]"#, + ) + .create(); + let index = server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_status(500) + .expect(0) + .create(); + + let out = cmd(&server, &dir) + .args(["search", "check", "garage=4", "--strict"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + index.assert(); + let doc = parse(&out); + assert_eq!(doc["values_checked"], serde_json::json!([])); + assert_eq!(doc["value_warnings"], serde_json::json!([])); +} + +#[test] +fn check_skips_non_zip_numeric_autocomplete_fields() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::UrlEncoded("mls_number".into(), "999999".into())) + .with_body(r#"{"description":"d","criteria":{"mls_number":["999999"]}}"#) + .create(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body( + r#"[{"id":"mls_number","label":"MLS #","widget":"text","flags":[],"choices":[]}]"#, + ) + .create(); + server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_body( + r#"[{"field":"mls_number","value":"100001"},{"field":"mls_number","value":"100002"}]"#, + ) + .create(); + + let out = cmd(&server, &dir) + .args(["search", "check", "mls_number=999999", "--strict"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let doc = parse(&out); + assert_eq!(doc["values_checked"], serde_json::json!([])); + assert_eq!(doc["value_warnings"], serde_json::json!([])); +} + +#[test] +fn check_skips_min_max_suffix_fields_without_static_choices() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::UrlEncoded("beds_min".into(), "3".into())) + .with_body(r#"{"description":"d","criteria":{"beds_min":["3"]}}"#) + .create(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_status(404) + .create(); + server + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body(FORM) + .create(); + let index = server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_status(500) + .expect(0) + .create(); + + let out = cmd(&server, &dir) + .args(["search", "check", "beds_min=3", "--strict"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + index.assert(); + let doc = parse(&out); + assert_eq!(doc["values_checked"], serde_json::json!([])); + assert_eq!(doc["value_warnings"], serde_json::json!([])); +} + +#[test] +fn check_validates_static_catalog_field_without_hitting_autocomplete() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"type":["RES"]}}"#) + .create(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body(CATALOG) + .create(); + let index = server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_status(500) + .expect(0) + .create(); + + let out = cmd(&server, &dir) + .args(["search", "check", "type=RES"]) + .assert() + .success() + .stderr(predicate::str::contains("`res`")) + .get_output() + .stdout + .clone(); + let doc = parse(&out); + assert_eq!(doc["values_checked"], serde_json::json!(["type"])); + let warnings = doc["value_warnings"].as_array().unwrap(); + assert_eq!(warnings.len(), 1, "{doc}"); + assert_eq!(warnings[0]["field"], "type"); + assert_eq!(warnings[0]["kind"], "case_mismatch"); + assert_eq!(warnings[0]["suggestions"], serde_json::json!(["res"])); + + let assert = cmd(&server, &dir) + .args(["search", "check", "type=RES", "--strict"]) + .assert() + .code(5); + let err: Value = serde_json::from_slice(&assert.get_output().stderr).unwrap(); + assert_eq!(err["error"]["code"], "value_mismatch"); + index.assert(); +} From 2f8e0bbe8b215acfc769d484cb92838a8ea6c010 Mon Sep 17 00:00:00 2001 From: Dominic Fahey Date: Wed, 25 Nov 2026 08:58:31 -0500 Subject: [PATCH 3/3] fix(search): guard search url --save, fix run/choices output, document the changes - `search url --save` refuses to save when the site ignored a criterion (the saved search would filter nothing) and fails if the site returns no `search_id` - `search run` table footer shows the real page count ("of at least N" when the total is capped; no bogus count for --per-page 0) - checkbox labels are kept when form rows merge, range choices are de-duplicated, `search choices polygon --all` is rejected up front, a form answered with HTML is reported as such, and filters in `search choices` / `search-forms fields` lowercase Unicode text - GUIDE: criteria parsing, --save, zip checks, fixed catalog lists and failed-autocomplete behaviour Co-Authored-By: Claude Opus 5.5 --- docs/GUIDE.md | 25 +- src/commands/search.rs | 132 +++++++--- src/commands/search_forms.rs | 8 +- tests/search.rs | 455 +++++++++++++++++++++++++++++++++++ tests/search_forms.rs | 52 ++++ 5 files changed, 622 insertions(+), 50 deletions(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index e6ba68c..3c75608 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -599,9 +599,15 @@ not show) prints nothing and a note on stderr pointing at `--all`. Criteria are `key=value` items; repeat a key for several values (`type=res type=con`). A whole query string or URL copied from the site is -accepted as one item. `--save` stores the search on the site and returns -its short id, which is what `/search/results//`, the map search and a -page's `search_id` refer to. +accepted as one item, with or without `https://` (`www.example.com?city=Miami` +works); a URL with no query string, or a criterion with an empty key +(`=Miami`), is a usage error. A single `key=value` keeps `&` and `+` in its +value as typed; only a stray `&` at either end is dropped. `--save` stores +the search on the site and returns its short id, which is what +`/search/results//`, the map search and a page's `search_id` refer to. +It refuses to save (exit 5) when the site ignored a criterion, since the +saved search would filter nothing for it, and fails if the site's answer +has no `search_id`. `search check` also compares each value with the field's choices, for fields that have a choice list (city, county, subdivision, zip, type …; @@ -609,7 +615,8 @@ price, beds and other numeric fields are skipped). Values are case sensitive on the site: `city=McLean` is understood but matches nothing when the site stores `Mclean`. The result carries: -- `values_checked`: the fields whose values were compared. +- `values_checked`: the fields whose values were compared (a field given + only `all`, "no preference", is not listed). - `value_warnings`: one entry per bad value, `{field, value, kind, suggestions, message}`. `kind` is `case_mismatch` (the suggestion is the site's spelling) or `unknown_value` (up to 3 closest values by edit @@ -624,9 +631,13 @@ site's choice lists cannot be read, values go unchecked (reported in `value_check_error`); `--strict` then exits 1 (`value_check_unavailable`) rather than pass a check it could not make. The field's list in the catalog (the form's on sites without one; reported in -`choices_source`) is tried first and the site's autocomplete index (every -county) only when that does not settle it, so a value valid in another -county is not flagged. Yes-no fields (`pool=true`, `1` or `yes`) are not +`choices_source`) is tried first. A fixed catalog list (one not marked +`dynamic`, such as `type`) is the whole answer. For other fields the +site's autocomplete index (every county) is read when the list does not +settle it, so a value valid in another county is not flagged. If that +index cannot be read, the field is left unchecked, with no partial +warnings, and lands in `value_check_error`. ZIP codes are checked like +names; other numeric lists (prices, beds, presets) are not. Yes-no fields (`pool=true`, `1` or `yes`) are not value-checked. A clean check without `--count` still does not prove the page will show listings; use `--count` or `search run`. diff --git a/src/commands/search.rs b/src/commands/search.rs index a67c3d4..6891131 100644 --- a/src/commands/search.rs +++ b/src/commands/search.rs @@ -7,7 +7,7 @@ //! commands make that visible: every criterion you pass is checked against //! what the site echoes back, and anything ignored is reported. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashSet}; use clap::{Args, Subcommand}; use serde_json::{json, Map, Value}; @@ -181,6 +181,11 @@ pub fn run(ctx: &Context, cmd: SearchCommand) -> Result<()> { all, fuzzy, } => { + if field == POLYGON { + return Err(Error::Usage( + "polygon has no list of values: it takes lat,lng;lat,lng;… points (see `geekcli guide polygon`)".into(), + )); + } if all { all_choices(ctx, &field, search.as_deref(), fuzzy.as_deref()) } else { @@ -607,6 +612,14 @@ impl FieldRow { fn form_fields(ctx: &Context) -> Result> { let form = ctx.client.site_get(FORM_PATH, &Query::new())?.body; + let valid = form.is_object() + && (form.get("primary").is_some_and(Value::is_array) + || form.get("secondary").is_some_and(Value::is_array)); + if !valid { + return Err(Error::Other( + "the advanced search form response did not contain primary or secondary fields".into(), + )); + } let mut rows = Vec::new(); for section in ["primary", "secondary"] { let Some(items) = form.get(section).and_then(Value::as_array) else { @@ -692,7 +705,7 @@ fn catalog_rows(body: &Value) -> Option> { .into_json(), ); } - Some(rows) + (!rows.is_empty()).then_some(rows) } fn catalog_fields(ctx: &Context) -> Result> { @@ -737,13 +750,17 @@ fn fields(ctx: &Context) -> Result<()> { let mut merged: Vec = Vec::new(); for row in rows { let attr = row.get("attr").cloned().unwrap_or(Value::Null); - if let Some(existing) = merged.iter_mut().find(|m| { - m.get("attr") == Some(&attr) && m.get("value").is_some_and(|v| !v.is_null()) - }) { - let values = format!("{}, {}", cell(&existing["value"]), cell(&row["value"])); - existing["value"] = Value::String(values); - existing["label"] = Value::String("Property type".into()); - continue; + if !attr.is_null() && row.get("value").is_some_and(|v| !v.is_null()) { + if let Some(existing) = merged.iter_mut().find(|m| { + m.get("attr") == Some(&attr) && m.get("value").is_some_and(|v| !v.is_null()) + }) { + let values = format!("{}, {}", cell(&existing["value"]), cell(&row["value"])); + existing["value"] = Value::String(values); + if attr.as_str() == Some("type") { + existing["label"] = Value::String("Property type".into()); + } + continue; + } } merged.push(row); } @@ -792,11 +809,32 @@ fn choice_rows(rows: &[&Value]) -> Vec { out } +/// Remove duplicate `{value, label}` choices while preserving order. +fn dedup_choices(choices: Vec) -> Vec { + let mut seen: HashSet<(String, String)> = HashSet::with_capacity(choices.len()); + let mut out = Vec::with_capacity(choices.len()); + for choice in choices { + let key = (choice["value"].to_string(), choice["label"].to_string()); + if seen.insert(key) { + out.push(choice); + } + } + out +} + /// The form's choices for a field, also looked up by the catalog row's /// params (the form lists `list_price_min`, the catalog `list_price`). fn form_choices_for(ctx: &Context, field: &str, catalog: &[&Value]) -> Option> { let form = form_fields(ctx).ok()?; - let mut names: Vec = vec![field.to_string()]; + let exact: Vec<&Value> = form + .iter() + .filter(|r| r.get("attr").and_then(Value::as_str) == Some(field)) + .collect(); + let exact_out = dedup_choices(choice_rows(&exact)); + if !exact_out.is_empty() { + return Some(exact_out); + } + let mut names: Vec = Vec::new(); for row in catalog { for key in ["attr", "params"] { match row.get(key) { @@ -818,7 +856,7 @@ fn form_choices_for(ctx: &Context, field: &str, catalog: &[&Value]) -> Option Option, fuzzy: Option<&str>) -> Result<()> { - if field == POLYGON { - return Err(Error::Usage( - "polygon has no list of values: it takes lat,lng;lat,lng;… points (see `geekcli guide polygon`)".into(), - )); - } let fields = load_fields(ctx, true)?; let matching = field_rows(&fields.rows, field); if matching.is_empty() { @@ -858,10 +891,10 @@ fn choices(ctx: &Context, field: &str, needle: Option<&str>, fuzzy: Option<&str> ctx.printer.note(&format!("Values from {source}.")); } if let Some(needle) = needle { - let needle = needle.to_ascii_lowercase(); + let needle = needle.to_lowercase(); out.retain(|c| { - cell(&c["value"]).to_ascii_lowercase().contains(&needle) - || cell(&c["label"]).to_ascii_lowercase().contains(&needle) + cell(&c["value"]).to_lowercase().contains(&needle) + || cell(&c["label"]).to_lowercase().contains(&needle) }); } print_choices(ctx, out, fuzzy) @@ -937,10 +970,10 @@ fn all_choices( fuzzy: Option<&str>, ) -> Result<()> { let index = autocomplete_index(ctx)?; - let needle = needle.map(str::to_ascii_lowercase); + let needle = needle.map(str::to_lowercase); let mut values = autocomplete_values(&index, field); if let Some(n) = &needle { - values.retain(|v| v.to_ascii_lowercase().contains(n)); + values.retain(|v| v.to_lowercase().contains(n)); } if values.is_empty() { return Err(not_found(format!( @@ -1413,10 +1446,18 @@ fn run_search(ctx: &Context, args: &RunArgs) -> Result<()> { .as_ref() .map(|r| format!(" (count limited by {r})")) .unwrap_or_default(); - ctx.printer.note(&format!( - "{count} matching {noun}{limit}, page {} of {} shown", - args.page, args.per_page - )); + let pages = total + .filter(|_| args.per_page > 0) + .map(|t| t.div_ceil(u64::from(args.per_page)).max(1)); + let paging = match pages { + Some(total_pages) if limited.is_some() => { + format!("page {} of {total_pages}+ shown", args.page) + } + Some(total_pages) => format!("page {} of {total_pages} shown", args.page), + None => format!("page {} ({} per page)", args.page, args.per_page), + }; + ctx.printer + .note(&format!("{count} matching {noun}{limit}, {paging}")); Ok(()) } Format::Json | Format::Jsonl => ctx.printer.raw(&json!({ @@ -1447,23 +1488,28 @@ fn url(ctx: &Context, args: &UrlArgs) -> Result<()> { "results_path": format!("/search/results/?{qs}"), "map_path": format!("/map_search/results/?{qs}"), }); + if !understood.ignored.is_empty() { + ctx.printer.raw(&doc)?; + return Err(ignored_error(&understood.ignored)); + } if args.save { let saved = ctx.client.site_post(SEARCH_PATH, &canonical)?.body; - if let Some(id) = saved.get("search_id").and_then(Value::as_str) { - doc["search_id"] = Value::String(id.to_string()); - doc["search_id_int"] = saved.get("search_id_int").cloned().unwrap_or(Value::Null); - doc["results_path"] = Value::String(format!("/search/results/{id}/")); - doc["map_path"] = Value::String(format!("/map_search/results/{id}/1/")); - doc["results_url"] = - Value::String(ctx.client.site_url(&format!("search/results/{id}/"))); - } - } - ctx.printer.raw(&doc)?; - if understood.ignored.is_empty() { - Ok(()) - } else { - Err(ignored_error(&understood.ignored)) + let Some(id) = saved + .get("search_id") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + else { + return Err(Error::Other( + "the site did not return a search_id when saving the search".into(), + )); + }; + doc["search_id"] = Value::String(id.to_string()); + doc["search_id_int"] = saved.get("search_id_int").cloned().unwrap_or(Value::Null); + doc["results_path"] = Value::String(format!("/search/results/{id}/")); + doc["map_path"] = Value::String(format!("/map_search/results/{id}/1/")); + doc["results_url"] = Value::String(ctx.client.site_url(&format!("search/results/{id}/"))); } + ctx.printer.raw(&doc) } // ------------------------------------------------------- saved searches @@ -1626,6 +1672,14 @@ mod tests { assert!(!is_numeric_list(&list(&["100", "NaN"]))); } + #[test] + fn catalog_rows_returns_none_for_empty_or_malformed_arrays() { + assert!(catalog_rows(&json!([])).is_none()); + assert!(catalog_rows(&json!({"fields": []})).is_none()); + assert!(catalog_rows(&json!([{"label": "no id"}])).is_none()); + assert!(catalog_rows(&json!({"raw": "oops"})).is_none()); + } + #[test] fn parse_criteria_preserves_ampersand_in_values() { let q = parse_criteria(&["subdivision=Town & Country".into()]).unwrap_or_default(); diff --git a/src/commands/search_forms.rs b/src/commands/search_forms.rs index 9faa80b..885cb1b 100644 --- a/src/commands/search_forms.rs +++ b/src/commands/search_forms.rs @@ -113,15 +113,15 @@ pub fn run(ctx: &Context, cmd: SearchFormsCommand) -> Result<()> { .cloned() .unwrap_or_default(); if let Some(group) = &args.group { - let g = group.to_ascii_lowercase(); - rows.retain(|f| text(f, "group").to_ascii_lowercase().contains(&g)); + let g = group.to_lowercase(); + rows.retain(|f| text(f, "group").to_lowercase().contains(&g)); } if let Some(needle) = &args.search { - let n = needle.to_ascii_lowercase(); + let n = needle.to_lowercase(); rows.retain(|f| { ["key", "label"] .iter() - .any(|k| text(f, k).to_ascii_lowercase().contains(&n)) + .any(|k| text(f, k).to_lowercase().contains(&n)) }); } ctx.printer.list(&rows, None, FIELD_COLUMNS) diff --git a/tests/search.rs b/tests/search.rs index 056aaf7..6e02e27 100644 --- a/tests/search.rs +++ b/tests/search.rs @@ -929,6 +929,53 @@ fn check_validates_values_against_the_catalog() { ); } +#[test] +fn url_save_does_not_post_when_criteria_are_ignored() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{}}"#) + .create(); + let post = server + .mock("POST", "/api/v2/search/") + .match_query(Matcher::Any) + .expect(0) + .create(); + let assert = cmd(&server, &dir) + .args(["search", "url", "q=Buckhead", "--save"]) + .assert() + .code(5); + post.assert(); + let doc = parse(&assert.get_output().stdout); + assert_eq!(doc["ignored"], serde_json::json!(["q"])); + let err: Value = serde_json::from_slice(&assert.get_output().stderr).unwrap(); + assert_eq!(err["error"]["code"], "ignored_criteria"); +} + +#[test] +fn url_save_errors_when_search_id_is_missing() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"city":["Miami"]}}"#) + .create(); + server + .mock("POST", "/api/v2/search/") + .match_query(Matcher::Any) + .with_status(200) + .with_body("{}") + .create(); + cmd(&server, &dir) + .args(["search", "url", "city=Miami", "--save"]) + .assert() + .code(1) + .stderr(predicate::str::contains("search_id")); +} + #[test] fn check_validates_zip_from_autocomplete_and_keeps_numeric_presets() { let mut server = Server::new(); @@ -1074,6 +1121,79 @@ fn check_strict_exits_1_when_autocomplete_fails_on_unsettled_field() { assert_eq!(doc["value_warnings"], serde_json::json!([])); } +#[test] +fn fields_falls_back_when_catalog_is_empty_or_malformed() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body("[]") + .create(); + let form = server + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body(FORM) + .expect(1) + .create(); + let assert = cmd(&server, &dir) + .args(["search", "fields"]) + .assert() + .success() + .stderr(predicate::str::contains("field catalog could not be read")); + form.assert(); + let doc = parse(&assert.get_output().stdout); + assert_eq!(doc["results"][0]["section"], "primary"); +} + +#[test] +fn check_strict_exits_1_on_html_form_and_autocomplete_responses() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"city":["Miami"]}}"#) + .create(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body("maintenance") + .create(); + server + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body("maintenance") + .create(); + let index = server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_body("[]") + .expect(0) + .create(); + + let assert = cmd(&server, &dir) + .args(["search", "check", "city=Miami", "--strict"]) + .assert() + .code(1); + index.assert(); + let err: Value = serde_json::from_slice(&assert.get_output().stderr).unwrap(); + assert_eq!(err["error"]["code"], "value_check_unavailable"); + + let mut server2 = Server::new(); + server2 + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"city":["Mclean"]}}"#) + .create(); + mock_catalog(&mut server2); + server2 + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_body("maintenance") + .create(); + let assert = cmd(&server2, &dir) + .args(["search", "check", "city=Mclean", "--strict"]) + .assert() + .code(1); + let err: Value = serde_json::from_slice(&assert.get_output().stderr).unwrap(); + assert_eq!(err["error"]["code"], "value_check_unavailable"); +} + #[test] fn check_skips_empty_min_max_catalog_field_without_fetching_autocomplete() { let mut server = Server::new(); @@ -1385,3 +1505,338 @@ fn check_validates_static_catalog_field_without_hitting_autocomplete() { assert_eq!(err["error"]["code"], "value_mismatch"); index.assert(); } + +#[test] +fn run_table_footer_shows_total_pages() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"city":["Miami"]}}"#) + .create(); + server + .mock("GET", "/api/v2/search/") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("city".into(), "Miami".into()), + Matcher::UrlEncoded("page".into(), "1".into()), + Matcher::UrlEncoded("per_page".into(), "10".into()), + ])) + .with_header("x-total-count", "1234") + .with_body("[]") + .create(); + cmd(&server, &dir) + .args([ + "-o", + "table", + "search", + "run", + "city=Miami", + "--per-page", + "10", + "--page", + "1", + ]) + .assert() + .success() + .stderr(predicate::str::contains( + "1234 matching properties, page 1 of 124 shown", + )); + + server + .mock("GET", "/api/v2/search/") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("city".into(), "Miami".into()), + Matcher::UrlEncoded("page".into(), "2".into()), + Matcher::UrlEncoded("per_page".into(), "10".into()), + ])) + .with_body("[]") + .create(); + cmd(&server, &dir) + .args([ + "-o", + "table", + "search", + "run", + "city=Miami", + "--per-page", + "10", + "--page", + "2", + ]) + .assert() + .success() + .stderr(predicate::str::contains( + "? matching properties, page 2 (10 per page)", + )); +} + +#[test] +fn fields_table_merge_preserves_non_type_checkbox_labels_and_skips_null_values() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_status(404) + .create(); + server + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body( + r#"{"primary":[],"secondary":[ +{"attr":"type","label":"Home","widget_type":"checkbox","value":"res"}, +{"attr":"type","label":"Condo","widget_type":"checkbox","value":"con"}, +{"attr":"status","label":"Active","widget_type":"checkbox","value":"act"}, +{"attr":"status","label":"Pending","widget_type":"checkbox","value":"pnd"}, +{"attr":"status","label":"Status Note","widget_type":"text","value":null} +]}"#, + ) + .create(); + let out = cmd(&server, &dir) + .args(["-o", "table", "search", "fields"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let table = String::from_utf8_lossy(&out); + assert!(table.contains("Property type"), "{table}"); + assert!(table.contains("res, con"), "{table}"); + assert!(table.contains("act, pnd"), "{table}"); + assert!( + !table.contains("act, pnd, "), + "null-value row must not merge into checkbox values:\n{table}" + ); + let status_line = table + .lines() + .find(|line| line.contains("act, pnd")) + .unwrap(); + assert!( + status_line.contains("Active") && !status_line.contains("Property type"), + "non-type merged row must keep its label:\n{status_line}" + ); +} + +#[test] +fn choices_from_form_does_not_duplicate_range_choices() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body( + r#"[{"id":"beds","label":"Beds","widget":"min_max_field","flags":["min_max_field"],"choices":[]}]"#, + ) + .create(); + server + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body( + r#"{"primary":[],"secondary":[ +{"attr":"beds_min","label":"Min Beds","widget_type":"select","choices":[["all","No Min"],[1,"1+"],[2,"2+"]]}, +{"attr":"beds_max","label":"Max Beds","widget_type":"select","choices":[["all","No Max"],[1,"1+"],[2,"2+"]]} +]}"#, + ) + .create(); + + let out = cmd(&server, &dir) + .args(["search", "choices", "beds_min"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let doc = parse(&out); + let rows = doc["results"].as_array().unwrap(); + assert_eq!(rows.len(), 3, "{doc}"); + assert_eq!(rows[0]["label"], "No Min"); + + let out = cmd(&server, &dir) + .args(["search", "choices", "beds"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let doc = parse(&out); + let rows = doc["results"].as_array().unwrap(); + assert_eq!(rows.len(), 4, "{doc}"); + let labels: Vec<&str> = rows.iter().map(|r| r["label"].as_str().unwrap()).collect(); + assert_eq!(labels, ["No Min", "1+", "2+", "No Max"]); +} + +#[test] +fn choices_polygon_all_is_usage_error_before_any_request() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + let any = server + .mock("GET", Matcher::Any) + .match_query(Matcher::Any) + .expect(0) + .create(); + cmd(&server, &dir) + .args(["search", "choices", "polygon", "--all"]) + .assert() + .code(2) + .stderr(predicate::str::contains("polygon")); + cmd(&server, &dir) + .args(["search", "choices", "polygon"]) + .assert() + .code(2) + .stderr(predicate::str::contains("polygon")); + any.assert(); +} + +#[test] +fn choices_search_matches_non_ascii_case_insensitively() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_body( + r#"[{"id":"city","label":"City","widget":"multiselect","choices":[{"label":"San JOSÉ","val":"San JOSÉ"},{"label":"Miami","val":"Miami"}]}]"#, + ) + .create(); + server + .mock("GET", "/api/v2/search/autocomplete-options/") + .with_body(r#"[{"field":"city","value":"San JOSÉ"},{"field":"city","value":"Miami"}]"#) + .create(); + + let out = cmd(&server, &dir) + .args(["search", "choices", "city", "-s", "josé"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let doc = parse(&out); + assert_eq!(doc["results"].as_array().unwrap().len(), 1, "{doc}"); + assert_eq!(doc["results"][0]["value"], "San JOSÉ"); + + let out = cmd(&server, &dir) + .args(["search", "choices", "city", "--all", "-s", "josé"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let doc = parse(&out); + assert_eq!(doc["results"].as_array().unwrap().len(), 1, "{doc}"); + assert_eq!(doc["results"][0]["value"], "San JOSÉ"); +} + +#[test] +fn form_without_primary_or_secondary_reports_missing_sections() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_status(404) + .create(); + server + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body("{}") + .create(); + cmd(&server, &dir) + .args(["search", "fields"]) + .assert() + .code(1) + .stderr( + predicate::str::contains("primary or secondary") + .and(predicate::str::contains("not valid JSON").not()), + ); + + let mut server2 = Server::new(); + server2 + .mock("GET", "/search_forms/api/dump_uberform_fields.json") + .with_status(404) + .create(); + server2 + .mock("GET", "/search_forms/api/advanced_search_form.json") + .with_body(r#"{"primary":[],"secondary":[]}"#) + .create(); + let out = cmd(&server2, &dir) + .args(["search", "fields"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let doc = parse(&out); + assert_eq!(attrs(&doc), ["polygon"]); +} + +#[test] +fn run_table_footer_marks_capped_total_pages() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"city":["Miami"]}}"#) + .create(); + server + .mock("GET", "/api/v2/search/") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("city".into(), "Miami".into()), + Matcher::UrlEncoded("page".into(), "1".into()), + Matcher::UrlEncoded("per_page".into(), "10".into()), + ])) + .with_header("x-total-count", "1000") + .with_header("x-total-count-limited", "max_results") + .with_body("[]") + .create(); + cmd(&server, &dir) + .args([ + "-o", + "table", + "search", + "run", + "city=Miami", + "--per-page", + "10", + "--page", + "1", + ]) + .assert() + .success() + .stderr(predicate::str::contains( + "1000 matching properties (count limited by max_results), page 1 of 100+ shown", + )); +} + +#[test] +fn run_table_footer_falls_back_when_per_page_is_zero() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v2/search/metadata/") + .match_query(Matcher::Any) + .with_body(r#"{"description":"d","criteria":{"city":["Miami"]}}"#) + .create(); + server + .mock("GET", "/api/v2/search/") + .match_query(Matcher::AllOf(vec![ + Matcher::UrlEncoded("city".into(), "Miami".into()), + Matcher::UrlEncoded("page".into(), "1".into()), + Matcher::UrlEncoded("per_page".into(), "0".into()), + ])) + .with_header("x-total-count", "50") + .with_body("[]") + .create(); + cmd(&server, &dir) + .args([ + "-o", + "table", + "search", + "run", + "city=Miami", + "--per-page", + "0", + "--page", + "1", + ]) + .assert() + .success() + .stderr( + predicate::str::contains("50 matching properties, page 1 (0 per page)") + .and(predicate::str::contains("page 1 of 1 shown").not()), + ); +} diff --git a/tests/search_forms.rs b/tests/search_forms.rs index 5c3f5c9..a2314db 100644 --- a/tests/search_forms.rs +++ b/tests/search_forms.rs @@ -245,3 +245,55 @@ fn reset_and_revisions() { .success(); revert.assert(); } + +#[test] +fn search_forms_fields_filters_unicode_case_insensitively() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + let forms = json!({ + "source": "board", + "pages": [], + "home_page_forms": [], + "fields": [ + { + "key": "san_jose_area", + "label": "San JOSÉ Area", + "group": "Ubicación", + "kind": "choice" + }, + { + "key": "pool", + "label": "Pool", + "group": "Other", + "kind": "checkbox" + } + ] + }); + server + .mock("GET", "/api/v3/search-forms/") + .with_body(forms.to_string()) + .expect(2) + .create(); + + let out_search = cmd(&server, &dir) + .args(["search-forms", "fields", "-s", "josé"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let rows_search = parse(&out_search)["results"].as_array().unwrap().clone(); + assert_eq!(rows_search.len(), 1); + assert_eq!(rows_search[0]["key"], "san_jose_area"); + + let out_group = cmd(&server, &dir) + .args(["search-forms", "fields", "--group", "UBICACIÓN"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let rows_group = parse(&out_group)["results"].as_array().unwrap().clone(); + assert_eq!(rows_group.len(), 1); + assert_eq!(rows_group[0]["key"], "san_jose_area"); +}