diff --git a/rust/pact_matching/README.md b/rust/pact_matching/README.md index 4138b80b6..1a2eddaca 100644 --- a/rust/pact_matching/README.md +++ b/rust/pact_matching/README.md @@ -214,7 +214,29 @@ are compared in the order they appear in the query string. For matching header values: 1. If there is a matcher defined for `header.`, default to that matcher -2. Otherwise strip all whitespace after commas and compare the resulting strings. +2. Otherwise compare the values according to the kind of header: + * Single-value headers (`Set-Cookie`, `Date`, `User-Agent`, …): each value is compared on its own. + * `Accept` and `Content-Type`: the media type must be equal and the parameters are compared + by name, ignoring the case of their values. + * Known multi-value headers: each value is compared on its own, in order. + * Custom headers: see below. + +Plain comparison of two single values trims whitespace around each comma and then compares the +strings for equality, so `a,b` matches `a, b`. + +Custom headers: repeated field lines are one comma-joined list (RFC 9110 section 5.3). + +* **No matcher.** The field lines on each side are joined with commas, ignoring whitespace and + empty elements outside quoted strings, and the joined values are compared. +* **Scalar matchers** (`Equality`, `Regex`, `Type`, `Include` and so on) see the joined value. +* **List matchers** (`MinType`, `MaxType`, `MinMaxType`, `EachValue`, `ArrayContains`, + index-specific rules and `[*]` wildcard rules) see the list elements. The joined value is split + on commas outside quoted strings. `Link` also keeps commas inside `<...>` together, and `Via` + keeps commas inside nested `(...)` comments together. + +When the joined comparison fails but comparing the field lines one by one succeeds, the header +passes with a deprecation warning. A future release will compare only the joined value, or the +list elements for list matchers. #### Matching Request Headers diff --git a/rust/pact_matching/src/engine/interpreter.rs b/rust/pact_matching/src/engine/interpreter.rs index 899b80df0..217f4bdba 100644 --- a/rust/pact_matching/src/engine/interpreter.rs +++ b/rust/pact_matching/src/engine/interpreter.rs @@ -8,10 +8,10 @@ use anyhow::anyhow; use itertools::Itertools; use maplit::hashset; use serde_json::{json, Value}; -use tracing::{debug, error, instrument, Level, trace}; +use tracing::{debug, error, instrument, Level, trace, warn}; use itertools::Either; -use pact_models::matchingrules::MatchingRule; +use pact_models::matchingrules::{MatchingRule, MatchingRuleCategory}; use pact_models::path_exp::{DocPath, PathToken}; #[cfg(feature = "xml")] use pact_models::xml_utils::resolve_matching_node; @@ -20,9 +20,11 @@ use crate::engine::context::PlanMatchingContext; use crate::engine::value_resolvers::ValueResolver; use crate::field_rules::scope_from_plan_path; #[cfg(feature = "xml")] use crate::engine::xml::XmlValue; +use crate::{CoreMatchingContext, DiffConfig}; use crate::headers::{parse_charset_parameters, strip_whitespace}; use crate::json::type_of; use crate::matchingrules::DoMatch; +use crate::repeated_headers::{match_repeated_header, normalise_list}; #[cfg(feature = "xml")] use crate::xml::resolve_attr_namespaces; /// Main interpreter for the matching plan AST @@ -321,6 +323,8 @@ impl ExecutionPlanInterpreter { "error" => self.execute_error(action, value_resolver, node, &action_path), "header:parse" => self.execute_header_parse(action, value_resolver, node, &action_path), "header:normalize-commas" => self.execute_normalize_comma_whitespace(action, value_resolver, node, &action_path), + "header:repeated" => self.execute_header_repeated(action, value_resolver, node, &action_path), + "header:match-repeated" => self.execute_header_match_repeated(action, value_resolver, node, &action_path), "for-each" => self.execute_for_each(value_resolver, node, &action_path), #[cfg(feature = "multipart")] "multipart:parse" => self.execute_multipart_parse(action, value_resolver, node, &action_path), @@ -2519,9 +2523,8 @@ impl ExecutionPlanInterpreter { Err(value) => return value }; - let normalize = |s: &str| -> String { - s.split(',').map(|v| v.trim()).collect::>().join(",") - }; + // Only MULTI_VALUE_HEADERS reach this action, and they all use the plain list grammar. + let normalize = |s: &str| normalise_list("", s); let results = values.iter() .map(|v| { @@ -2547,6 +2550,64 @@ impl ExecutionPlanInterpreter { } } + fn execute_header_repeated( + &mut self, + action: &str, + value_resolver: &dyn ValueResolver, + node: ExecutionPlanNode, + action_path: &Vec + ) -> ExecutionPlanNode { + let ExecutionPlanNode { node_type, children, .. } = node; + match self.validate_one_arg(children, action, value_resolver, action_path) { + Ok(value) => { + let repeated = value.value() + .unwrap_or_default() + .as_slist() + .is_some_and(|values| values.len() > 1); + ExecutionPlanNode { + node_type, + result: Some(NodeResult::VALUE(NodeValue::BOOL(repeated))), + children: vec![value] + } + } + Err(err) => { + ExecutionPlanNode { + node_type, + result: Some(NodeResult::ERROR(err.to_string())), + children: vec![] + } + } + } + } + + fn execute_header_match_repeated( + &mut self, + action: &str, + value_resolver: &dyn ValueResolver, + node: ExecutionPlanNode, + action_path: &Vec + ) -> ExecutionPlanNode { + let ExecutionPlanNode { node_type, children, .. } = node; + match self.validate_args(4, 0, children, action, value_resolver, action_path) { + Ok((args, _)) => { + let result = match_repeated_header_args(&args) + .unwrap_or_else(|err| NodeResult::ERROR(err.to_string())); + ExecutionPlanNode { + node_type, + result: Some(result), + children: args + } + } + Err(err) => { + ExecutionPlanNode { + node_type, + result: Some(NodeResult::ERROR(err.to_string())), + children: vec![] + } + } + } + } + fn execute_for_each( &mut self, value_resolver: &dyn ValueResolver, @@ -2860,3 +2921,38 @@ fn json_check_type(expected_type: String, json_value: &Value) -> anyhow::Result< _ => Err(anyhow!("'{}' is not a valid JSON type", expected_type)) } } + +fn header_values(value: NodeValue) -> Vec { + match value { + NodeValue::STRING(value) => vec![value], + NodeValue::SLIST(values) => values, + _ => vec![] + } +} + +fn match_repeated_header_args(args: &[ExecutionPlanNode]) -> anyhow::Result { + let mut values = args.iter() + .map(|arg| arg.value().unwrap_or_default().value_or_error()) + .collect::>>()? + .into_iter(); + let key = values.next().and_then(|value| value.as_string()).unwrap_or_default(); + let expected = header_values(values.next().unwrap_or_default()); + let actual = header_values(values.next().unwrap_or_default()); + let mut rules = MatchingRuleCategory::empty("header"); + rules.add_rules_from_json(&values.next().and_then(|value| value.as_json()).unwrap_or_default())?; + + #[cfg(feature = "plugins")] #[cfg(not(target_family = "wasm"))] + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &rules, &std::collections::HashMap::new()); + #[cfg(any(not(feature = "plugins"), target_family = "wasm"))] + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &rules); + + let result = match_repeated_header(&key, &expected, &actual, &context); + if result.mismatches.is_empty() { + if let Some(warning) = &result.warning { + warn!("{}", warning); + } + Ok(NodeResult::VALUE(NodeValue::BOOL(true))) + } else { + Ok(NodeResult::ERROR(result.mismatches.iter().map(|mismatch| mismatch.description.as_str()).join(", "))) + } +} diff --git a/rust/pact_matching/src/engine/mod.rs b/rust/pact_matching/src/engine/mod.rs index b4e343b6f..0b241fe39 100644 --- a/rust/pact_matching/src/engine/mod.rs +++ b/rust/pact_matching/src/engine/mod.rs @@ -13,7 +13,7 @@ use bytes::Bytes; use itertools::Itertools; #[cfg(feature = "xml")] use kiss_xml::dom::Element; use maplit::hashmap; -use serde_json::Value; +use serde_json::{json, Value}; use serde_json::Value::Object; use tracing::debug; use pact_models::bodies::OptionalBody; @@ -35,6 +35,7 @@ use crate::headers::{parse_charset_parameters, strip_whitespace}; use crate::{BodyMatchResult, Mismatch}; use crate::matchingrules::{DoMatch, value_for_mismatch}; use crate::Mismatch::{BodyMismatch, HeaderMismatch, MetadataMismatch, QueryMismatch}; +use crate::repeated_headers::{header_kind, normalise_list, HeaderKind}; mod bodies; mod value_resolvers; @@ -1961,6 +1962,49 @@ fn setup_query_plan( Ok(plan_node) } +/// Routes a custom header with more than one field line on either side through +/// `header:match-repeated`. Other headers keep `match_node`. +fn build_custom_header_node( + key: &str, + expected: &[String], + path: &DocPath, + match_node: ExecutionPlanNode, + context: &PlanMatchingContext +) -> ExecutionPlanNode { + if header_kind(key) != HeaderKind::Custom || expected.is_empty() { + return match_node; + } + + let rules = context.matching_rules + .filter(|(rule_path, _)| rule_path.first_field().is_some_and(|field| field.eq_ignore_ascii_case(key))); + // Keyed by the full path, as `MatchingRuleCategory::to_v3_json` drops indexes from header paths. + let rules_json = Value::Object(rules.rules.iter() + .map(|(rule_path, rule_list)| (rule_path.to_lower_case().to_string(), json!({ + "combine": if rule_list.rule_logic == RuleLogic::Or { "OR" } else { "AND" }, + "matchers": rule_list.rules.iter().map(|rule| rule.to_json()).collect_vec() + }))) + .sorted_by(|(a, _), (b, _)| a.cmp(b)) + .collect()); + let mut match_repeated = ExecutionPlanNode::action("header:match-repeated"); + match_repeated + .add(ExecutionPlanNode::value_node(key)) + .add(ExecutionPlanNode::value_node(NodeValue::SLIST(expected.to_vec()))) + .add(ExecutionPlanNode::resolve_value(path.clone())) + .add(ExecutionPlanNode::value_node(NodeValue::JSON(rules_json))); + + if expected.len() > 1 { + match_repeated + } else { + let mut repeated_check = ExecutionPlanNode::action("if"); + repeated_check + .add(ExecutionPlanNode::action("header:repeated") + .add(ExecutionPlanNode::resolve_value(path.clone()))) + .add(match_repeated) + .add(match_node); + repeated_check + } +} + fn setup_header_plan( expected: &T, context: &PlanMatchingContext @@ -1989,12 +2033,14 @@ fn setup_header_plan( let item_path = DocPath::root().join(key); let path = doc_path.join(key); + let actual_value = ExecutionPlanNode::resolve_value(path.clone()); if context.matcher_is_defined(&item_path) { let matchers = context.select_best_matcher(&item_path); item_node.add(ExecutionPlanNode::annotation(format!("{} {}", key, matchers.generate_description(true)))); - presence_check.add(build_matching_rule_node(&ExecutionPlanNode::value_node(item_value), - &ExecutionPlanNode::resolve_value(&path), &matchers, true, - context.config.show_types_in_errors)); + let match_node = build_matching_rule_node(&ExecutionPlanNode::value_node(item_value), + &actual_value, &matchers, true, + context.config.show_types_in_errors); + presence_check.add(build_custom_header_node(key, value, &path, match_node, context)); } else if PARAMETERISED_HEADERS.contains(&key.to_lowercase().as_str()) { item_node.add(ExecutionPlanNode::annotation(format!("{}={}", key, item_value.to_string()))); if value.len() == 1 { @@ -2018,7 +2064,7 @@ fn setup_header_plan( // for known multi-value headers. Custom headers (e.g. JSON payloads) must not // be normalised as commas are semantically significant there. let normalized_value = if let NodeValue::STRING(s) = &item_value { - NodeValue::STRING(s.split(',').map(|v| v.trim()).collect::>().join(",")) + NodeValue::STRING(normalise_list(key, s)) } else { item_value.clone() }; @@ -2031,11 +2077,11 @@ fn setup_header_plan( } else { item_check .add(ExecutionPlanNode::value_node(item_value)) - .add(ExecutionPlanNode::resolve_value(doc_path.join(key))) + .add(actual_value) .add(ExecutionPlanNode::value_node(NodeValue::NULL)) .add(ExecutionPlanNode::value_node(context.config.show_types_in_errors)); } - presence_check.add(item_check); + presence_check.add(build_custom_header_node(key, value, &path, item_check, context)); } presence_check.add( diff --git a/rust/pact_matching/src/engine/tests/header_tests.rs b/rust/pact_matching/src/engine/tests/header_tests.rs index 3b4d1a805..1433e8096 100644 --- a/rust/pact_matching/src/engine/tests/header_tests.rs +++ b/rust/pact_matching/src/engine/tests/header_tests.rs @@ -3,11 +3,38 @@ use maplit::hashmap; use pact_models::matchingrules; use pact_models::matchingrules::MatchingRule; use pact_models::prelude::v4::SynchronousHttp; -use pact_models::v4::http_parts::HttpRequest; +use pact_models::v4::http_parts::{HttpRequest, HttpResponse}; use pact_models::v4::interaction::V4Interaction; -use crate::engine::{execute_request_plan, ExecutionPlan, setup_header_plan}; +use crate::engine::{ + build_request_plan, build_response_plan, execute_request_plan, execute_response_plan, + ExecutionPlan, NodeResult, NodeValue, setup_header_plan +}; use crate::engine::context::PlanMatchingContext; +use crate::repeated_headers::cases; + +#[test] +fn match_repeated_custom_headers_in_request_and_response_plans() { + let expected_headers = Some(hashmap! { + "X-Request".to_string() => vec!["request1".to_string(), "request2".to_string()] + }); + let actual_headers = Some(hashmap! { + "X-Request".to_string() => vec!["request1, request2".to_string()] + }); + let context = PlanMatchingContext::default(); + + let expected_request = HttpRequest { headers: expected_headers.clone(), ..HttpRequest::default() }; + let actual_request = HttpRequest { headers: actual_headers.clone(), ..HttpRequest::default() }; + let request_plan = build_request_plan(&expected_request, &context).unwrap(); + let request_result = execute_request_plan(&request_plan, &actual_request, &context).unwrap(); + assert_eq!(request_result.plan_root.result, Some(NodeResult::VALUE(NodeValue::BOOL(true)))); + + let expected_response = HttpResponse { headers: expected_headers, ..HttpResponse::default() }; + let actual_response = HttpResponse { headers: actual_headers, ..HttpResponse::default() }; + let response_plan = build_response_plan(&expected_response, &context).unwrap(); + let response_result = execute_response_plan(&response_plan, &actual_response, &context).unwrap(); + assert_eq!(response_result.plan_root.result, Some(NodeResult::VALUE(NodeValue::BOOL(true)))); +} #[test] fn match_headers_where_there_are_none() { @@ -62,11 +89,22 @@ fn match_headers_with_expected_headers() { %check:exists ( $.headers['HEADER-X'] ), - %match:equality ( - 'b', - $.headers['HEADER-X'], - NULL, - BOOL(false) + %if ( + %header:repeated ( + $.headers['HEADER-X'] + ), + %header:match-repeated ( + 'HEADER-X', + ['b'], + $.headers['HEADER-X'], + json:{} + ), + %match:equality ( + 'b', + $.headers['HEADER-X'], + NULL, + BOOL(false) + ) ), %error ( 'Expected header \'HEADER-X\' but was missing' @@ -104,11 +142,22 @@ fn match_headers_with_expected_headers() { %check:exists ( $.headers['HEADER-X'] => NULL ) => BOOL(false), - %match:equality ( - 'b', - $.headers['HEADER-X'], - NULL, - BOOL(false) + %if ( + %header:repeated ( + $.headers['HEADER-X'] + ), + %header:match-repeated ( + 'HEADER-X', + ['b'], + $.headers['HEADER-X'], + json:{} + ), + %match:equality ( + 'b', + $.headers['HEADER-X'], + NULL, + BOOL(false) + ) ), %error ( 'Expected header \'HEADER-X\' but was missing' => 'Expected header \'HEADER-X\' but was missing' @@ -151,11 +200,22 @@ fn match_headers_with_expected_headers() { %check:exists ( $.headers['HEADER-X'] => 'b' ) => BOOL(true), - %match:equality ( - 'b' => 'b', - $.headers['HEADER-X'] => 'b', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['HEADER-X'] => 'b' + ) => BOOL(false), + %header:match-repeated ( + 'HEADER-X', + ['b'], + $.headers['HEADER-X'], + json:{} + ), + %match:equality ( + 'b' => 'b', + $.headers['HEADER-X'] => 'b', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'HEADER-X\' but was missing' @@ -198,12 +258,23 @@ fn match_headers_with_expected_headers() { %check:exists ( $.headers['HEADER-X'] => 'C' ) => BOOL(true), - %match:equality ( - 'b' => 'b', - $.headers['HEADER-X'] => 'C', - NULL => NULL, - BOOL(false) => BOOL(false) - ) => ERROR(Expected 'C' to be equal to 'b'), + %if ( + %header:repeated ( + $.headers['HEADER-X'] => 'C' + ) => BOOL(false), + %header:match-repeated ( + 'HEADER-X', + ['b'], + $.headers['HEADER-X'], + json:{} + ), + %match:equality ( + 'b' => 'b', + $.headers['HEADER-X'] => 'C', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => ERROR(Expected 'C' to be equal to 'b') + ) => BOOL(false), %error ( 'Expected header \'HEADER-X\' but was missing' ) @@ -246,11 +317,22 @@ fn match_headers_with_expected_headers() { %check:exists ( $.headers['HEADER-X'] => 'b' ) => BOOL(true), - %match:equality ( - 'b' => 'b', - $.headers['HEADER-X'] => 'b', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['HEADER-X'] => 'b' + ) => BOOL(false), + %header:match-repeated ( + 'HEADER-X', + ['b'], + $.headers['HEADER-X'], + json:{} + ), + %match:equality ( + 'b' => 'b', + $.headers['HEADER-X'] => 'b', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'HEADER-X\' but was missing' @@ -293,11 +375,22 @@ fn match_headers_with_expected_headers() { %check:exists ( $.headers['HEADER-X'] => NULL ) => BOOL(false), - %match:equality ( - 'b', - $.headers['HEADER-X'], - NULL, - BOOL(false) + %if ( + %header:repeated ( + $.headers['HEADER-X'] + ), + %header:match-repeated ( + 'HEADER-X', + ['b'], + $.headers['HEADER-X'], + json:{} + ), + %match:equality ( + 'b', + $.headers['HEADER-X'], + NULL, + BOOL(false) + ) ), %error ( 'Expected header \'HEADER-X\' but was missing' => 'Expected header \'HEADER-X\' but was missing' @@ -359,11 +452,22 @@ fn match_headers_with_matching_rule() { %check:exists ( $.headers['REF-CODE'] ), - %match:equality ( - 'test', - $.headers['REF-CODE'], - NULL, - BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] + ), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test', + $.headers['REF-CODE'], + NULL, + BOOL(false) + ) ), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -376,11 +480,22 @@ fn match_headers_with_matching_rule() { %check:exists ( $.headers['REF-ID'] ), - %match:regex ( - '1234', - $.headers['REF-ID'], - json:{"regex":"^[0-9]+$"}, - BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-ID'] + ), + %header:match-repeated ( + 'REF-ID', + ['1234'], + $.headers['REF-ID'], + json:{"ref-id":{"combine":"AND","matchers":[{"match":"regex","regex":"^[0-9]+$"}]}} + ), + %match:regex ( + '1234', + $.headers['REF-ID'], + json:{"regex":"^[0-9]+$"}, + BOOL(false) + ) ), %error ( 'Expected header \'REF-ID\' but was missing' @@ -424,11 +539,22 @@ fn match_headers_with_matching_rule() { %check:exists ( $.headers['REF-CODE'] => 'test' ) => BOOL(true), - %match:equality ( - 'test' => 'test', - $.headers['REF-CODE'] => 'test', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] => 'test' + ) => BOOL(false), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test' => 'test', + $.headers['REF-CODE'] => 'test', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -441,11 +567,22 @@ fn match_headers_with_matching_rule() { %check:exists ( $.headers['REF-ID'] => '9023470945622' ) => BOOL(true), - %match:regex ( - '1234' => '1234', - $.headers['REF-ID'] => '9023470945622', - json:{"regex":"^[0-9]+$"} => json:{"regex":"^[0-9]+$"}, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-ID'] => '9023470945622' + ) => BOOL(false), + %header:match-repeated ( + 'REF-ID', + ['1234'], + $.headers['REF-ID'], + json:{"ref-id":{"combine":"AND","matchers":[{"match":"regex","regex":"^[0-9]+$"}]}} + ), + %match:regex ( + '1234' => '1234', + $.headers['REF-ID'] => '9023470945622', + json:{"regex":"^[0-9]+$"} => json:{"regex":"^[0-9]+$"}, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-ID\' but was missing' @@ -489,11 +626,22 @@ fn match_headers_with_matching_rule() { %check:exists ( $.headers['REF-CODE'] => 'test' ) => BOOL(true), - %match:equality ( - 'test' => 'test', - $.headers['REF-CODE'] => 'test', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] => 'test' + ) => BOOL(false), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test' => 'test', + $.headers['REF-CODE'] => 'test', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -506,12 +654,23 @@ fn match_headers_with_matching_rule() { %check:exists ( $.headers['REF-ID'] => '9023470X945622' ) => BOOL(true), - %match:regex ( - '1234' => '1234', - $.headers['REF-ID'] => '9023470X945622', - json:{"regex":"^[0-9]+$"} => json:{"regex":"^[0-9]+$"}, - BOOL(false) => BOOL(false) - ) => ERROR(Expected '9023470X945622' to match '^[0-9]+$'), + %if ( + %header:repeated ( + $.headers['REF-ID'] => '9023470X945622' + ) => BOOL(false), + %header:match-repeated ( + 'REF-ID', + ['1234'], + $.headers['REF-ID'], + json:{"ref-id":{"combine":"AND","matchers":[{"match":"regex","regex":"^[0-9]+$"}]}} + ), + %match:regex ( + '1234' => '1234', + $.headers['REF-ID'] => '9023470X945622', + json:{"regex":"^[0-9]+$"} => json:{"regex":"^[0-9]+$"}, + BOOL(false) => BOOL(false) + ) => ERROR(Expected '9023470X945622' to match '^[0-9]+$') + ) => BOOL(false), %error ( 'Expected header \'REF-ID\' but was missing' ) @@ -568,11 +727,11 @@ fn match_headers_with_values_having_different_lengths() { %check:exists ( $.headers['REF-CODE'] ), - %match:equality ( + %header:match-repeated ( + 'REF-CODE', ['test', 'test2'], $.headers['REF-CODE'], - NULL, - BOOL(false) + json:{} ), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -585,11 +744,22 @@ fn match_headers_with_values_having_different_lengths() { %check:exists ( $.headers['REF-ID'] ), - %match:equality ( - '1234', - $.headers['REF-ID'], - NULL, - BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-ID'] + ), + %header:match-repeated ( + 'REF-ID', + ['1234'], + $.headers['REF-ID'], + json:{} + ), + %match:equality ( + '1234', + $.headers['REF-ID'], + NULL, + BOOL(false) + ) ), %error ( 'Expected header \'REF-ID\' but was missing' @@ -633,11 +803,11 @@ fn match_headers_with_values_having_different_lengths() { %check:exists ( $.headers['REF-CODE'] => ['test', 'test2'] ) => BOOL(true), - %match:equality ( + %header:match-repeated ( + 'REF-CODE' => 'REF-CODE', ['test', 'test2'] => ['test', 'test2'], $.headers['REF-CODE'] => ['test', 'test2'], - NULL => NULL, - BOOL(false) => BOOL(false) + json:{} => json:{} ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -650,11 +820,22 @@ fn match_headers_with_values_having_different_lengths() { %check:exists ( $.headers['REF-ID'] => '1234' ) => BOOL(true), - %match:equality ( - '1234' => '1234', - $.headers['REF-ID'] => '1234', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-ID'] => '1234' + ) => BOOL(false), + %header:match-repeated ( + 'REF-ID', + ['1234'], + $.headers['REF-ID'], + json:{} + ), + %match:equality ( + '1234' => '1234', + $.headers['REF-ID'] => '1234', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-ID\' but was missing' @@ -698,12 +879,12 @@ fn match_headers_with_values_having_different_lengths() { %check:exists ( $.headers['REF-CODE'] => 'test' ) => BOOL(true), - %match:equality ( + %header:match-repeated ( + 'REF-CODE' => 'REF-CODE', ['test', 'test2'] => ['test', 'test2'], $.headers['REF-CODE'] => 'test', - NULL => NULL, - BOOL(false) => BOOL(false) - ) => ERROR(Expected 'test' to be equal to ['test', 'test2']), + json:{} => json:{} + ) => ERROR(Mismatch with header 'REF-CODE': Expected 'test' to be equal to 'test, test2'), %error ( 'Expected header \'REF-CODE\' but was missing' ) @@ -715,12 +896,23 @@ fn match_headers_with_values_having_different_lengths() { %check:exists ( $.headers['REF-ID'] => ['1234', '1234', '4567'] ) => BOOL(true), - %match:equality ( - '1234' => '1234', - $.headers['REF-ID'] => ['1234', '1234', '4567'], - NULL => NULL, - BOOL(false) => BOOL(false) - ) => ERROR(Expected ['1234', '1234', '4567'] to be equal to '1234'), + %if ( + %header:repeated ( + $.headers['REF-ID'] => ['1234', '1234', '4567'] + ) => BOOL(true), + %header:match-repeated ( + 'REF-ID' => 'REF-ID', + ['1234'] => ['1234'], + $.headers['REF-ID'] => ['1234', '1234', '4567'], + json:{} => json:{} + ) => ERROR(Mismatch with header 'REF-ID': Expected '1234, 1234, 4567' to be equal to '1234'), + %match:equality ( + '1234', + $.headers['REF-ID'], + NULL, + BOOL(false) + ) + ) => BOOL(false), %error ( 'Expected header \'REF-ID\' but was missing' ) @@ -781,11 +973,22 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-CODE'] ), - %match:equality ( - 'test', - $.headers['REF-CODE'], - NULL, - BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] + ), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test', + $.headers['REF-CODE'], + NULL, + BOOL(false) + ) ), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -798,11 +1001,22 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-ID'] ), - %match:integer ( - '1234', - $.headers['REF-ID'], - json:{}, - BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-ID'] + ), + %header:match-repeated ( + 'REF-ID', + ['1234'], + $.headers['REF-ID'], + json:{"ref-id":{"combine":"AND","matchers":[{"match":"integer"}]}} + ), + %match:integer ( + '1234', + $.headers['REF-ID'], + json:{}, + BOOL(false) + ) ), %error ( 'Expected header \'REF-ID\' but was missing' @@ -846,11 +1060,22 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-CODE'] => 'test' ) => BOOL(true), - %match:equality ( - 'test' => 'test', - $.headers['REF-CODE'] => 'test', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] => 'test' + ) => BOOL(false), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test' => 'test', + $.headers['REF-CODE'] => 'test', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -863,11 +1088,22 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-ID'] => '9023470945622' ) => BOOL(true), - %match:integer ( - '1234' => '1234', - $.headers['REF-ID'] => '9023470945622', - json:{} => json:{}, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-ID'] => '9023470945622' + ) => BOOL(false), + %header:match-repeated ( + 'REF-ID', + ['1234'], + $.headers['REF-ID'], + json:{"ref-id":{"combine":"AND","matchers":[{"match":"integer"}]}} + ), + %match:integer ( + '1234' => '1234', + $.headers['REF-ID'] => '9023470945622', + json:{} => json:{}, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-ID\' but was missing' @@ -911,11 +1147,22 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-CODE'] => 'test' ) => BOOL(true), - %match:equality ( - 'test' => 'test', - $.headers['REF-CODE'] => 'test', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] => 'test' + ) => BOOL(false), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test' => 'test', + $.headers['REF-CODE'] => 'test', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -928,12 +1175,23 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-ID'] => '9023470X945622' ) => BOOL(true), - %match:integer ( - '1234' => '1234', - $.headers['REF-ID'] => '9023470X945622', - json:{} => json:{}, - BOOL(false) => BOOL(false) - ) => ERROR(Expected '9023470X945622' to match an integer number), + %if ( + %header:repeated ( + $.headers['REF-ID'] => '9023470X945622' + ) => BOOL(false), + %header:match-repeated ( + 'REF-ID', + ['1234'], + $.headers['REF-ID'], + json:{"ref-id":{"combine":"AND","matchers":[{"match":"integer"}]}} + ), + %match:integer ( + '1234' => '1234', + $.headers['REF-ID'] => '9023470X945622', + json:{} => json:{}, + BOOL(false) => BOOL(false) + ) => ERROR(Expected '9023470X945622' to match an integer number) + ) => BOOL(false), %error ( 'Expected header \'REF-ID\' but was missing' ) @@ -976,11 +1234,22 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-CODE'] => 'test' ) => BOOL(true), - %match:equality ( - 'test' => 'test', - $.headers['REF-CODE'] => 'test', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] => 'test' + ) => BOOL(false), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test' => 'test', + $.headers['REF-CODE'] => 'test', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -993,11 +1262,22 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-ID'] => ['1111', '2222'] ) => BOOL(true), - %match:integer ( - '1234' => '1234', - $.headers['REF-ID'] => ['1111', '2222'], - json:{} => json:{}, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-ID'] => ['1111', '2222'] + ) => BOOL(true), + %header:match-repeated ( + 'REF-ID' => 'REF-ID', + ['1234'] => ['1234'], + $.headers['REF-ID'] => ['1111', '2222'], + json:{"ref-id":{"combine":"AND","matchers":[{"match":"integer"}]}} => json:{"ref-id":{"combine":"AND","matchers":[{"match":"integer"}]}} + ) => BOOL(true), + %match:integer ( + '1234', + $.headers['REF-ID'], + json:{}, + BOOL(false) + ) ) => BOOL(true), %error ( 'Expected header \'REF-ID\' but was missing' @@ -1041,11 +1321,22 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-CODE'] => 'test' ) => BOOL(true), - %match:equality ( - 'test' => 'test', - $.headers['REF-CODE'] => 'test', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] => 'test' + ) => BOOL(false), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test' => 'test', + $.headers['REF-CODE'] => 'test', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -1058,12 +1349,23 @@ fn match_headers_with_number_type_matching_rule() { %check:exists ( $.headers['REF-ID'] => ['1111', 'two'] ) => BOOL(true), - %match:integer ( - '1234' => '1234', - $.headers['REF-ID'] => ['1111', 'two'], - json:{} => json:{}, - BOOL(false) => BOOL(false) - ) => ERROR(Expected 'two' to match an integer number), + %if ( + %header:repeated ( + $.headers['REF-ID'] => ['1111', 'two'] + ) => BOOL(true), + %header:match-repeated ( + 'REF-ID' => 'REF-ID', + ['1234'] => ['1234'], + $.headers['REF-ID'] => ['1111', 'two'], + json:{"ref-id":{"combine":"AND","matchers":[{"match":"integer"}]}} => json:{"ref-id":{"combine":"AND","matchers":[{"match":"integer"}]}} + ) => ERROR(Mismatch with header 'REF-ID': Expected '1111, two' to match an integer number, Mismatch with header 'REF-ID': Expected 'two' to match an integer number for value at index 1), + %match:integer ( + '1234', + $.headers['REF-ID'], + json:{}, + BOOL(false) + ) + ) => BOOL(false), %error ( 'Expected header \'REF-ID\' but was missing' ) @@ -1124,11 +1426,22 @@ fn match_headers_with_min_type_matching_rules() { %check:exists ( $.headers['REF-CODE'] ), - %match:equality ( - 'test', - $.headers['REF-CODE'], - NULL, - BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] + ), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test', + $.headers['REF-CODE'], + NULL, + BOOL(false) + ) ), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -1141,11 +1454,11 @@ fn match_headers_with_min_type_matching_rules() { %check:exists ( $.headers['REF-ID'] ), - %match:min-type ( + %header:match-repeated ( + 'REF-ID', ['1234', '4567'], $.headers['REF-ID'], - json:{"min":2}, - BOOL(false) + json:{"ref-id":{"combine":"AND","matchers":[{"match":"type","min":2}]}} ), %error ( 'Expected header \'REF-ID\' but was missing' @@ -1189,11 +1502,22 @@ fn match_headers_with_min_type_matching_rules() { %check:exists ( $.headers['REF-CODE'] => 'test' ) => BOOL(true), - %match:equality ( - 'test' => 'test', - $.headers['REF-CODE'] => 'test', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] => 'test' + ) => BOOL(false), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test' => 'test', + $.headers['REF-CODE'] => 'test', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -1206,11 +1530,11 @@ fn match_headers_with_min_type_matching_rules() { %check:exists ( $.headers['REF-ID'] => ['1', '1', '1'] ) => BOOL(true), - %match:min-type ( + %header:match-repeated ( + 'REF-ID' => 'REF-ID', ['1234', '4567'] => ['1234', '4567'], $.headers['REF-ID'] => ['1', '1', '1'], - json:{"min":2} => json:{"min":2}, - BOOL(false) => BOOL(false) + json:{"ref-id":{"combine":"AND","matchers":[{"match":"type","min":2}]}} => json:{"ref-id":{"combine":"AND","matchers":[{"match":"type","min":2}]}} ) => BOOL(true), %error ( 'Expected header \'REF-ID\' but was missing' @@ -1254,11 +1578,22 @@ fn match_headers_with_min_type_matching_rules() { %check:exists ( $.headers['REF-CODE'] => 'test' ) => BOOL(true), - %match:equality ( - 'test' => 'test', - $.headers['REF-CODE'] => 'test', - NULL => NULL, - BOOL(false) => BOOL(false) + %if ( + %header:repeated ( + $.headers['REF-CODE'] => 'test' + ) => BOOL(false), + %header:match-repeated ( + 'REF-CODE', + ['test'], + $.headers['REF-CODE'], + json:{} + ), + %match:equality ( + 'test' => 'test', + $.headers['REF-CODE'] => 'test', + NULL => NULL, + BOOL(false) => BOOL(false) + ) => BOOL(true) ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -1271,11 +1606,11 @@ fn match_headers_with_min_type_matching_rules() { %check:exists ( $.headers['REF-ID'] => '1' ) => BOOL(true), - %match:min-type ( + %header:match-repeated ( + 'REF-ID' => 'REF-ID', ['1234', '4567'] => ['1234', '4567'], $.headers['REF-ID'] => '1', - json:{"min":2} => json:{"min":2}, - BOOL(false) => BOOL(false) + json:{"ref-id":{"combine":"AND","matchers":[{"match":"type","min":2}]}} => json:{"ref-id":{"combine":"AND","matchers":[{"match":"type","min":2}]}} ) => ERROR(Expected [1] \(size 1\) to have minimum size of 2), %error ( 'Expected header \'REF-ID\' but was missing' @@ -1709,3 +2044,35 @@ fn match_content_type_header() { ) "#, executed_plan.pretty_form()); } + +#[test] +fn repeated_header_cases_v2() { + let mut failures = vec![]; + for case in cases::all() { + let mut expected = HttpRequest { + headers: Some(hashmap! { + case.header.to_string() => case.expected.iter().map(|v| v.to_string()).collect() + }), + ..HttpRequest::default() + }; + expected.matching_rules.add_category("header").add_rules((case.rules)()); + let actual = HttpRequest { + headers: Some(hashmap! { + case.header.to_lowercase() => case.actual.iter().map(|v| v.to_string()).collect() + }), + ..HttpRequest::default() + }; + let context = PlanMatchingContext { + interaction: Box::new(SynchronousHttp { request: expected.clone(), ..SynchronousHttp::default() }), + ..PlanMatchingContext::default() + }; + + let plan = build_request_plan(&expected, &context).unwrap(); + let executed = execute_request_plan(&plan, &actual, &context).unwrap(); + let matched = executed.plan_root.result == Some(NodeResult::VALUE(NodeValue::BOOL(true))); + if matched != case.matches { + failures.push(format!("{}: matches != {}\n{}", case.name, case.matches, executed.pretty_form())); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index d7bfc4682..85b9db5a5 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -7,11 +7,12 @@ use itertools::Itertools; use maplit::hashmap; use pact_models::headers::PARAMETERISED_HEADERS; use pact_models::matchingrules::MatchingRule; -use pact_models::path_exp::DocPath; -use tracing::{instrument, debug}; +use pact_models::path_exp::{DocPath, PathToken}; +use tracing::{instrument, debug, warn}; use crate::{CommonMismatch, MatchingContext, Mismatch}; use crate::field_rules::FieldMatchScope; use crate::matchingrules::{compare_lists_with_matchingrules, DoMatch, match_values}; +use crate::repeated_headers::{header_kind, is_repeated, match_repeated_header, normalise_list, HeaderKind}; pub(crate) fn strip_whitespace<'a, T: FromIterator<&'a str>>(val: &'a str, split_by: &'a str) -> T { val.split(split_by).map(|v| v.trim()).filter(|v| !v.is_empty()).collect() @@ -103,13 +104,10 @@ pub(crate) fn match_header_value( } else if PARAMETERISED_HEADERS.contains(&key.to_lowercase().as_str()) { match_parameter_header(expected, actual, key, "header", index, single_value) } else { - // Normalize whitespace around commas for comparison, since RFC 7230 allows optional whitespace - // after commas in header values. This ensures "a,b" matches "a, b". - let normalize_comma_whitespace = |s: &str| -> String { - s.split(',').map(|v| v.trim()).collect::>().join(",") - }; - let normalized_expected = normalize_comma_whitespace(expected); - let normalized_actual = normalize_comma_whitespace(actual); + // RFC 9110 §5.6.1 allows optional whitespace around list commas, so "a,b" matches "a, b". Only commas + // that separate list elements in the header's grammar count, not ones inside a Link or a quoted string. + let normalized_expected = normalise_list(key, expected); + let normalized_actual = normalise_list(key, actual); MatchingRule::Equality.match_value(normalized_expected.as_str(), normalized_actual.as_str(), false, false) .map_err(|err| { if single_value { @@ -139,6 +137,58 @@ fn find_entry(map: &HashMap, key: &str) -> Option<(String, T)> whe } } +/// Compares the field lines one at a time: by index, or through the header's list matcher. +pub(crate) fn match_header_lines( + key: &str, + expected: &[String], + actual: &[String], + context: &dyn MatchingContext +) -> Vec { + let mut mismatches = vec![]; + + // Special case when the headers only have 1 value to improve messaging + if expected.len() == 1 && actual.len() == 1 { + let comparison_result = match_header_value(key, 0, expected.first().unwrap(), + actual.first().unwrap(), context, true) + .err() + .unwrap_or_default(); + mismatches.extend(comparison_result.iter().cloned()); + } else { + let path = DocPath::root().join(key.to_lowercase()); + if context.matcher_is_defined(&path) { + debug!("match_header_lines: Matcher is defined for path {}", path); + let values_result = compare_lists_with_matchingrules(&path, &context.select_best_matcher(&path), expected, actual, context.clone_with(context.matchers()).as_ref(), &mut |path, expected, actual, context| { + let index = match path.last() { Some(PathToken::Index(index)) => index, _ => 0 }; + match_header_value(key, index, expected, actual, context, false) + }); + mismatches.extend(values_result.err().unwrap_or_default()); + } else { + let empty = String::new(); + for (index, val) in expected.iter() + .pad_using(actual.len(), |_| &empty) + .enumerate() { + if let Some(actual_value) = actual.get(index) { + let comparison_result = match_header_value(key, index, val, + actual_value, context, false) + .err() + .unwrap_or_default(); + mismatches.extend(comparison_result.iter().cloned()); + } else { + mismatches.push(CommonMismatch { + path: key.to_string(), + expected: val.clone(), + actual: "".to_string(), + description: format!("Mismatch with header '{}': Expected value '{}' at index {} but was missing (actual has {} value(s))", + key, val, index, actual.len()) + }); + } + } + } + } + + mismatches +} + fn match_header_maps( expected: HashMap>, actual: HashMap>, @@ -153,46 +203,15 @@ fn match_header_maps( actual: format!("{}", actual_values.join(", ")), mismatch: format!("Expected an empty header '{}' but actual value was '{}'", key, actual_values.join(", ")) }]); } else { - let mut mismatches = vec![]; - - // Special case when the headers only have 1 value to improve messaging - if value.len() == 1 && actual_values.len() == 1 { - let comparison_result = match_header_value(key, 0, value.first().unwrap(), - actual_values.first().unwrap(), context, true) - .err() - .unwrap_or_default(); - mismatches.extend(comparison_result.iter().cloned()); - } else { - let path = DocPath::root().join(key.to_lowercase()); - if context.matcher_is_defined(&path) { - debug!("match_header_maps: Matcher is defined for path {}", path); - let values_result = compare_lists_with_matchingrules(&path, &context.select_best_matcher(&path), value, &actual_values, context.clone_with(context.matchers()).as_ref(), &mut |_, expected, actual, context| { - match_header_value(key, 0, expected, actual, context, false) - }); - mismatches.extend(values_result.err().unwrap_or_default()); - } else { - let empty = String::new(); - for (index, val) in value.iter() - .pad_using(actual_values.len(), |_| &empty) - .enumerate() { - if let Some(actual_value) = actual_values.get(index) { - let comparison_result = match_header_value(key, index, val, - actual_value, context, false) - .err() - .unwrap_or_default(); - mismatches.extend(comparison_result.iter().cloned()); - } else { - mismatches.push(CommonMismatch { - path: key.clone(), - expected: val.clone(), - actual: "".to_string(), - description: format!("Mismatch with header '{}': Expected value '{}' at index {} but was missing (actual has {} value(s))", - key, val, index, actual_values.len()) - }); - } - } + let mismatches = if header_kind(key) == HeaderKind::Custom && is_repeated(value, &actual_values) { + let result = match_repeated_header(key, value, &actual_values, context); + if let Some(warning) = &result.warning { + warn!("{}", warning); } - } + result.mismatches + } else { + match_header_lines(key, value, &actual_values, context) + }; result.insert(key.clone(), mismatches.iter().map(|mismatch| mismatch.to_header_mismatch()).collect()); }, @@ -235,9 +254,11 @@ mod tests { use pact_models::matchingrules::MatchingRule; use pact_models::matchingrules::expressions::{MatchingRuleDefinition, ValueType}; use pretty_assertions::assert_eq; + use rstest::rstest; use crate::{CoreMatchingContext, DiffConfig, HeaderMatchingContext, Mismatch, CommonMismatch}; use crate::headers::{match_header_value, match_headers, parse_charset_parameters}; + use crate::repeated_headers::{cases, header_kind, is_repeated, match_repeated_header, HeaderKind}; #[test] fn matching_headers_be_true_when_headers_are_equal() { @@ -565,6 +586,143 @@ mod tests { }); } + #[test] + fn match_headers_repeated_custom_header_matches_combined_field_line() { + let expected = Some(hashmap! { + "X-Request".to_string() => vec!["request1".to_string(), "request2".to_string()] + }); + let actual = Some(hashmap! { + "x-request".to_string() => vec!["request1, request2".to_string()] + }); + + let result = match_headers(expected, actual, &CoreMatchingContext::default()); + + assert!(result.values().all(Vec::is_empty), "{result:?}"); + } + + #[rstest( + case(&["request1", "request2"], &["request1,request2"], true), + case(&["request1", "request2"], &["request1 ,\t request2"], true), + case(&["request1", "request2"], &["request1", "request2"], true), + case(&["request1", "request2", "request3"], &["request1, request2", "request3"], true), + case(&["request1", "request2"], &["request1, wrong", "request2"], false), + case(&["request1", "request2"], &["request1", "wrong, request2"], false), + case(&["\"one,two\"", "three"], &["\"one,two\", three"], true), + case(&[r#""one\",two""#, "three"], &[r#""one\",two", three"#], true), + case(&[r#"{"foo":"bar,baz","arr":[1,2,3]}"#], &[r#"{"foo":"bar,baz","arr":[1,2,3]}"#], true), + case(&[r#"{"foo":"bar,baz","arr":[1,2,3]}"#, "tail"], &[r#"{"foo":"bar,baz","arr":[1,2,3]}, tail"#], true), + case(&["request1", "request2"], &["request1"], false), + case(&["request1", "request2"], &["request1, wrong"], false), + case(&["request1", "request2"], &["request2, request1"], false), + case(&["request1", "request2"], &["request1, request2, extra"], false), + case(&["request1", "request2"], &["\"request1, request2\""], false) + )] + fn match_headers_combined_custom_header_compatibility( + #[case] expected_values: &[&str], + #[case] actual_values: &[&str], + #[case] should_match: bool + ) { + let expected = Some(hashmap! { + "X-Request".to_string() => expected_values.iter().map(|value| value.to_string()).collect() + }); + let actual = Some(hashmap! { + "x-request".to_string() => actual_values.iter().map(|value| value.to_string()).collect() + }); + let result = match_headers(expected.clone(), actual.clone(), &CoreMatchingContext::default()); + assert_eq!(result.values().all(Vec::is_empty), should_match, + "expected={expected:?}, actual={actual:?}, result={result:?}"); + } + + #[test] + fn match_headers_combined_custom_header_preserves_indexed_matchers() { + let rules = matchingrules! { + "header" => { + "$.x-request.0" => [ MatchingRule::Regex("^first-[0-9]+$".to_string()) ], + "$.x-request.1" => [ MatchingRule::Regex("^second-[0-9]+$".to_string()) ] + } + }; + let context = CoreMatchingContext { + matchers: rules.rules_for_category("header").unwrap(), + ..CoreMatchingContext::default() + }; + for (actual_value, should_match) in [("first-42, second-99", true), ("first-42, first-99", false)] { + let expected = Some(hashmap! { + "X-Request".to_string() => vec!["first-1".to_string(), "second-2".to_string()] + }); + let actual = Some(hashmap! { + "x-request".to_string() => vec![actual_value.to_string()] + }); + let result = match_headers(expected, actual, &context); + assert_eq!(result.values().all(Vec::is_empty), should_match, "{result:?}"); + } + } + + #[test] + fn match_headers_does_not_split_parameterised_headers() { + let expected = Some(hashmap! { + "Content-Type".to_string() => vec!["text/plain".to_string(), "text/html".to_string()] + }); + let actual = Some(hashmap! { + "Content-Type".to_string() => vec!["text/plain, text/html".to_string()] + }); + let result = match_headers(expected, actual, &CoreMatchingContext::default()); + assert!(!result.values().all(Vec::is_empty), "{result:?}"); + } + + #[test] + fn repeated_header_cases_legacy() { + let mut failures = vec![]; + for case in cases::all() { + let expected_values: Vec = case.expected.iter().map(|v| v.to_string()).collect(); + let actual_values: Vec = case.actual.iter().map(|v| v.to_string()).collect(); + let context = CoreMatchingContext { + matchers: (case.rules)(), + ..CoreMatchingContext::default() + }; + let result = match_headers( + Some(hashmap! { case.header.to_string() => expected_values.clone() }), + Some(hashmap! { case.header.to_lowercase() => actual_values.clone() }), + &context + ); + if result.values().all(Vec::is_empty) != case.matches { + failures.push(format!("{}: matches != {}: {result:?}", case.name, case.matches)); + } + if is_repeated(&expected_values, &actual_values) && header_kind(case.header) == HeaderKind::Custom { + let repeated = match_repeated_header(case.header, &expected_values, &actual_values, &context); + if repeated.warning.is_some() != case.warns { + failures.push(format!("{}: warns != {}: {:?}", case.name, case.warns, repeated.warning)); + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); + } + + #[test] + fn match_headers_does_not_split_multi_value_headers() { + let expected = Some(hashmap! { + "Cache-Control".to_string() => vec!["no-cache".to_string(), "no-store".to_string()] + }); + let actual = Some(hashmap! { + "Cache-Control".to_string() => vec!["no-cache, no-store".to_string()] + }); + let result = match_headers(expected, actual, &CoreMatchingContext::default()); + assert!(!result.values().all(Vec::is_empty), "{result:?}"); + } + + #[test] + fn match_headers_does_not_split_single_value_headers() { + for header in ["Set-Cookie", "Date", "User-Agent"] { + let expected = Some(hashmap! { + header.to_string() => vec!["one".to_string(), "two".to_string()] + }); + let actual = Some(hashmap! { + header.to_string() => vec!["one, two".to_string()] + }); + let result = match_headers(expected, actual, &CoreMatchingContext::default()); + assert!(!result.values().all(Vec::is_empty), "{header}: {result:?}"); + } + } + #[test] fn match_headers_returns_a_mismatch_if_the_header_values_have_different_lengths() { let expected = Some(hashmap!{ @@ -580,9 +738,9 @@ mod tests { expect!(mismatches.len()).to(be_equal_to(1)); expect!(mismatches[0].clone()).to(be_equal_to(Mismatch::HeaderMismatch { key: "c".to_string(), - expected: "e".to_string(), - actual: "".to_string(), - mismatch: "Mismatch with header 'c': Expected value 'e' at index 1".to_string(), + expected: "d, e".to_string(), + actual: "d".to_string(), + mismatch: "Mismatch with header 'c': Expected 'd' to be equal to 'd, e'".to_string(), })); let expected = Some(hashmap!{ @@ -593,18 +751,12 @@ mod tests { }); let result = match_headers(expected, actual, &CoreMatchingContext::default()); let mismatches: Vec = result.values().flatten().cloned().collect(); - expect!(mismatches.len()).to(be_equal_to(2)); + expect!(mismatches.len()).to(be_equal_to(1)); expect!(mismatches[0].clone()).to(be_equal_to(Mismatch::HeaderMismatch { key: "c".to_string(), - expected: "d".to_string(), + expected: "d, e".to_string(), actual: "e".to_string(), - mismatch: "Mismatch with header 'c': Expected 'd' to be equal to 'e' for value at index 0".to_string(), - })); - expect!(mismatches[1].clone()).to(be_equal_to(Mismatch::HeaderMismatch { - key: "c".to_string(), - expected: "e".to_string(), - actual: "".to_string(), - mismatch: "Mismatch with header 'c': Expected value 'e' at index 1 but was missing (actual has 1 value(s))".to_string(), + mismatch: "Mismatch with header 'c': Expected 'e' to be equal to 'd, e'".to_string(), })); } @@ -733,6 +885,12 @@ mod tests { let mismatches: Vec = result.values().flatten().cloned().collect(); expect!(mismatches.clone()).to(be_equal_to(vec![ + Mismatch::HeaderMismatch { + key: "X-IMPROVED".to_string(), + expected: "like, regex, values, arrayContaining".to_string(), + actual: "regex, like, values, arrayContaining".to_string(), + mismatch: "Mismatch with header 'X-IMPROVED': Expected 'regex, like, values, arrayContaining' to be equal to 'like, regex, values, arrayContaining'".to_string(), + }, Mismatch::HeaderMismatch { key: "X-IMPROVED".to_string(), expected: "like".to_string(), @@ -777,6 +935,24 @@ mod tests { expect!(result.values().flatten()).to(be_empty()); } + #[test] + fn match_headers_with_array_contains_matcher_with_combined_field_lines() { + let context = HeaderMatchingContext::new(&CoreMatchingContext::new( + DiffConfig::AllowUnexpectedKeys, + &matchingrules! { + "header" => { + "X-Id" => [ + MatchingRule::ArrayContains(vec![]) + ] + } + }.rules_for_category("header").unwrap_or_default(), &hashmap!{} + )); + let expected = hashmap! { "X-Id".to_string() => vec!["1".to_string(), "3".to_string()] }; + let actual = hashmap! { "X-Id".to_string() => vec!["1, 2".to_string(), "3, 4".to_string()]}; + let result = match_headers(Some(expected), Some(actual), &context); + expect!(result.values().flatten()).to(be_empty()); + } + #[test] fn match_headers_with_array_contains_matcher_fails() { let context = HeaderMatchingContext::new(&CoreMatchingContext::new( @@ -822,6 +998,25 @@ mod tests { expect!(result.values().flatten()).to(be_empty()); } + #[test] + fn match_headers_with_each_value_matcher_with_combined_field_lines() { + let context = HeaderMatchingContext::new(&CoreMatchingContext::new( + DiffConfig::AllowUnexpectedKeys, + &matchingrules! { + "header" => { + "X-Id" => [ + MatchingRule::EachValue(MatchingRuleDefinition::new("100".to_string(), ValueType::String, + MatchingRule::Regex("^\\d+$".to_string()), None, "".to_string())) + ] + } + }.rules_for_category("header").unwrap_or_default(), &hashmap!{} + )); + let expected = hashmap! { "X-Id".to_string() => vec!["1".to_string(), "2".to_string()] }; + let actual = hashmap! { "X-Id".to_string() => vec!["3, 4".to_string(), "567".to_string()]}; + let result = match_headers(Some(expected), Some(actual), &context); + expect!(result.values().flatten()).to(be_empty()); + } + #[test] fn match_headers_with_each_value_matcher_fails() { let context = HeaderMatchingContext::new(&CoreMatchingContext::new( diff --git a/rust/pact_matching/src/lib.rs b/rust/pact_matching/src/lib.rs index c711c9faf..f4b32b531 100644 --- a/rust/pact_matching/src/lib.rs +++ b/rust/pact_matching/src/lib.rs @@ -431,6 +431,7 @@ pub mod headers; pub mod query; pub mod form_urlencoded; mod field_rules; +mod repeated_headers; use crate::field_rules::FieldMatchScope; #[cfg(feature = "plugins")] #[cfg(not(target_family = "wasm"))] mod plugin_support; #[cfg(feature = "plugins")] #[cfg(not(target_family = "wasm"))] mod core_capabilities; diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs new file mode 100644 index 000000000..2ae6dbc5e --- /dev/null +++ b/rust/pact_matching/src/repeated_headers.rs @@ -0,0 +1,592 @@ +//! Matching of headers whose values arrive over several field lines, or are combined into one. + +use itertools::Itertools; +use pact_models::headers::{MULTI_VALUE_HEADERS, PARAMETERISED_HEADERS, SINGLE_VALUE_HEADERS}; +use pact_models::matchingrules::MatchingRule; +use pact_models::matchingrules::expressions::{MatchingRuleDefinition, ValueType}; +use pact_models::path_exp::{DocPath, PathToken}; + +use crate::{CommonMismatch, MatchingContext}; +use crate::headers::match_header_lines; + +// MARK: Classification + +/// How a header's field lines may be combined and split. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum HeaderKind { + /// A value that may itself contain commas, so it is never split. + Singleton, + /// A comma-separated list whose members carry `;` parameters. + Parameterised, + /// A comma-separated list of plain tokens. + MultiValue, + /// Any header not named in the pact_models lists. + Custom, +} + +/// Classifies a header by name, ignoring case. A name in several lists takes the first of +/// `Singleton`, `Parameterised`, `MultiValue`. +pub(crate) fn header_kind(name: &str) -> HeaderKind { + let name = name.to_lowercase(); + let name = name.as_str(); + if SINGLE_VALUE_HEADERS.contains(&name) { + HeaderKind::Singleton + } else if PARAMETERISED_HEADERS.contains(&name) { + HeaderKind::Parameterised + } else if MULTI_VALUE_HEADERS.contains(&name) { + HeaderKind::MultiValue + } else { + HeaderKind::Custom + } +} + +// MARK: Repeated headers + +/// True when either side of a header has more than one field line. +pub(crate) fn is_repeated(expected: &[String], actual: &[String]) -> bool { + expected.len() > 1 || actual.len() > 1 +} + +/// Combines field lines into one value. RFC 9110 §5.3 makes repeated field lines equivalent +/// to a single line with the values joined by commas. +pub(crate) fn join_field_lines(values: &[String]) -> String { + values.join(", ") +} + +/// Delimiters inside which a comma does not separate list elements. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Grammar { + /// Only quoted strings protect a comma. + Plain, + /// `<…>` link targets protect a comma (RFC 8288 §3). + Link, + /// Nested `(…)` comments protect a comma (RFC 9110 §5.6.5). Quotes are ordinary text inside + /// a comment, and `\` escapes the next character. + Via +} + +impl Grammar { + fn for_header(name: &str) -> Grammar { + if name.eq_ignore_ascii_case("link") { + Grammar::Link + } else if name.eq_ignore_ascii_case("via") { + Grammar::Via + } else { + Grammar::Plain + } + } +} + +/// Splits a list value on commas outside quoted strings (RFC 9110 §5.6.4) and outside the +/// grammar's delimiters, trimming each element and dropping empty ones (RFC 9110 §5.6.1.2). +/// An unbalanced quote or delimiter extends to the end of the value. +fn list_elements(value: &str, grammar: Grammar) -> Vec<&str> { + let mut elements = vec![]; + let mut quoted = false; + let mut escaped = false; + let mut depth = 0usize; + let mut start = 0; + for (index, character) in value.char_indices() { + let in_comment = grammar == Grammar::Via && depth > 0; + if escaped { + escaped = false; + } else if (quoted || in_comment) && character == '\\' { + escaped = true; + } else if character == '"' && !in_comment { + quoted = !quoted; + } else if quoted { + continue; + } else if grammar == Grammar::Link && character == '<' { + depth = 1; + } else if grammar == Grammar::Link && character == '>' { + depth = 0; + } else if grammar == Grammar::Via && character == '(' { + depth += 1; + } else if grammar == Grammar::Via && character == ')' { + depth = depth.saturating_sub(1); + } else if character == ',' && depth == 0 { + elements.push(value[start..index].trim()); + start = index + 1; + } + } + elements.push(value[start..].trim()); + elements.retain(|element| !element.is_empty()); + elements +} + +/// Normalises a list value for comparison: whitespace around commas outside quoted strings +/// and the header's delimiters is dropped, as are empty elements. +pub(crate) fn normalise_list(name: &str, value: &str) -> String { + list_elements(value, Grammar::for_header(name)).join(",") +} + +/// Splits a header's field lines into its list elements. +pub(crate) fn split_list_elements(name: &str, values: &[String]) -> Vec { + let grammar = Grammar::for_header(name); + values.iter() + .flat_map(|value| list_elements(value, grammar)) + .map(str::to_string) + .collect() +} + +/// The outcome of matching a repeated header, with any warning to log. +#[derive(Debug, Clone, Default)] +pub(crate) struct RepeatedHeaderResult { + pub mismatches: Vec, + pub warning: Option +} + +fn rules_defined(key: &str, context: &dyn MatchingContext) -> bool { + let key = key.to_lowercase(); + context.matcher_is_defined(&DocPath::root().join(key.as_str())) || + context.matchers().rules.keys() + .any(|path| path.first_field().is_some_and(|field| field.to_lowercase() == key)) +} + +/// True for rules that apply to a header's list of values rather than to one value. +pub(crate) fn is_list_aware(rule: &MatchingRule) -> bool { + matches!(rule, + MatchingRule::MinType(_) | MatchingRule::MaxType(_) | MatchingRule::MinMaxType(_, _) | + MatchingRule::EachValue(_) | MatchingRule::ArrayContains(_)) +} + +fn per_line_warning(key: &str, joined_actual: &str) -> String { + format!("Header '{}' only matched when its field lines were compared one at a time. \ + Per-line matching of repeated headers is deprecated: RFC 9110 §5.3 treats repeated field lines as one line with the values joined by commas, \ + and a future release will compare only the joined value '{}'.", key, joined_actual) +} + +fn list_warning(key: &str, count: usize) -> String { + format!("Header '{}' only matched when its field lines were treated as whole values. \ + Matching repeated field lines as whole values is deprecated: RFC 9110 §5.3 treats them as one comma-joined list, \ + and a future release will split it into list elements (RFC 9110 §5.6.1), which gives {} elements here. \ + Quote values that contain commas, as RFC 9110 §5.5 advises, \ + e.g. Example-Dates: \"Sat, 04 May 1996\", \"Wed, 14 Sep 2005\".", key, count) +} + +fn is_header_path(path: &DocPath, key: &str) -> bool { + path.first_field().is_some_and(|field| field.to_lowercase() == key) +} + +/// The rules at the header's own path. +fn bare_rules(key: &str, context: &dyn MatchingContext) -> Vec { + let key = key.to_lowercase(); + context.matchers().rules.iter() + .filter(|(path, _)| path.len() == 2 && is_header_path(path, &key)) + .flat_map(|(_, list)| list.rules.iter().cloned()) + .collect() +} + +/// True when a rule sits at `$..` or `$.[]` for some `n < len`, or at +/// `$.[*]` or `$..*`, which address every element. +fn has_indexed_rule(key: &str, len: usize, context: &dyn MatchingContext) -> bool { + let key = key.to_lowercase(); + context.matchers().rules.keys() + .filter(|path| path.len() == 3 && is_header_path(path, &key)) + .any(|path| match path.tokens().last() { + Some(PathToken::Index(index)) => *index < len, + Some(PathToken::Field(field)) => field.parse::().is_ok_and(|index| index < len), + Some(PathToken::Star | PathToken::StarIndex) => len > 0, + _ => false + }) +} + +/// Matches a custom header where either side has more than one field line. +pub(crate) fn match_repeated_header( + key: &str, + expected: &[String], + actual: &[String], + context: &dyn MatchingContext +) -> RepeatedHeaderResult { + if rules_defined(key, context) { + let bare = bare_rules(key, context); + let elements = split_list_elements(key, actual); + if bare.iter().any(is_list_aware) || has_indexed_rule(key, expected.len().max(elements.len()), context) { + let primary = match_header_lines(key, expected, &elements, context); + if primary.is_empty() { + return RepeatedHeaderResult::default(); + } + if match_header_lines(key, expected, actual, context).is_empty() { + return RepeatedHeaderResult { mismatches: vec![], warning: Some(list_warning(key, elements.len())) }; + } + return RepeatedHeaderResult { mismatches: primary, warning: None }; + } + + let joined_actual = join_field_lines(actual); + let primary = match_header_lines(key, &[join_field_lines(expected)], std::slice::from_ref(&joined_actual), context); + if primary.is_empty() { + return RepeatedHeaderResult::default(); + } + let per_line = match_header_lines(key, expected, actual, context); + if per_line.is_empty() { + let warning = if bare.is_empty() { + per_line_warning(key, &joined_actual) + } else { + let each_value = bare.iter() + .map(|rule| MatchingRule::EachValue(MatchingRuleDefinition::new( + expected.first().cloned().unwrap_or_default(), ValueType::String, rule.clone(), None, String::new())).to_json().to_string()) + .join(", "); + format!("{} To match each value separately, use {} instead.", per_line_warning(key, &joined_actual), each_value) + }; + return RepeatedHeaderResult { mismatches: vec![], warning: Some(warning) }; + } + // The joined mismatch alone doesn't say which value failed, so report the per-line ones as well. + return RepeatedHeaderResult { mismatches: primary.into_iter().chain(per_line).collect(), warning: None }; + } + + let joined_expected = join_field_lines(expected); + let joined_actual = join_field_lines(actual); + if normalise_list(key, &joined_expected) == normalise_list(key, &joined_actual) { + RepeatedHeaderResult::default() + } else if match_header_lines(key, expected, actual, context).is_empty() { + RepeatedHeaderResult { + mismatches: vec![], + warning: Some(per_line_warning(key, &joined_actual)) + } + } else { + RepeatedHeaderResult { + mismatches: vec![CommonMismatch { + path: key.to_string(), + expected: joined_expected.clone(), + actual: joined_actual.clone(), + description: format!("Mismatch with header '{}': Expected '{}' to be equal to '{}'", + key, joined_actual, joined_expected) + }], + warning: None + } + } +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + + use pact_models::matchingrules::{MatchingRuleCategory, RuleLogic}; + use pact_models::path_exp::DocPath; + + use crate::CoreMatchingContext; + + use super::*; + + #[rstest] + #[case("Set-Cookie", HeaderKind::Singleton)] + #[case("user-agent", HeaderKind::Singleton)] + #[case("Content-Type", HeaderKind::Parameterised)] + #[case("Accept", HeaderKind::Parameterised)] + #[case("Cache-Control", HeaderKind::MultiValue)] + #[case("X-Request", HeaderKind::Custom)] + #[case("Link", HeaderKind::Custom)] + fn header_kind_classifies(#[case] name: &str, #[case] kind: HeaderKind) { + assert_eq!(header_kind(name), kind); + } + + #[test] + fn per_line_fallback_warns_of_deprecation() { + // An unbalanced quote runs to the end of the joined value, but not past the end of its own line. + let expected = vec!["\"a".to_string(), "b".to_string()]; + let actual = vec!["\"a ".to_string(), "b".to_string()]; + let result = match_repeated_header("X-Request", &expected, &actual, &CoreMatchingContext::default()); + assert!(result.mismatches.is_empty(), "{:?}", result.mismatches); + assert_eq!(result.warning.as_deref(), Some("Header 'X-Request' only matched when its field lines were \ + compared one at a time. Per-line matching of repeated headers is deprecated: RFC 9110 §5.3 treats \ + repeated field lines as one line with the values joined by commas, and a future release will compare \ + only the joined value '\"a , b'.")); + assert!(result.warning.unwrap().contains("deprecated")); + } + + #[test] + fn scalar_fallback_warning_suggests_each_value() { + let mut category = MatchingRuleCategory::empty("header"); + category.add_rule(DocPath::new_unwrap("$.x-request"), MatchingRule::Regex(r"^first-\d+$".to_string()), RuleLogic::And); + let context = CoreMatchingContext { matchers: category, ..CoreMatchingContext::default() }; + let expected = vec!["first-1".to_string(), "first-2".to_string()]; + let actual = vec!["first-42".to_string(), "first-99".to_string()]; + let result = match_repeated_header("X-Request", &expected, &actual, &context); + assert!(result.mismatches.is_empty(), "{:?}", result.mismatches); + let warning = result.warning.unwrap(); + assert!(warning.contains("RFC 9110 §5.3"), "{warning}"); + assert!(warning.contains("eachValue"), "{warning}"); + assert!(warning.contains("first-"), "{warning}"); + } + + #[test] + fn scalar_rule_mismatch_names_the_failing_value() { + // compatibility-suite V2 http_consumer "Supports matchers for repeated request headers (negative case)" + let mut category = MatchingRuleCategory::empty("header"); + category.add_rule(DocPath::new_unwrap("$.x-test"), MatchingRule::Regex(r"\d{1,4}".to_string()), RuleLogic::And); + let context = CoreMatchingContext { matchers: category, ..CoreMatchingContext::default() }; + let expected = vec!["1000".to_string()]; + let actual = vec!["1000".to_string(), "1234".to_string(), "9999ABC".to_string()]; + let result = match_repeated_header("X-Test", &expected, &actual, &context); + assert!(result.warning.is_none()); + assert!(result.mismatches.iter().any(|m| m.description.contains(r"Expected '9999ABC' to match '\d{1,4}'")), + "{:?}", result.mismatches); + } + + #[test] + fn scalar_rules_with_no_expected_lines_do_not_panic() { + let mut category = MatchingRuleCategory::empty("header"); + category.add_rule(DocPath::new_unwrap("$.x-request"), MatchingRule::Regex(r"^first-\d+$".to_string()), RuleLogic::And); + let context = CoreMatchingContext { matchers: category, ..CoreMatchingContext::default() }; + let actual = vec!["first-42".to_string(), "first-99".to_string()]; + let result = match_repeated_header("X-Request", &[], &actual, &context); + assert!(result.mismatches.is_empty(), "{:?}", result.mismatches); + assert!(result.warning.is_some()); + } + + #[rstest] + #[case(&["a, b", "c"], &["a", "b", "c"])] + #[case(&["a, , b,"], &["a", "b"])] + #[case(&[r#""one,two", three"#], &[r#""one,two""#, "three"])] + #[case(&[r#""one\",two", three"#], &[r#""one\",two""#, "three"])] + #[case(&[r#"{"a":1,"b":2}, x"#], &[r#"{"a":1"#, r#""b":2}"#, "x"])] + fn split_list_elements_splits_on_commas_outside_quotes(#[case] lines: &[&str], #[case] elements: &[&str]) { + let lines = lines.iter().map(|line| line.to_string()).collect_vec(); + assert_eq!(split_list_elements("X-Request", &lines), elements); + } + + #[test] + fn split_list_elements_keeps_an_unbalanced_quote_as_one_element() { + let lines = vec!["\"abc, def".to_string()]; + assert_eq!(split_list_elements("X-Request", &lines), vec!["\"abc, def"]); + } + + #[test] + fn split_list_elements_keeps_link_targets_whole() { + let lines = vec![r#"; rel="next", ; rel="last""#.to_string()]; + assert_eq!(split_list_elements("Link", &lines), vec![ + r#"; rel="next""#, + r#"; rel="last""# + ]); + assert_eq!(split_list_elements("LINK", &lines).len(), 2); + } + + #[test] + fn split_list_elements_keeps_via_comments_whole() { + let lines = vec!["1.1 proxy (Squid, v5), 1.0 fred".to_string()]; + assert_eq!(split_list_elements("Via", &lines), vec!["1.1 proxy (Squid, v5)", "1.0 fred"]); + assert_eq!(split_list_elements("via", &lines).len(), 2); + } + + #[test] + fn split_list_elements_nests_via_comments() { + let lines = vec!["1.1 a (x (y, z), w), 1.0 b".to_string()]; + assert_eq!(split_list_elements("Via", &lines), vec!["1.1 a (x (y, z), w)", "1.0 b"]); + } + + #[test] + fn split_list_elements_reads_brackets_literally_for_other_headers() { + let lines = vec!["(a, b)".to_string()]; + assert_eq!(split_list_elements("X-Request", &lines), vec!["(a", "b)"]); + let lines = vec!["".to_string()]; + assert_eq!(split_list_elements("X-Request", &lines), vec![""]); + assert_eq!(split_list_elements("Via", &["".to_string()]), vec![""]); + assert_eq!(split_list_elements("Link", &["(a, b)".to_string()]), vec!["(a", "b)"]); + } + + #[test] + fn split_list_elements_ignores_delimiters_inside_quotes() { + let lines = vec![r#"; title="x"#.to_string()]; + assert_eq!(split_list_elements("Link", &lines), vec![r#"; title="x"]); + let lines = vec![r#"1.1 a "x(", 1.0 b"#.to_string()]; + assert_eq!(split_list_elements("Via", &lines), vec![r#"1.1 a "x(""#, "1.0 b"]); + } + + #[test] + fn split_list_elements_treats_quotes_in_via_comments_as_text() { + let lines = vec![r#"1.1 a (the "best, proxy), 1.0 b"#.to_string()]; + assert_eq!(split_list_elements("Via", &lines), vec![r#"1.1 a (the "best, proxy)"#, "1.0 b"]); + } + + #[test] + fn split_list_elements_honours_quoted_pairs_in_via_comments() { + let lines = vec![r#"1.1 a (x \) y, z), 1.0 b"#.to_string()]; + assert_eq!(split_list_elements("Via", &lines), vec![r#"1.1 a (x \) y, z)"#, "1.0 b"]); + } + + #[test] + fn split_list_elements_keeps_an_unbalanced_delimiter_as_one_element() { + assert_eq!(split_list_elements("Link", &[" MatchingRuleCategory, + pub matches: bool, + pub warns: bool + } + + fn no_rules() -> MatchingRuleCategory { + MatchingRuleCategory::empty("header") + } + + const fn plain( + name: &'static str, + header: &'static str, + expected: &'static [&'static str], + actual: &'static [&'static str], + matches: bool, + warns: bool + ) -> Case { + Case { name, header, expected, actual, rules: no_rules, matches, warns } + } + + fn rule(path: &'static str, matcher: MatchingRule) -> MatchingRuleCategory { + let mut category = MatchingRuleCategory::empty("header"); + category.add_rule(DocPath::new_unwrap(path), matcher, RuleLogic::And); + category + } + + fn regex_joined() -> MatchingRuleCategory { rule("$.x-request", MatchingRule::Regex("^a, b$".to_string())) } + fn regex_first() -> MatchingRuleCategory { rule("$.x-request", MatchingRule::Regex(r"^first-\d+$".to_string())) } + fn regex_request() -> MatchingRuleCategory { rule("$.x-request", MatchingRule::Regex(r"^request\d$".to_string())) } + fn type_rule() -> MatchingRuleCategory { rule("$.x-request", MatchingRule::Type) } + fn each_value(path: &'static str, regex: &str) -> MatchingRuleCategory { + rule(path, MatchingRule::EachValue(MatchingRuleDefinition::new("1".into(), ValueType::String, + MatchingRule::Regex(regex.to_string()), None, String::new()))) + } + fn each_value_digits() -> MatchingRuleCategory { each_value("$.x-request", r"^\d+$") } + fn each_value_dates() -> MatchingRuleCategory { + each_value("$.x-sunset", r"^\w{3}, \d{2} \w{3} \d{4} \d{2}:\d{2}:\d{2} GMT$") + } + fn each_value_link() -> MatchingRuleCategory { each_value("$.link", r#"^<[^>]+>; rel="\w+"$"#) } + fn via_max_type() -> MatchingRuleCategory { rule("$.via", MatchingRule::MaxType(2)) } + fn min_type() -> MatchingRuleCategory { rule("$.x-request", MatchingRule::MinType(2)) } + fn max_type() -> MatchingRuleCategory { rule("$.x-request", MatchingRule::MaxType(2)) } + fn indexed() -> MatchingRuleCategory { + let mut category = rule("$.x-request.0", MatchingRule::Regex("^first-[0-9]+$".to_string())); + category.add_rule(DocPath::new_unwrap("$.x-request.1"), MatchingRule::Regex("^second-[0-9]+$".to_string()), RuleLogic::And); + category + } + + fn wildcard_regex() -> MatchingRuleCategory { rule("$.x-request[*]", MatchingRule::Regex(r"^\d+$".to_string())) } + + const SUNSET: &[&str] = &["Sat, 01 Mar 2025 00:00:00 GMT", "Sun, 01 Jun 2025 00:00:00 GMT"]; + const LINKS: &[&str] = &[r#"; rel="next""#, + r#"; rel="last""#]; + + pub(crate) fn all() -> Vec { + vec![ + Case { name: "regex joined, combined", header: "X-Request", expected: &["a", "b"], actual: &["a, b"], rules: regex_joined, matches: true, warns: false }, + Case { name: "regex joined, lines", header: "X-Request", expected: &["a", "b"], actual: &["a", "b"], rules: regex_joined, matches: true, warns: false }, + Case { name: "regex per-line fallback", header: "X-Request", expected: &["first-1", "first-2"], actual: &["first-42", "first-99"], rules: regex_first, matches: true, warns: true }, + Case { name: "regex combined fails", header: "X-Request", expected: &["first-1", "first-2"], actual: &["first-42, first-99"], rules: regex_first, matches: false, warns: false }, + Case { name: "regex one expected", header: "X-Request", expected: &["first-1"], actual: &["first-42", "first-99"], rules: regex_first, matches: true, warns: true }, + Case { name: "type", header: "X-Request", expected: &["a", "b"], actual: &["x, y, z"], rules: type_rule, matches: true, warns: false }, + Case { name: "each-value mixed", header: "X-Request", expected: &["1", "2"], actual: &["3, 4", "567"], rules: each_value_digits, matches: true, warns: false }, + Case { name: "each-value lines", header: "X-Request", expected: &["1", "2"], actual: &["3", "4", "567"], rules: each_value_digits, matches: true, warns: false }, + Case { name: "min-type combined", header: "X-Request", expected: &["a", "b"], actual: &["x, y"], rules: min_type, matches: true, warns: false }, + Case { name: "max-type fallback", header: "X-Request", expected: &["a", "b"], actual: &["x, y", "z"], rules: max_type, matches: true, warns: true }, + Case { name: "each-value dates fallback", header: "X-Sunset", expected: SUNSET, actual: SUNSET, rules: each_value_dates, matches: true, warns: true }, + Case { name: "each-value link", header: "Link", expected: LINKS, actual: LINKS, rules: each_value_link, matches: true, warns: false }, + Case { name: "each-value link combined", header: "Link", expected: LINKS, + actual: &[r#"; rel="next", ; rel="last""#], + rules: each_value_link, matches: true, warns: false }, + Case { name: "via max-type", header: "Via", expected: &["1.1 a", "1.1 b"], actual: &["1.1 proxy (Squid, v5), 1.0 fred"], rules: via_max_type, matches: true, warns: false }, + Case { name: "indexed combined", header: "X-Request", expected: &["first-1", "second-2"], actual: &["first-42, second-99"], rules: indexed, matches: true, warns: false }, + Case { name: "indexed wrong", header: "X-Request", expected: &["first-1", "second-2"], actual: &["first-42, first-99"], rules: indexed, matches: false, warns: false }, + Case { name: "wildcard regex combined", header: "X-Request", expected: &["1", "2"], actual: &["3, 4", "567"], rules: wildcard_regex, matches: true, warns: false }, + Case { name: "case mix", header: "X-Request", expected: &["request1", "request2"], actual: &["request1", "request2"], rules: regex_request, matches: true, warns: true }, + plain("combined line", "X-Request", &["request1", "request2"], &["request1, request2"], true, false), + plain("separate lines", "X-Request", &["request1", "request2"], &["request1", "request2"], true, false), + plain("mixed grouping", "X-Request", &["request1", "request2", "request3"], &["request1, request2", "request3"], true, false), + plain("no whitespace", "X-Request", &["request1", "request2"], &["request1,request2"], true, false), + plain("OWS both sides", "X-Request", &["request1", "request2"], &["request1 ,\t request2"], true, false), + plain("comma in value", "X-Request", &["a, b", "c"], &["a, b", "c"], true, false), + plain("dates", "X-Sunset", + &["Sat, 01 Mar 2025 00:00:00 GMT", "Sun, 01 Jun 2025 00:00:00 GMT"], + &["Sat, 01 Mar 2025 00:00:00 GMT", "Sun, 01 Jun 2025 00:00:00 GMT"], true, false), + plain("link", "Link", + &[r#"; rel="next""#, + r#"; rel="last""#], + &[r#"; rel="next""#, + r#"; rel="last""#], true, false), + plain("quoted comma", "X-Request", &["\"one,two\"", "three"], &["\"one,two\", three"], true, false), + plain("trailing comma", "X-Request", &["request1", "request2"], &["request1, request2,"], true, false), + plain("middle empty", "X-Request", &["request1", "request2"], &["request1, , request2"], true, false), + plain("one expected, two lines", "X-Request", &["request1, request2"], &["request1", "request2"], true, false), + plain("empty expected member", "X-Request", &["", "a"], &["a"], true, false), + plain("reversed", "X-Request", &["request1", "request2"], &["request2, request1"], false, false), + plain("extra member", "X-Request", &["request1", "request2"], &["request1, request2, extra"], false, false), + plain("missing member", "X-Request", &["request1", "request2"], &["request1"], false, false), + plain("quoted whole", "X-Request", &["request1", "request2"], &["\"request1, request2\""], false, false), + plain("quoted OWS", "X-Request", &["\"x , y\"", "z"], &["\"x, y\"", "z"], false, false), + plain("unbalanced quote fallback", "X-Request", &["\"a", "b"], &["\"a ", "b"], true, true), + plain("singleton untouched", "Set-Cookie", &["one", "two"], &["one, two"], false, false), + plain("singleton separate lines", "Set-Cookie", &["a=1; Path=/", "b=2; Expires=Sat, 01 Mar 2025 00:00:00 GMT"], + &["a=1; Path=/", "b=2; Expires=Sat, 01 Mar 2025 00:00:00 GMT"], true, false), + plain("link whitespace inside target", "Link", + &[r#"; rel="a""#, r#"; rel="b""#], + &[r#"; rel="a", ; rel="b""#], false, false), + plain("via comment whitespace", "Via", &["1.0 fred (a,b)", "1.1 p"], &["1.0 fred (a, b), 1.1 p"], false, false), + plain("single multi-value OWS", "Cache-Control", &["no-cache,no-store"], &["no-cache, no-store"], true, false), + plain("single multi-value quoted whitespace", "Cache-Control", &["private=\"x,y\""], &["private=\"x, y\""], false, false), + plain("single link whitespace inside target", "Link", + &[r#"; rel="a""#], &[r#"; rel="a""#], false, false), + plain("single quoted whitespace", "X-Request", &["\"x,y\""], &["\"x, y\""], false, false), + plain("single via comment whitespace", "Via", &["1.0 fred (a,b)"], &["1.0 fred (a, b)"], false, false) + ] + } +}