//! Declarative assertions and extract rules. use crate::http::Response; use crate::model::*; use serde::Serialize; use serde_json::Value; #[derive(Debug, Clone, Serialize)] pub struct AssertResult { pub index: usize, pub label: String, pub passed: bool, pub expected: String, pub actual: String, } #[derive(Debug, Clone, Serialize)] pub struct Extracted { pub var: String, pub value: Option, pub persist: bool, pub error: Option, } pub fn json_path(doc: &Value, path: &str) -> Result, String> { let path = path.trim(); let path = if path.starts_with('$') { path.to_string() } else { format!("$.{path}") }; let p = serde_json_path::JsonPath::parse(&path).map_err(|e| format!("invalid JSONPath: {e}"))?; Ok(p.query(doc).all().into_iter().cloned().collect()) } fn target_value(rule: &AssertRule, resp: &Response) -> (Option, String) { let path = rule.path.clone().unwrap_or_default(); match rule.on { AssertTarget::Status => (Some(Value::from(resp.status)), "status".into()), AssertTarget::Time => ( Some(Value::from((resp.timings.total_ms).round() as u64)), "response time (ms)".into(), ), AssertTarget::Size => (Some(Value::from(resp.size)), "body size (bytes)".into()), AssertTarget::Body => (Some(Value::String(resp.text())), "body".into()), AssertTarget::Header => ( resp.header(&path).map(|v| Value::String(v.to_string())), format!("header {path}"), ), AssertTarget::Json => { let label = format!("json {path}"); let Some(doc) = resp.json() else { return (None, label) }; match json_path(&doc, &path) { Ok(mut v) if v.len() == 1 => (v.pop(), label), Ok(v) if v.is_empty() => (None, label), Ok(v) => (Some(Value::Array(v)), label), Err(_) => (None, label), } } } } fn show(v: &Option) -> String { match v { None => "(missing)".into(), Some(Value::String(s)) => { if s.chars().count() > 200 { format!("\"{}…\"", s.chars().take(200).collect::()) } else { format!("\"{s}\"") } } Some(v) => v.to_string(), } } /// Loose equality: `201` equals `"201"`, so YAML authors need not care about quoting. fn loose_eq(a: &Value, b: &Value) -> bool { if a == b { return true; } match (a, b) { (Value::String(s), other) | (other, Value::String(s)) if !other.is_string() => { let o = match other { Value::Null => "null".to_string(), v => v.to_string(), }; *s == o } (Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(), _ => false, } } fn type_name(v: &Value) -> &'static str { match v { Value::Null => "null", Value::Bool(_) => "boolean", Value::Number(_) => "number", Value::String(_) => "string", Value::Array(_) => "array", Value::Object(_) => "object", } } fn as_number(v: &Value) -> Option { match v { Value::Number(n) => n.as_f64(), Value::String(s) => s.trim().parse().ok(), _ => None, } } pub fn run_asserts(rules: &[AssertRule], resp: &Response) -> Vec { let mut out = Vec::new(); for (index, rule) in rules.iter().enumerate().filter(|(_, r)| r.enabled) { let (actual, label) = target_value(rule, resp); let mut push = |op: &str, expected: String, passed: bool| { out.push(AssertResult { index, label: format!("{label} {op}"), passed, expected, actual: show(&actual), }) }; if let Some(e) = &rule.equals { push("equals", e.to_string(), actual.as_ref().is_some_and(|a| loose_eq(a, e))); } if let Some(e) = &rule.not_equals { push("not equals", e.to_string(), !actual.as_ref().is_some_and(|a| loose_eq(a, e))); } if let Some(e) = &rule.contains { let ok = match (&actual, e) { (Some(Value::String(a)), Value::String(s)) => a.contains(s.as_str()), (Some(Value::String(a)), other) => a.contains(&other.to_string()), (Some(Value::Array(a)), e) => a.iter().any(|x| loose_eq(x, e)), (Some(Value::Object(o)), Value::String(k)) => o.contains_key(k), _ => false, }; push("contains", e.to_string(), ok); } if let Some(e) = rule.exists { push(if e { "exists" } else { "does not exist" }, e.to_string(), actual.is_some() == e); } if let Some(t) = &rule.type_is { let ok = actual.as_ref().is_some_and(|a| { type_name(a) == t || (t == "integer" && a.as_i64().is_some()) }); push("type", t.clone(), ok); } if let Some(re) = &rule.matches { let ok = match regex::Regex::new(re) { Ok(r) => actual.as_ref().is_some_and(|a| match a { Value::String(s) => r.is_match(s), v => r.is_match(&v.to_string()), }), Err(_) => false, }; push("matches", format!("/{re}/"), ok); } if let Some(n) = rule.gt { push(">", n.to_string(), actual.as_ref().and_then(as_number).is_some_and(|a| a > n)); } if let Some(n) = rule.lt { push("<", n.to_string(), actual.as_ref().and_then(as_number).is_some_and(|a| a < n)); } } out } pub fn run_extracts(rules: &[ExtractRule], resp: &Response) -> Vec { rules .iter() .filter(|r| r.enabled && !r.var.is_empty()) .map(|r| { let (value, error) = match extract_one(r, resp) { Ok(v) => (v, None), Err(e) => (None, Some(e)), }; Extracted { var: r.var.clone(), value, persist: r.persist, error } }) .collect() } fn extract_one(r: &ExtractRule, resp: &Response) -> Result, String> { Ok(match r.from { ExtractSource::Status => Some(resp.status.to_string()), ExtractSource::Header => resp.header(&r.path).map(str::to_string), ExtractSource::Cookie => resp.cookies.iter().find(|c| c.name == r.path).map(|c| c.value.clone()), ExtractSource::Regex => { let re = regex::Regex::new(&r.path).map_err(|e| format!("invalid regex: {e}"))?; let text = resp.text(); re.captures(&text) .map(|c| c.get(1).or_else(|| c.get(0)).unwrap().as_str().to_string()) } ExtractSource::Json => { let doc = resp.json().ok_or("response body is not JSON")?; let mut v = json_path(&doc, &r.path)?; match v.len() { 0 => None, 1 => Some(scalar_to_string(&v.pop().unwrap())), _ => Some(Value::Array(v).to_string()), } } }) } #[cfg(test)] mod tests { use super::*; use crate::http::Timings; fn resp(body: &str) -> Response { Response { status: 201, status_text: "Created".into(), http_version: "1.1".into(), url: "http://x".into(), headers: vec![("Content-Type".into(), "application/json".into())], cookies: vec![], size: body.len() as u64, header_size: 0, content_type: Some("application/json".into()), timings: Timings { total_ms: 12.0, ..Default::default() }, redirects: vec![], remote_addr: None, body_file: None, body: body.as_bytes().to_vec(), } } #[test] fn asserts() { let r = resp(r#"{"id": 7, "tags": ["a","b"], "name": "Ann"}"#); let rules: Vec = serde_yaml_ng::from_str( r#" - { on: status, equals: 201 } - { on: json, path: $.id, equals: "7", type: number } - { on: json, path: tags, contains: b } - { on: json, path: $.missing, exists: false } - { on: header, path: content-type, matches: "json$" } - { on: time, lt: 1000 } - { on: status, equals: 200 } "#, ) .unwrap(); let res = run_asserts(&rules, &r); let failed: Vec<_> = res.iter().filter(|r| !r.passed).collect(); assert_eq!(failed.len(), 1, "{res:#?}"); assert_eq!(failed[0].index, 6); } #[test] fn extracts() { let r = resp(r#"{"data": {"id": "abc"}}"#); let rules = vec![ ExtractRule { var: "id".into(), from: ExtractSource::Json, path: "$.data.id".into(), enabled: true, persist: false }, ExtractRule { var: "ct".into(), from: ExtractSource::Header, path: "content-type".into(), enabled: true, persist: false }, ExtractRule { var: "re".into(), from: ExtractSource::Regex, path: r#""id": "(\w+)""#.into(), enabled: true, persist: false }, ]; let out = run_extracts(&rules, &r); assert_eq!(out[0].value.as_deref(), Some("abc")); assert_eq!(out[1].value.as_deref(), Some("application/json")); assert_eq!(out[2].value.as_deref(), Some("abc")); } }