From 5385299bc5f1f54a99539b7fa2b156af4f83a446 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Fri, 16 Oct 2026 16:26:43 +0100 Subject: [PATCH 01/12] fix(matching): match combined headers against repeated expectations Normalize combined actual field lines during matching while preserving quoted commas, indexed matchers, singleton headers, and pact data. Add regression coverage for repeated custom header expectations. --- rust/pact_matching/src/headers.rs | 114 +++++++++++++++++++++++++++++- 1 file changed, 113 insertions(+), 1 deletion(-) diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index d7bfc4682..cc1e7bd37 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -5,7 +5,7 @@ use std::iter::FromIterator; use itertools::Itertools; use maplit::hashmap; -use pact_models::headers::PARAMETERISED_HEADERS; +use pact_models::headers::{PARAMETERISED_HEADERS, SINGLE_VALUE_HEADERS}; use pact_models::matchingrules::MatchingRule; use pact_models::path_exp::DocPath; use tracing::{instrument, debug}; @@ -139,6 +139,29 @@ fn find_entry(map: &HashMap, key: &str) -> Option<(String, T)> whe } } +fn split_header_field_lines(values: &[String]) -> Vec { + values.iter().flat_map(|value| { + let mut quoted = false; + let mut escaped = false; + let mut start = 0; + let mut members = vec![]; + for (index, character) in value.char_indices() { + if escaped { + escaped = false; + } else if quoted && character == '\\' { + escaped = true; + } else if character == '"' { + quoted = !quoted; + } else if character == ',' && !quoted { + members.push(value[start..index].trim().to_string()); + start = index + 1; + } + } + members.push(value[start..].trim().to_string()); + members + }).collect() +} + fn match_header_maps( expected: HashMap>, actual: HashMap>, @@ -154,6 +177,12 @@ fn match_header_maps( mismatch: format!("Expected an empty header '{}' but actual value was '{}'", key, actual_values.join(", ")) }]); } else { let mut mismatches = vec![]; + let actual_values = if value.len() > 1 && actual_values.len() < value.len() + && !SINGLE_VALUE_HEADERS.contains(&key.to_lowercase().as_str()) { + split_header_field_lines(&actual_values) + } else { + actual_values + }; // Special case when the headers only have 1 value to improve messaging if value.len() == 1 && actual_values.len() == 1 { @@ -565,6 +594,89 @@ 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:?}"); + } + + #[test] + fn match_headers_combined_custom_header_compatibility() { + let cases: &[(&[&str], &[&str], bool)] = &[ + (&["request1", "request2"], &["request1,request2"], true), + (&["request1", "request2"], &["request1 ,\t request2"], true), + (&["request1", "request2"], &["request1", "request2"], true), + (&["request1", "request2", "request3"], &["request1, request2", "request3"], true), + (&["\"one,two\"", "three"], &["\"one,two\", three"], true), + (&[r#""one\",two""#, "three"], &[r#""one\",two", three"#], true), + (&[r#"{"foo":"bar,baz","arr":[1,2,3]}"#], &[r#"{"foo":"bar,baz","arr":[1,2,3]}"#], true), + (&["request1", "request2"], &["request1"], false), + (&["request1", "request2"], &["request1, wrong"], false), + (&["request1", "request2"], &["request2, request1"], false), + (&["request1", "request2"], &["request1, request2, extra"], false), + (&["request1", "request2"], &["\"request1, request2\""], false), + ]; + for (expected_values, actual_values, should_match) in cases { + 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:?}"); + assert_eq!(expected.as_ref().unwrap()["X-Request"].len(), expected_values.len()); + assert_eq!(actual.as_ref().unwrap()["x-request"].len(), actual_values.len()); + } + } + + #[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_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!{ From 138fc4077b03992007b12c0479b7f6e4dd30cfae Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 19 Oct 2026 12:47:02 +0100 Subject: [PATCH 02/12] fix(matching): normalize repeated custom headers across engines Split combined custom-header values consistently for list matching, regardless of field-line grouping. Apply the same normalization in the V2 request and response plans while preserving quoted and JSON values, and add regression coverage. --- rust/pact_matching/src/engine/interpreter.rs | 29 ++++++- rust/pact_matching/src/engine/mod.rs | 16 +++- .../src/engine/tests/header_tests.rs | 56 ++++++++++--- rust/pact_matching/src/headers.rs | 80 +++++++++++-------- 4 files changed, 133 insertions(+), 48 deletions(-) diff --git a/rust/pact_matching/src/engine/interpreter.rs b/rust/pact_matching/src/engine/interpreter.rs index 62bfb323c..e5db8f592 100644 --- a/rust/pact_matching/src/engine/interpreter.rs +++ b/rust/pact_matching/src/engine/interpreter.rs @@ -20,7 +20,7 @@ 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::headers::{parse_charset_parameters, strip_whitespace}; +use crate::headers::{parse_charset_parameters, split_header_field_lines, strip_whitespace}; use crate::json::type_of; use crate::matchingrules::DoMatch; #[cfg(feature = "xml")] use crate::xml::resolve_attr_namespaces; @@ -321,6 +321,7 @@ 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:split-values" => self.execute_split_header_values(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), @@ -2547,6 +2548,32 @@ impl ExecutionPlanInterpreter { } } + fn execute_split_header_values( + &mut self, + value_resolver: &dyn ValueResolver, + node: ExecutionPlanNode, + action_path: &Vec + ) -> ExecutionPlanNode { + let ExecutionPlanNode { node_type, children, .. } = node; + let (result_children, values) = match self.evaluate_children(value_resolver, &node_type, children, action_path, true) { + Ok(value) => value, + Err(value) => return value + }; + let values = values.iter() + .flat_map(|value| match value.as_value().unwrap_or_default() { + NodeValue::STRING(value) => split_header_field_lines(&[value]), + NodeValue::SLIST(values) => split_header_field_lines(&values), + _ => vec![] + }) + .collect(); + + ExecutionPlanNode { + node_type, + result: Some(NodeResult::VALUE(NodeValue::SLIST(values))), + children: result_children + } + } + fn execute_for_each( &mut self, value_resolver: &dyn ValueResolver, diff --git a/rust/pact_matching/src/engine/mod.rs b/rust/pact_matching/src/engine/mod.rs index b4e343b6f..e9fc6170c 100644 --- a/rust/pact_matching/src/engine/mod.rs +++ b/rust/pact_matching/src/engine/mod.rs @@ -18,7 +18,7 @@ use serde_json::Value::Object; use tracing::debug; use pact_models::bodies::OptionalBody; use pact_models::content_types::TEXT; -use pact_models::headers::{MULTI_VALUE_HEADERS, PARAMETERISED_HEADERS}; +use pact_models::headers::{MULTI_VALUE_HEADERS, PARAMETERISED_HEADERS, SINGLE_VALUE_HEADERS}; use pact_models::json_utils::json_to_string; use pact_models::http_parts::HttpPart; use pact_models::matchingrules::{MatchingRule, RuleList, RuleLogic}; @@ -1989,11 +1989,21 @@ fn setup_header_plan( let item_path = DocPath::root().join(key); let path = doc_path.join(key); + let actual_value = if value.len() > 1 + && !SINGLE_VALUE_HEADERS.contains(&key.to_lowercase().as_str()) + && !PARAMETERISED_HEADERS.contains(&key.to_lowercase().as_str()) + && !MULTI_VALUE_HEADERS.contains(&key.to_lowercase().as_str()) { + let mut split_values = ExecutionPlanNode::action("header:split-values"); + split_values.add(ExecutionPlanNode::resolve_value(path.clone())); + split_values + } else { + 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, + &actual_value, &matchers, true, context.config.show_types_in_errors)); } else if PARAMETERISED_HEADERS.contains(&key.to_lowercase().as_str()) { item_node.add(ExecutionPlanNode::annotation(format!("{}={}", key, item_value.to_string()))); @@ -2031,7 +2041,7 @@ 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)); } diff --git a/rust/pact_matching/src/engine/tests/header_tests.rs b/rust/pact_matching/src/engine/tests/header_tests.rs index 3b4d1a805..a1e5f23da 100644 --- a/rust/pact_matching/src/engine/tests/header_tests.rs +++ b/rust/pact_matching/src/engine/tests/header_tests.rs @@ -3,12 +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; +#[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() { let expected = HttpRequest::default(); @@ -570,7 +596,9 @@ fn match_headers_with_values_having_different_lengths() { ), %match:equality ( ['test', 'test2'], - $.headers['REF-CODE'], + %header:split-values ( + $.headers['REF-CODE'] + ), NULL, BOOL(false) ), @@ -635,7 +663,9 @@ fn match_headers_with_values_having_different_lengths() { ) => BOOL(true), %match:equality ( ['test', 'test2'] => ['test', 'test2'], - $.headers['REF-CODE'] => ['test', 'test2'], + %header:split-values ( + $.headers['REF-CODE'] => ['test', 'test2'] + ) => ['test', 'test2'], NULL => NULL, BOOL(false) => BOOL(false) ) => BOOL(true), @@ -700,10 +730,12 @@ fn match_headers_with_values_having_different_lengths() { ) => BOOL(true), %match:equality ( ['test', 'test2'] => ['test', 'test2'], - $.headers['REF-CODE'] => 'test', + %header:split-values ( + $.headers['REF-CODE'] => 'test' + ) => ['test'], NULL => NULL, BOOL(false) => BOOL(false) - ) => ERROR(Expected 'test' to be equal to ['test', 'test2']), + ) => ERROR(Expected ['test'] to be equal to ['test', 'test2']), %error ( 'Expected header \'REF-CODE\' but was missing' ) @@ -1143,7 +1175,9 @@ fn match_headers_with_min_type_matching_rules() { ), %match:min-type ( ['1234', '4567'], - $.headers['REF-ID'], + %header:split-values ( + $.headers['REF-ID'] + ), json:{"min":2}, BOOL(false) ), @@ -1208,7 +1242,9 @@ fn match_headers_with_min_type_matching_rules() { ) => BOOL(true), %match:min-type ( ['1234', '4567'] => ['1234', '4567'], - $.headers['REF-ID'] => ['1', '1', '1'], + %header:split-values ( + $.headers['REF-ID'] => ['1', '1', '1'] + ) => ['1', '1', '1'], json:{"min":2} => json:{"min":2}, BOOL(false) => BOOL(false) ) => BOOL(true), @@ -1273,7 +1309,9 @@ fn match_headers_with_min_type_matching_rules() { ) => BOOL(true), %match:min-type ( ['1234', '4567'] => ['1234', '4567'], - $.headers['REF-ID'] => '1', + %header:split-values ( + $.headers['REF-ID'] => '1' + ) => ['1'], json:{"min":2} => json:{"min":2}, BOOL(false) => BOOL(false) ) => ERROR(Expected [1] \(size 1\) to have minimum size of 2), diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index cc1e7bd37..8fbcd7f57 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -139,10 +139,11 @@ fn find_entry(map: &HashMap, key: &str) -> Option<(String, T)> whe } } -fn split_header_field_lines(values: &[String]) -> Vec { +pub(crate) fn split_header_field_lines(values: &[String]) -> Vec { values.iter().flat_map(|value| { let mut quoted = false; let mut escaped = false; + let mut nested = 0usize; let mut start = 0; let mut members = vec![]; for (index, character) in value.char_indices() { @@ -152,7 +153,11 @@ fn split_header_field_lines(values: &[String]) -> Vec { escaped = true; } else if character == '"' { quoted = !quoted; - } else if character == ',' && !quoted { + } else if !quoted && (character == '{' || character == '[') { + nested += 1; + } else if !quoted && (character == '}' || character == ']') { + nested = nested.saturating_sub(1); + } else if character == ',' && !quoted && nested == 0 { members.push(value[start..index].trim().to_string()); start = index + 1; } @@ -177,7 +182,7 @@ fn match_header_maps( mismatch: format!("Expected an empty header '{}' but actual value was '{}'", key, actual_values.join(", ")) }]); } else { let mut mismatches = vec![]; - let actual_values = if value.len() > 1 && actual_values.len() < value.len() + let actual_values = if value.len() > 1 && !SINGLE_VALUE_HEADERS.contains(&key.to_lowercase().as_str()) { split_header_field_lines(&actual_values) } else { @@ -264,6 +269,7 @@ 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}; @@ -608,35 +614,39 @@ mod tests { assert!(result.values().all(Vec::is_empty), "{result:?}"); } - #[test] - fn match_headers_combined_custom_header_compatibility() { - let cases: &[(&[&str], &[&str], bool)] = &[ - (&["request1", "request2"], &["request1,request2"], true), - (&["request1", "request2"], &["request1 ,\t request2"], true), - (&["request1", "request2"], &["request1", "request2"], true), - (&["request1", "request2", "request3"], &["request1, request2", "request3"], true), - (&["\"one,two\"", "three"], &["\"one,two\", three"], true), - (&[r#""one\",two""#, "three"], &[r#""one\",two", three"#], true), - (&[r#"{"foo":"bar,baz","arr":[1,2,3]}"#], &[r#"{"foo":"bar,baz","arr":[1,2,3]}"#], true), - (&["request1", "request2"], &["request1"], false), - (&["request1", "request2"], &["request1, wrong"], false), - (&["request1", "request2"], &["request2, request1"], false), - (&["request1", "request2"], &["request1, request2, extra"], false), - (&["request1", "request2"], &["\"request1, request2\""], false), - ]; - for (expected_values, actual_values, should_match) in cases { - 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:?}"); - assert_eq!(expected.as_ref().unwrap()["X-Request"].len(), expected_values.len()); - assert_eq!(actual.as_ref().unwrap()["x-request"].len(), actual_values.len()); - } + #[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:?}"); + assert_eq!(expected.as_ref().unwrap()["X-Request"].len(), expected_values.len()); + assert_eq!(actual.as_ref().unwrap()["x-request"].len(), actual_values.len()); } #[test] @@ -884,7 +894,7 @@ mod tests { }.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".to_string(), "2".to_string(), "3".to_string(), "4".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()); } @@ -923,13 +933,13 @@ mod tests { "header" => { "X-Id" => [ MatchingRule::EachValue(MatchingRuleDefinition::new("100".to_string(), ValueType::String, - MatchingRule::Regex("\\d+".to_string()), None, "".to_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".to_string(), "4".to_string(), "567".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()); } From d034a0e631060366ee03ce140e914787d4b5adbf Mon Sep 17 00:00:00 2001 From: JP-Ellis Date: Tue, 20 Oct 2026 20:31:51 +1100 Subject: [PATCH 03/12] fix(matching): classify headers once for both engines The legacy matcher and the V2 plan builder each decided on their own which headers may be split on commas. Legacy split Content-Type and multi-value headers such as Cache-Control, while V2 skipped both, so the same pact verified differently depending on the engine. repeated_headers::header_kind now maps a header name to Singleton, Parameterised, MultiValue or Custom, using the lists in pact_models. Both engines split only Custom headers, which removes the Content-Type divergence: ["text/plain", "text/html"] no longer matches a single "text/plain, text/html" line in either engine. Tests pin that Content-Type and Cache-Control stay unsplit. Assisted-by: Claude Code:claude-opus-5-5 --- rust/pact_matching/src/engine/mod.rs | 8 ++-- rust/pact_matching/src/headers.rs | 30 ++++++++++-- rust/pact_matching/src/lib.rs | 1 + rust/pact_matching/src/repeated_headers.rs | 53 ++++++++++++++++++++++ 4 files changed, 84 insertions(+), 8 deletions(-) create mode 100644 rust/pact_matching/src/repeated_headers.rs diff --git a/rust/pact_matching/src/engine/mod.rs b/rust/pact_matching/src/engine/mod.rs index e9fc6170c..26760aefb 100644 --- a/rust/pact_matching/src/engine/mod.rs +++ b/rust/pact_matching/src/engine/mod.rs @@ -18,7 +18,7 @@ use serde_json::Value::Object; use tracing::debug; use pact_models::bodies::OptionalBody; use pact_models::content_types::TEXT; -use pact_models::headers::{MULTI_VALUE_HEADERS, PARAMETERISED_HEADERS, SINGLE_VALUE_HEADERS}; +use pact_models::headers::{MULTI_VALUE_HEADERS, PARAMETERISED_HEADERS}; use pact_models::json_utils::json_to_string; use pact_models::http_parts::HttpPart; use pact_models::matchingrules::{MatchingRule, RuleList, RuleLogic}; @@ -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, HeaderKind}; mod bodies; mod value_resolvers; @@ -1989,10 +1990,7 @@ fn setup_header_plan( let item_path = DocPath::root().join(key); let path = doc_path.join(key); - let actual_value = if value.len() > 1 - && !SINGLE_VALUE_HEADERS.contains(&key.to_lowercase().as_str()) - && !PARAMETERISED_HEADERS.contains(&key.to_lowercase().as_str()) - && !MULTI_VALUE_HEADERS.contains(&key.to_lowercase().as_str()) { + let actual_value = if value.len() > 1 && header_kind(key) == HeaderKind::Custom { let mut split_values = ExecutionPlanNode::action("header:split-values"); split_values.add(ExecutionPlanNode::resolve_value(path.clone())); split_values diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index 8fbcd7f57..6453e0270 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -5,13 +5,14 @@ use std::iter::FromIterator; use itertools::Itertools; use maplit::hashmap; -use pact_models::headers::{PARAMETERISED_HEADERS, SINGLE_VALUE_HEADERS}; +use pact_models::headers::PARAMETERISED_HEADERS; use pact_models::matchingrules::MatchingRule; use pact_models::path_exp::DocPath; use tracing::{instrument, debug}; 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, 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() @@ -182,8 +183,7 @@ fn match_header_maps( mismatch: format!("Expected an empty header '{}' but actual value was '{}'", key, actual_values.join(", ")) }]); } else { let mut mismatches = vec![]; - let actual_values = if value.len() > 1 - && !SINGLE_VALUE_HEADERS.contains(&key.to_lowercase().as_str()) { + let actual_values = if value.len() > 1 && header_kind(key) == HeaderKind::Custom { split_header_field_lines(&actual_values) } else { actual_values @@ -673,6 +673,30 @@ mod tests { } } + #[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 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"] { 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..e3f14bcb1 --- /dev/null +++ b/rust/pact_matching/src/repeated_headers.rs @@ -0,0 +1,53 @@ +//! Classification of headers for matching repeated expectations against combined field lines. + +use pact_models::headers::{MULTI_VALUE_HEADERS, PARAMETERISED_HEADERS, SINGLE_VALUE_HEADERS}; + +// 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 + } +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + + 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); + } +} From 681e989f552ed909b320cc14f979af9213173ef5 Mon Sep 17 00:00:00 2001 From: JP-Ellis Date: Tue, 20 Oct 2026 20:47:45 +1100 Subject: [PATCH 04/12] fix(matching): compare repeated custom headers by their joined value MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 9110 §5.3 makes repeated field lines equivalent to one line with the values joined by commas. A repeated custom header without matchers now joins both sides with ", " and compares the results, ignoring whitespace around commas outside quoted strings and empty list elements. Both engines share this logic through `match_repeated_header`. The previous change split only the actual field lines on commas. That broke repeated values that contain commas themselves: `["a, b", "c"]` against the same lines, two `X-Sunset` dates, or two `Link` lines whose URIs hold commas. Joining both sides keeps the combined, separate and mixed `X-Request` groupings matching. When the joined comparison fails, the header falls back to the per-line comparison it used before. A pass through the fallback logs a deprecation warning: per-line matching of repeated headers is deprecated, and a future release will compare only the joined value. A failed fallback reports one mismatch for the joined comparison. The legacy engine extracts the per-line body of `match_header_maps` into `match_header_lines`. The V2 plan replaces `header:split-values` with `header:match-repeated`. A custom header with one expected value gains a `header:repeated` check, so a single actual line keeps the existing plan node. Headers with matching rules keep the actual-only split until matchers move onto the joined value. Changed expectations: - `match_headers_returns_a_mismatch_if_the_header_values_have_different_lengths` now reports the joined mismatch (`Expected 'd' to be equal to 'd, e'`). - The V2 plan snapshots in `engine/tests/header_tests.rs` show the new actions. `match_headers_with_number_type_matching_rule` reports the legacy engine's matcher message for repeated actual lines. Assisted-by: Claude Code:claude-opus-5-5 --- rust/pact_matching/src/engine/interpreter.rs | 110 ++- rust/pact_matching/src/engine/mod.rs | 60 +- .../src/engine/tests/header_tests.rs | 693 +++++++++++++----- rust/pact_matching/src/headers.rs | 152 ++-- rust/pact_matching/src/repeated_headers.rs | 184 ++++- 5 files changed, 928 insertions(+), 271 deletions(-) diff --git a/rust/pact_matching/src/engine/interpreter.rs b/rust/pact_matching/src/engine/interpreter.rs index e5db8f592..7c3dba2ee 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::headers::{parse_charset_parameters, split_header_field_lines, strip_whitespace}; +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; #[cfg(feature = "xml")] use crate::xml::resolve_attr_namespaces; /// Main interpreter for the matching plan AST @@ -321,7 +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:split-values" => self.execute_split_header_values(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), @@ -2548,29 +2551,61 @@ impl ExecutionPlanInterpreter { } } - fn execute_split_header_values( + fn execute_header_repeated( &mut self, + action: &str, value_resolver: &dyn ValueResolver, node: ExecutionPlanNode, action_path: &Vec ) -> ExecutionPlanNode { let ExecutionPlanNode { node_type, children, .. } = node; - let (result_children, values) = match self.evaluate_children(value_resolver, &node_type, children, action_path, true) { - Ok(value) => value, - Err(value) => return value - }; - let values = values.iter() - .flat_map(|value| match value.as_value().unwrap_or_default() { - NodeValue::STRING(value) => split_header_field_lines(&[value]), - NodeValue::SLIST(values) => split_header_field_lines(&values), - _ => vec![] - }) - .collect(); + 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![] + } + } + } + } - ExecutionPlanNode { - node_type, - result: Some(NodeResult::VALUE(NodeValue::SLIST(values))), - children: result_children + 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![] + } + } } } @@ -2878,3 +2913,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 26760aefb..742111de1 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; @@ -1962,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 { + 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 @@ -1990,19 +2033,14 @@ fn setup_header_plan( let item_path = DocPath::root().join(key); let path = doc_path.join(key); - let actual_value = if value.len() > 1 && header_kind(key) == HeaderKind::Custom { - let mut split_values = ExecutionPlanNode::action("header:split-values"); - split_values.add(ExecutionPlanNode::resolve_value(path.clone())); - split_values - } else { - ExecutionPlanNode::resolve_value(path.clone()) - }; + 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), + let match_node = build_matching_rule_node(&ExecutionPlanNode::value_node(item_value), &actual_value, &matchers, true, - context.config.show_types_in_errors)); + 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 { @@ -2043,7 +2081,7 @@ fn setup_header_plan( .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 a1e5f23da..12f586732 100644 --- a/rust/pact_matching/src/engine/tests/header_tests.rs +++ b/rust/pact_matching/src/engine/tests/header_tests.rs @@ -11,6 +11,7 @@ use crate::engine::{ 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() { @@ -88,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' @@ -130,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' @@ -177,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' @@ -224,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' ) @@ -272,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' @@ -319,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' @@ -385,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' @@ -402,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' @@ -450,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' @@ -467,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' @@ -515,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' @@ -532,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' ) @@ -594,13 +727,11 @@ fn match_headers_with_values_having_different_lengths() { %check:exists ( $.headers['REF-CODE'] ), - %match:equality ( + %header:match-repeated ( + 'REF-CODE', ['test', 'test2'], - %header:split-values ( - $.headers['REF-CODE'] - ), - NULL, - BOOL(false) + $.headers['REF-CODE'], + json:{} ), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -613,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' @@ -661,13 +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'], - %header:split-values ( - $.headers['REF-CODE'] => ['test', 'test2'] - ) => ['test', 'test2'], - NULL => NULL, - BOOL(false) => BOOL(false) + $.headers['REF-CODE'] => ['test', 'test2'], + json:{} => json:{} ) => BOOL(true), %error ( 'Expected header \'REF-CODE\' but was missing' @@ -680,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' @@ -728,14 +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'], - %header:split-values ( - $.headers['REF-CODE'] => 'test' - ) => ['test'], - NULL => NULL, - BOOL(false) => BOOL(false) - ) => ERROR(Expected ['test'] to be equal to ['test', 'test2']), + $.headers['REF-CODE'] => 'test', + json:{} => json:{} + ) => ERROR(Mismatch with header 'REF-CODE': Expected 'test' to be equal to 'test, test2'), %error ( 'Expected header \'REF-CODE\' but was missing' ) @@ -747,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' ) @@ -813,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' @@ -830,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' @@ -878,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' @@ -895,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' @@ -943,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' @@ -960,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' ) @@ -1008,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' @@ -1025,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' @@ -1073,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' @@ -1090,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 'two' to match an integer number for value at index 0), + %match:integer ( + '1234', + $.headers['REF-ID'], + json:{}, + BOOL(false) + ) + ) => BOOL(false), %error ( 'Expected header \'REF-ID\' but was missing' ) @@ -1156,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' @@ -1173,13 +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'], - %header:split-values ( - $.headers['REF-ID'] - ), - json:{"min":2}, - BOOL(false) + $.headers['REF-ID'], + json:{"ref-id":{"combine":"AND","matchers":[{"match":"type","min":2}]}} ), %error ( 'Expected header \'REF-ID\' but was missing' @@ -1223,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' @@ -1240,13 +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'], - %header:split-values ( - $.headers['REF-ID'] => ['1', '1', '1'] - ) => ['1', '1', '1'], - json:{"min":2} => json:{"min":2}, - BOOL(false) => BOOL(false) + $.headers['REF-ID'] => ['1', '1', '1'], + 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' @@ -1290,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' @@ -1307,13 +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'], - %header:split-values ( - $.headers['REF-ID'] => '1' - ) => ['1'], - json:{"min":2} => json:{"min":2}, - BOOL(false) => BOOL(false) + $.headers['REF-ID'] => '1', + 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' @@ -1747,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 6453e0270..9a28e34ee 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -8,11 +8,11 @@ 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 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, HeaderKind}; +use crate::repeated_headers::{header_kind, is_repeated, match_repeated_header, 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() @@ -168,6 +168,57 @@ pub(crate) fn split_header_field_lines(values: &[String]) -> Vec { }).collect() } +/// 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 |_, 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 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>, @@ -182,52 +233,16 @@ 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![]; - let actual_values = if value.len() > 1 && header_kind(key) == HeaderKind::Custom { - split_header_field_lines(&actual_values) + 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 { - actual_values + match_header_lines(key, value, &actual_values, context) }; - // 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()) - }); - } - } - } - } - result.insert(key.clone(), mismatches.iter().map(|mismatch| mismatch.to_header_mismatch()).collect()); }, None => { @@ -273,6 +288,7 @@ mod tests { 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() { @@ -685,6 +701,34 @@ mod tests { 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! { @@ -726,9 +770,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!{ @@ -739,18 +783,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(), })); } diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index e3f14bcb1..7f4f88000 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -1,6 +1,11 @@ -//! Classification of headers for matching repeated expectations against combined field lines. +//! 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::path_exp::DocPath; + +use crate::{CommonMismatch, MatchingContext}; +use crate::headers::{match_header_lines, split_header_field_lines}; // MARK: Classification @@ -33,10 +38,102 @@ pub(crate) fn header_kind(name: &str) -> HeaderKind { } } +// 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(", ") +} + +/// Normalises a list value for comparison: whitespace around commas outside quoted strings +/// is dropped, as are empty elements (RFC 9110 §5.6.1.2). +pub(crate) fn normalise_list(value: &str) -> String { + let mut elements = vec![]; + let mut quoted = false; + let mut escaped = false; + let mut start = 0; + for (index, character) in value.char_indices() { + if escaped { + escaped = false; + } else if quoted && character == '\\' { + escaped = true; + } else if character == '"' { + quoted = !quoted; + } else if character == ',' && !quoted { + elements.push(value[start..index].trim()); + start = index + 1; + } + } + elements.push(value[start..].trim()); + elements.iter().filter(|element| !element.is_empty()).join(",") +} + +/// 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)) +} + +/// 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 actual = if expected.len() > 1 { split_header_field_lines(actual) } else { actual.to_vec() }; + return RepeatedHeaderResult { + mismatches: match_header_lines(key, expected, &actual, context), + warning: None + }; + } + + let joined_expected = join_field_lines(expected); + let joined_actual = join_field_lines(actual); + if normalise_list(&joined_expected) == normalise_list(&joined_actual) { + RepeatedHeaderResult::default() + } else if match_header_lines(key, expected, actual, context).is_empty() { + RepeatedHeaderResult { + mismatches: vec![], + warning: Some(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)) + } + } 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 crate::CoreMatchingContext; + use super::*; #[rstest] @@ -50,4 +147,89 @@ mod tests { fn header_kind_classifies(#[case] name: &str, #[case] kind: HeaderKind) { assert_eq!(header_kind(name), kind); } + + #[test] + fn per_line_fallback_warns_of_deprecation() { + let expected = vec!["\"x , y\"".to_string(), "z".to_string()]; + let actual = vec!["\"x, y\"".to_string(), "z".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 '\"x, y\", z'.")); + assert!(result.warning.unwrap().contains("deprecated")); + } + + #[rstest] + #[case("a, b", "a,b")] + #[case(" a ,\t b ", "a,b")] + #[case("a, , b,", "a,b")] + #[case(r#""x , y", z"#, r#""x , y",z"#)] + #[case(r#""x\", y", z"#, r#""x\", y",z"#)] + #[case("", "")] + fn normalise_list_ignores_whitespace_and_empty_elements_outside_quotes(#[case] value: &str, #[case] normalised: &str) { + assert_eq!(normalise_list(value), normalised); + } +} + +#[cfg(test)] +pub(crate) mod cases { + use pact_models::matchingrules::MatchingRuleCategory; + + /// One repeated-header scenario, run against both engines. + pub(crate) struct Case { + pub name: &'static str, + pub header: &'static str, + pub expected: &'static [&'static str], + pub actual: &'static [&'static str], + pub rules: fn() -> 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 } + } + + pub(crate) fn all() -> Vec { + vec![ + 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 fallback", "X-Request", &["\"x , y\"", "z"], &["\"x, y\"", "z"], true, true), + plain("singleton untouched", "Set-Cookie", &["one", "two"], &["one, two"], false, false) + ] + } } From 4ad5158a676064debb404b2dd16240a778b2bdea Mon Sep 17 00:00:00 2001 From: JP-Ellis Date: Tue, 20 Oct 2026 20:57:21 +1100 Subject: [PATCH 05/12] fix(matching): apply scalar header matchers to the joined value MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A repeated custom header with scalar matchers (Regex, Type, Integer and the like) on its own path is now matched as RFC 9110 §5.3 describes it: the expected and actual field lines are joined with commas and the matchers run once against each joined value. List-aware rules (MinType, MaxType, MinMaxType, EachValue, ArrayContains) and headers with indexed rules go through the actual-only split_header_field_lines, with no fallback, until the list-element commit. When the joined value fails but the field lines pass one at a time, the header still matches and logs the per-line deprecation warning. The warning also suggests wrapping the user's rule in EachValue, rendered as JSON, as the way to keep per-value matching once only the joined value is compared. Two existing expectations change under the joined semantics, and the mismatch now describes the joined value instead of one line: - engine header_tests match_headers_with_number_type_matching_rule: "Expected '1111, two' to match an integer number". - headers::tests::match_header_with_a_values_matcher: a Values rule is not list-aware, so a reordered list reports one mismatch between the two joined values. A header whose expected list is empty skips the repeated-header node in the V2 plan and the matcher tolerates an empty expected list, so it cannot panic. Assisted-by: Claude Code:claude-opus-5-5 --- rust/pact_matching/src/engine/mod.rs | 2 +- .../src/engine/tests/header_tests.rs | 2 +- rust/pact_matching/src/headers.rs | 12 +- rust/pact_matching/src/repeated_headers.rs | 107 +++++++++++++++++- 4 files changed, 108 insertions(+), 15 deletions(-) diff --git a/rust/pact_matching/src/engine/mod.rs b/rust/pact_matching/src/engine/mod.rs index 742111de1..312adb76d 100644 --- a/rust/pact_matching/src/engine/mod.rs +++ b/rust/pact_matching/src/engine/mod.rs @@ -1971,7 +1971,7 @@ fn build_custom_header_node( match_node: ExecutionPlanNode, context: &PlanMatchingContext ) -> ExecutionPlanNode { - if header_kind(key) != HeaderKind::Custom { + if header_kind(key) != HeaderKind::Custom || expected.is_empty() { return match_node; } diff --git a/rust/pact_matching/src/engine/tests/header_tests.rs b/rust/pact_matching/src/engine/tests/header_tests.rs index 12f586732..632fb0537 100644 --- a/rust/pact_matching/src/engine/tests/header_tests.rs +++ b/rust/pact_matching/src/engine/tests/header_tests.rs @@ -1358,7 +1358,7 @@ fn match_headers_with_number_type_matching_rule() { ['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 'two' to match an integer number for value at index 0), + ) => ERROR(Mismatch with header 'REF-ID': Expected '1111, two' to match an integer number), %match:integer ( '1234', $.headers['REF-ID'], diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index 9a28e34ee..5e6cbe504 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -919,15 +919,9 @@ mod tests { expect!(mismatches.clone()).to(be_equal_to(vec![ Mismatch::HeaderMismatch { key: "X-IMPROVED".to_string(), - expected: "like".to_string(), - actual: "regex".to_string(), - mismatch: "Mismatch with header 'X-IMPROVED': Expected 'regex' to be equal to 'like' for value at index 0".to_string(), - }, - Mismatch::HeaderMismatch { - key: "X-IMPROVED".to_string(), - expected: "regex".to_string(), - actual: "like".to_string(), - mismatch: "Mismatch with header 'X-IMPROVED': Expected 'like' to be equal to 'regex' for value at index 1".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(), } ])); diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index 7f4f88000..4085836cd 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -2,6 +2,8 @@ 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; use crate::{CommonMismatch, MatchingContext}; @@ -88,6 +90,36 @@ fn rules_defined(key: &str, context: &dyn MatchingContext) -> bool { .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) +} + +/// The rules at the header's own path, and whether any rule sits at an indexed path below it. +fn header_rules(key: &str, context: &dyn MatchingContext) -> (Vec, bool) { + let key = key.to_lowercase(); + let mut bare = vec![]; + let mut indexed = false; + for (path, list) in &context.matchers().rules { + if path.first_field().is_some_and(|field| field.to_lowercase() == key) { + if path.len() > 2 { + indexed = true; + } else { + bare.extend(list.rules.iter().cloned()); + } + } + } + (bare, indexed) +} + /// Matches a custom header where either side has more than one field line. pub(crate) fn match_repeated_header( key: &str, @@ -96,6 +128,27 @@ pub(crate) fn match_repeated_header( context: &dyn MatchingContext ) -> RepeatedHeaderResult { if rules_defined(key, context) { + let (bare, indexed) = header_rules(key, context); + if !bare.is_empty() && !indexed && !bare.iter().any(is_list_aware) { + 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(); + } + if match_header_lines(key, expected, actual, context).is_empty() { + 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(", "); + return RepeatedHeaderResult { + mismatches: vec![], + warning: Some(format!("{} To match each value separately, use {} instead.", + per_line_warning(key, &joined_actual), each_value)) + }; + } + return RepeatedHeaderResult { mismatches: primary, warning: None }; + } + let actual = if expected.len() > 1 { split_header_field_lines(actual) } else { actual.to_vec() }; return RepeatedHeaderResult { mismatches: match_header_lines(key, expected, &actual, context), @@ -110,9 +163,7 @@ pub(crate) fn match_repeated_header( } else if match_header_lines(key, expected, actual, context).is_empty() { RepeatedHeaderResult { mismatches: vec![], - warning: Some(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)) + warning: Some(per_line_warning(key, &joined_actual)) } } else { RepeatedHeaderResult { @@ -132,6 +183,9 @@ pub(crate) fn match_repeated_header( mod tests { use rstest::rstest; + use pact_models::matchingrules::{MatchingRuleCategory, RuleLogic}; + use pact_models::path_exp::DocPath; + use crate::CoreMatchingContext; use super::*; @@ -161,6 +215,32 @@ mod tests { 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_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", "a,b")] #[case(" a ,\t b ", "a,b")] @@ -175,7 +255,8 @@ mod tests { #[cfg(test)] pub(crate) mod cases { - use pact_models::matchingrules::MatchingRuleCategory; + use pact_models::matchingrules::{MatchingRule, MatchingRuleCategory, RuleLogic}; + use pact_models::path_exp::DocPath; /// One repeated-header scenario, run against both engines. pub(crate) struct Case { @@ -203,8 +284,26 @@ pub(crate) mod cases { 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) } + 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: "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), From 139bb9db64e5641a8e67e25fd468879ffb4d865b Mon Sep 17 00:00:00 2001 From: JP-Ellis Date: Tue, 20 Oct 2026 21:08:29 +1100 Subject: [PATCH 06/12] fix(matching): split repeated headers into list elements for list matchers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit List-aware matchers (MinType, MaxType, MinMaxType, EachValue, ArrayContains) and index-specific matchers now see the list elements of a repeated custom header. The elements come from the joined actual value, so `3, 4` / `567` and `3` / `4` / `567` both give three elements. The splitter honours RFC 9110 §5.6.4: commas inside quoted strings do not separate elements, and `\` escapes inside quotes are respected. It trims each element and drops empty ones (§5.6.1). It has no `{}` or `[]` nesting, so a JSON-looking value splits at its commas like any other. `normalise_list` shares the same tokenizer. An indexed matcher triggers the split when it sits at `$..` or `$.[]` with `n` below the larger of the expected count and the element count. Wildcard element rules at `$.[*]` or `$..*` address every element, so they count as list rules too. This replaces a bare path-length check that caught any deeper path. When the element match fails, the matcher retries over the field lines as received, which is the old behaviour. A pass there logs a warning. The warning says whole-line matching is deprecated, gives the element count a future release will see, and points at RFC 9110 §5.5's advice to quote values that contain commas. This keeps MaxType(2) against `x, y` / `z`, and EachValue over unquoted dates or Link values, passing. The PR's interim `split_header_field_lines`, which tracked brace and bracket nesting, is removed. No existing test expectation changed: the JSON-valued compatibility cases carry no rules, so they still go through plain comparison. Assisted-by: Claude Code:claude-opus-5-5 --- rust/pact_matching/src/headers.rs | 28 --- rust/pact_matching/src/repeated_headers.rs | 199 +++++++++++++++++---- 2 files changed, 162 insertions(+), 65 deletions(-) diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index 5e6cbe504..632bb0499 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -140,34 +140,6 @@ fn find_entry(map: &HashMap, key: &str) -> Option<(String, T)> whe } } -pub(crate) fn split_header_field_lines(values: &[String]) -> Vec { - values.iter().flat_map(|value| { - let mut quoted = false; - let mut escaped = false; - let mut nested = 0usize; - let mut start = 0; - let mut members = vec![]; - for (index, character) in value.char_indices() { - if escaped { - escaped = false; - } else if quoted && character == '\\' { - escaped = true; - } else if character == '"' { - quoted = !quoted; - } else if !quoted && (character == '{' || character == '[') { - nested += 1; - } else if !quoted && (character == '}' || character == ']') { - nested = nested.saturating_sub(1); - } else if character == ',' && !quoted && nested == 0 { - members.push(value[start..index].trim().to_string()); - start = index + 1; - } - } - members.push(value[start..].trim().to_string()); - members - }).collect() -} - /// 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, diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index 4085836cd..d396d4717 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -4,10 +4,10 @@ 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; +use pact_models::path_exp::{DocPath, PathToken}; use crate::{CommonMismatch, MatchingContext}; -use crate::headers::{match_header_lines, split_header_field_lines}; +use crate::headers::match_header_lines; // MARK: Classification @@ -53,9 +53,9 @@ pub(crate) fn join_field_lines(values: &[String]) -> String { values.join(", ") } -/// Normalises a list value for comparison: whitespace around commas outside quoted strings -/// is dropped, as are empty elements (RFC 9110 §5.6.1.2). -pub(crate) fn normalise_list(value: &str) -> String { +/// Splits a list value on commas outside quoted strings (RFC 9110 §5.6.4), trimming each +/// element and dropping empty ones (RFC 9110 §5.6.1.2). +fn list_elements(value: &str) -> Vec<&str> { let mut elements = vec![]; let mut quoted = false; let mut escaped = false; @@ -73,7 +73,22 @@ pub(crate) fn normalise_list(value: &str) -> String { } } elements.push(value[start..].trim()); - elements.iter().filter(|element| !element.is_empty()).join(",") + elements.retain(|element| !element.is_empty()); + elements +} + +/// Normalises a list value for comparison: whitespace around commas outside quoted strings +/// is dropped, as are empty elements. +pub(crate) fn normalise_list(value: &str) -> String { + list_elements(value).join(",") +} + +/// Splits a header's field lines into its list elements. +pub(crate) fn split_list_elements(_name: &str, values: &[String]) -> Vec { + values.iter() + .flat_map(|value| list_elements(value)) + .map(str::to_string) + .collect() } /// The outcome of matching a repeated header, with any warning to log. @@ -103,21 +118,39 @@ fn per_line_warning(key: &str, joined_actual: &str) -> String { and a future release will compare only the joined value '{}'.", key, joined_actual) } -/// The rules at the header's own path, and whether any rule sits at an indexed path below it. -fn header_rules(key: &str, context: &dyn MatchingContext) -> (Vec, bool) { +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(); - let mut bare = vec![]; - let mut indexed = false; - for (path, list) in &context.matchers().rules { - if path.first_field().is_some_and(|field| field.to_lowercase() == key) { - if path.len() > 2 { - indexed = true; - } else { - bare.extend(list.rules.iter().cloned()); - } - } - } - (bare, indexed) + 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. @@ -128,32 +161,37 @@ pub(crate) fn match_repeated_header( context: &dyn MatchingContext ) -> RepeatedHeaderResult { if rules_defined(key, context) { - let (bare, indexed) = header_rules(key, context); - if !bare.is_empty() && !indexed && !bare.iter().any(is_list_aware) { - let joined_actual = join_field_lines(actual); - let primary = match_header_lines(key, &[join_field_lines(expected)], std::slice::from_ref(&joined_actual), 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(); + } + if match_header_lines(key, expected, actual, context).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(", "); - return RepeatedHeaderResult { - mismatches: vec![], - warning: Some(format!("{} To match each value separately, use {} instead.", - per_line_warning(key, &joined_actual), each_value)) - }; - } - return RepeatedHeaderResult { mismatches: primary, warning: None }; + format!("{} To match each value separately, use {} instead.", per_line_warning(key, &joined_actual), each_value) + }; + return RepeatedHeaderResult { mismatches: vec![], warning: Some(warning) }; } - - let actual = if expected.len() > 1 { split_header_field_lines(actual) } else { actual.to_vec() }; - return RepeatedHeaderResult { - mismatches: match_header_lines(key, expected, &actual, context), - warning: None - }; + return RepeatedHeaderResult { mismatches: primary, warning: None }; } let joined_expected = join_field_lines(expected); @@ -241,6 +279,61 @@ mod tests { 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_multibyte_characters_next_to_commas() { + let lines = vec!["é,ü".to_string(), "ß".to_string()]; + assert_eq!(split_list_elements("X-Request", &lines), vec!["é", "ü", "ß"]); + } + + #[test] + fn list_fallback_warns_of_deprecation() { + let mut category = MatchingRuleCategory::empty("header"); + category.add_rule(DocPath::new_unwrap("$.x-request"), MatchingRule::MaxType(2), RuleLogic::And); + let context = CoreMatchingContext { matchers: category, ..CoreMatchingContext::default() }; + let expected = vec!["a".to_string(), "b".to_string()]; + let actual = vec!["x, y".to_string(), "z".to_string()]; + let result = match_repeated_header("X-Request", &expected, &actual, &context); + assert!(result.mismatches.is_empty(), "{:?}", result.mismatches); + assert_eq!(result.warning.as_deref(), Some("Header 'X-Request' 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 3 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\".")); + } + + #[rstest] + #[case("$.x-request", false)] + #[case("$.x-request.1", true)] + #[case("$.x-request[1]", true)] + #[case("$.x-request[2]", false)] + #[case("$.x-request[*]", true)] + #[case("$.x-request.*", true)] + #[case("$.x-request.foo", false)] + #[case("$.x-other[0]", false)] + fn indexed_rules_need_an_index_within_the_list(#[case] path: &'static str, #[case] indexed: bool) { + let mut category = MatchingRuleCategory::empty("header"); + category.add_rule(DocPath::new_unwrap(path), MatchingRule::Regex("^a$".to_string()), RuleLogic::And); + let context = CoreMatchingContext { matchers: category, ..CoreMatchingContext::default() }; + assert_eq!(has_indexed_rule("X-Request", 2, &context), indexed); + } + #[rstest] #[case("a, b", "a,b")] #[case(" a ,\t b ", "a,b")] @@ -256,6 +349,7 @@ mod tests { #[cfg(test)] pub(crate) mod cases { use pact_models::matchingrules::{MatchingRule, MatchingRuleCategory, RuleLogic}; + use pact_models::matchingrules::expressions::{MatchingRuleDefinition, ValueType}; use pact_models::path_exp::DocPath; /// One repeated-header scenario, run against both engines. @@ -294,6 +388,28 @@ pub(crate) mod cases { 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 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![ @@ -303,6 +419,15 @@ pub(crate) mod cases { 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 fallback", header: "Link", expected: LINKS, actual: LINKS, rules: each_value_link, matches: true, warns: true }, + 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), From e2acef66f39f060e029470653353291e5b7ff9c5 Mon Sep 17 00:00:00 2001 From: JP-Ellis Date: Tue, 20 Oct 2026 21:14:12 +1100 Subject: [PATCH 07/12] feat(matching): respect Link and Via grammars when splitting headers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Splitting a repeated header into list elements cut every comma outside a quoted string. Two registered headers carry commas of their own: - Link (RFC 8288 §3): a comma inside `<…>` belongs to the target URI, as in `; rel="next"`. - Via (RFC 9110 §5.6.5): a comma inside a `(…)` comment belongs to the comment, and comments nest. `split_list_elements` now keeps those commas, matching the header name case-insensitively. Every other header reads `<`, `>`, `(` and `)` as ordinary characters. Delimiters inside quoted strings do not count, and an unbalanced `<` or `(` extends to the end of the value, as an unbalanced quote does. `normalise_list` stays name-agnostic. Plain comparison normalises both sides the same way, so a comma inside `<…>` that both share is harmless. User-Agent and Server are singletons (their product comments may hold commas) and are never split. The "each-value link fallback" case no longer needs the per-line fallback, so it becomes "each-value link" with no warning. New cases cover a combined Link line and a MaxType rule on Via. Assisted-by: Claude Code:claude-opus-5-5 --- rust/pact_matching/src/repeated_headers.rs | 123 +++++++++++++++++++-- 1 file changed, 113 insertions(+), 10 deletions(-) diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index d396d4717..357480789 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -53,21 +53,58 @@ pub(crate) fn join_field_lines(values: &[String]) -> String { values.join(", ") } -/// Splits a list value on commas outside quoted strings (RFC 9110 §5.6.4), trimming each -/// element and dropping empty ones (RFC 9110 §5.6.1.2). -fn list_elements(value: &str) -> Vec<&str> { +/// 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 && character == '\\' { + } else if (quoted || in_comment) && character == '\\' { escaped = true; - } else if character == '"' { + } else if character == '"' && !in_comment { quoted = !quoted; - } else if character == ',' && !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; } @@ -80,13 +117,14 @@ fn list_elements(value: &str) -> Vec<&str> { /// Normalises a list value for comparison: whitespace around commas outside quoted strings /// is dropped, as are empty elements. pub(crate) fn normalise_list(value: &str) -> String { - list_elements(value).join(",") + list_elements(value, Grammar::Plain).join(",") } /// Splits a header's field lines into its list elements. -pub(crate) fn split_list_elements(_name: &str, values: &[String]) -> Vec { +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)) + .flat_map(|value| list_elements(value, grammar)) .map(str::to_string) .collect() } @@ -296,6 +334,66 @@ mod tests { 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 { 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 { @@ -424,7 +523,11 @@ pub(crate) mod cases { 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 fallback", header: "Link", expected: LINKS, actual: LINKS, rules: each_value_link, 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 }, From 05d811bb60785b7a135bb885a9e1dd42e77cdce9 Mon Sep 17 00:00:00 2001 From: JP-Ellis Date: Tue, 20 Oct 2026 21:18:55 +1100 Subject: [PATCH 08/12] test(matching): keep separate-line header list cases beside combined ones The ArrayContains and EachValue X-Id tests had their inputs rewritten to combined field lines, which dropped coverage of the separate-line form that master tested. Restore the original inputs and add `_with_combined_field_lines` variants carrying the combined-line inputs with the same assertions. Also remove the two length asserts at the end of match_headers_combined_custom_header_compatibility. match_headers receives clones, so they cannot fail. Assisted-by: Claude Code:claude-opus-5-5 --- rust/pact_matching/src/headers.rs | 39 +++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index 632bb0499..8be508774 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -633,8 +633,6 @@ mod tests { 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:?}"); - assert_eq!(expected.as_ref().unwrap()["X-Request"].len(), expected_values.len()); - assert_eq!(actual.as_ref().unwrap()["x-request"].len(), actual_values.len()); } #[test] @@ -911,6 +909,24 @@ mod tests { #[test] fn match_headers_with_array_contains_matcher() { + 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".to_string(), "2".to_string(), "3".to_string(), "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_with_combined_field_lines() { let context = HeaderMatchingContext::new(&CoreMatchingContext::new( DiffConfig::AllowUnexpectedKeys, &matchingrules! { @@ -955,6 +971,25 @@ mod tests { #[test] fn match_headers_with_each_value_matcher() { + 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".to_string(), "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_with_combined_field_lines() { let context = HeaderMatchingContext::new(&CoreMatchingContext::new( DiffConfig::AllowUnexpectedKeys, &matchingrules! { From b20acd8c1690d03483ed84eac0de96bdd878f739 Mon Sep 17 00:00:00 2001 From: JP-Ellis Date: Tue, 20 Oct 2026 21:29:25 +1100 Subject: [PATCH 09/12] docs(matching): describe repeated header matching The "Matching Headers" section still said values are compared after stripping whitespace following commas. Describe the current rules: repeated custom headers compare by their comma-joined values per RFC 9110 section 5.3, list-aware and index-specific matchers see split elements (respecting quotes, Link angle brackets and Via comments), other matchers see the joined value, per-line-only matches pass with a deprecation warning, and single-value, Accept/Content-Type and known multi-value headers are unchanged. Assisted-by: Claude Code:claude-opus-5-5 --- rust/pact_matching/README.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) 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 From de449d74e5bd5f8867778c1a28eaeebaaa87de8e Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Wed, 28 Oct 2026 19:05:07 +0000 Subject: [PATCH 10/12] fix(matching): normalise repeated headers using the header's own grammar normalise_list split every header with the plain list grammar, so the fast path treated whitespace inside Link targets (<...>) and Via comments (...) as list separators. Values that differed only there compared as equal. Split with Grammar::for_header(name) instead, and add cases for Link, Via and Set-Cookie sent on separate lines. Co-Authored-By: Claude Opus 5.5 --- rust/pact_matching/src/repeated_headers.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index 357480789..a1840f259 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -115,9 +115,9 @@ fn list_elements(value: &str, grammar: Grammar) -> Vec<&str> { } /// Normalises a list value for comparison: whitespace around commas outside quoted strings -/// is dropped, as are empty elements. -pub(crate) fn normalise_list(value: &str) -> String { - list_elements(value, Grammar::Plain).join(",") +/// 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. @@ -234,7 +234,7 @@ pub(crate) fn match_repeated_header( let joined_expected = join_field_lines(expected); let joined_actual = join_field_lines(actual); - if normalise_list(&joined_expected) == normalise_list(&joined_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 { @@ -440,7 +440,7 @@ mod tests { #[case(r#""x\", y", z"#, r#""x\", y",z"#)] #[case("", "")] fn normalise_list_ignores_whitespace_and_empty_elements_outside_quotes(#[case] value: &str, #[case] normalised: &str) { - assert_eq!(normalise_list(value), normalised); + assert_eq!(normalise_list("X-Request", value), normalised); } } @@ -556,7 +556,13 @@ pub(crate) mod cases { plain("missing member", "X-Request", &["request1", "request2"], &["request1"], false, false), plain("quoted whole", "X-Request", &["request1", "request2"], &["\"request1, request2\""], false, false), plain("quoted OWS fallback", "X-Request", &["\"x , y\"", "z"], &["\"x, y\"", "z"], true, true), - plain("singleton untouched", "Set-Cookie", &["one", "two"], &["one, two"], false, false) + 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) ] } } From fd5ed24ef20223ad948b62f90e83b6ec159797ec Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Wed, 28 Oct 2026 21:17:21 +0000 Subject: [PATCH 11/12] fix(matching): use the header grammar when comparing single header values A header with one value on each side and no matching rule was compared after splitting on every comma and trimming, so whitespace inside a Link , a Via comment or a quoted string was ignored (`` matched ``). Use normalise_list, which only treats list-separating commas as insignificant, in the legacy matcher and in the V2 engine's multi-value header normalisation. The "quoted OWS fallback" case relied on that and now mismatches; the per-line deprecation warning test uses an unbalanced quote instead. Co-Authored-By: Claude Opus 5.5 --- rust/pact_matching/src/engine/interpreter.rs | 7 +++---- rust/pact_matching/src/engine/mod.rs | 4 ++-- rust/pact_matching/src/headers.rs | 13 +++++-------- rust/pact_matching/src/repeated_headers.rs | 18 +++++++++++++----- 4 files changed, 23 insertions(+), 19 deletions(-) diff --git a/rust/pact_matching/src/engine/interpreter.rs b/rust/pact_matching/src/engine/interpreter.rs index 7c3dba2ee..c37ba28eb 100644 --- a/rust/pact_matching/src/engine/interpreter.rs +++ b/rust/pact_matching/src/engine/interpreter.rs @@ -24,7 +24,7 @@ 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; +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 @@ -2523,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| { diff --git a/rust/pact_matching/src/engine/mod.rs b/rust/pact_matching/src/engine/mod.rs index 312adb76d..0b241fe39 100644 --- a/rust/pact_matching/src/engine/mod.rs +++ b/rust/pact_matching/src/engine/mod.rs @@ -35,7 +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, HeaderKind}; +use crate::repeated_headers::{header_kind, normalise_list, HeaderKind}; mod bodies; mod value_resolvers; @@ -2064,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() }; diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index 8be508774..1b6f4282c 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -12,7 +12,7 @@ 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, HeaderKind}; +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() @@ -104,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 { diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index a1840f259..a60af24d6 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -280,14 +280,15 @@ mod tests { #[test] fn per_line_fallback_warns_of_deprecation() { - let expected = vec!["\"x , y\"".to_string(), "z".to_string()]; - let actual = vec!["\"x, y\"".to_string(), "z".to_string()]; + // 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 '\"x, y\", z'.")); + only the joined value '\"a , b'.")); assert!(result.warning.unwrap().contains("deprecated")); } @@ -555,14 +556,21 @@ pub(crate) mod cases { 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 fallback", "X-Request", &["\"x , y\"", "z"], &["\"x, y\"", "z"], true, true), + 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("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) ] } } From 7d06dcb1b3ebc8030b683eb2f572b58c31783b4b Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Wed, 28 Oct 2026 22:17:10 +0000 Subject: [PATCH 12/12] fix(matching): name the failing value when a repeated header fails a scalar rule A scalar rule on a repeated header reported only the joined mismatch ("Expected '1000, 1234, 9999ABC' to match '\d{1,4}'"), which doesn't say which value failed. Report the per-line mismatches as well, and pass the real list index to match_header_value in the matcher path instead of 0. Fixes the V2 compatibility-suite scenario "Supports matchers for repeated request headers (negative case)". Co-Authored-By: Claude Opus 5.5 --- .../src/engine/tests/header_tests.rs | 2 +- rust/pact_matching/src/headers.rs | 19 +++++++++++++++--- rust/pact_matching/src/repeated_headers.rs | 20 +++++++++++++++++-- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/rust/pact_matching/src/engine/tests/header_tests.rs b/rust/pact_matching/src/engine/tests/header_tests.rs index 632fb0537..1433e8096 100644 --- a/rust/pact_matching/src/engine/tests/header_tests.rs +++ b/rust/pact_matching/src/engine/tests/header_tests.rs @@ -1358,7 +1358,7 @@ fn match_headers_with_number_type_matching_rule() { ['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), + ) => 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'], diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index 1b6f4282c..85b9db5a5 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -7,7 +7,7 @@ use itertools::Itertools; use maplit::hashmap; use pact_models::headers::PARAMETERISED_HEADERS; use pact_models::matchingrules::MatchingRule; -use pact_models::path_exp::DocPath; +use pact_models::path_exp::{DocPath, PathToken}; use tracing::{instrument, debug, warn}; use crate::{CommonMismatch, MatchingContext, Mismatch}; use crate::field_rules::FieldMatchScope; @@ -157,8 +157,9 @@ pub(crate) fn match_header_lines( 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 |_, expected, actual, context| { - match_header_value(key, 0, expected, actual, context, false) + 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 { @@ -889,6 +890,18 @@ mod tests { 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(), + actual: "regex".to_string(), + mismatch: "Mismatch with header 'X-IMPROVED': Expected 'regex' to be equal to 'like' for value at index 0".to_string(), + }, + Mismatch::HeaderMismatch { + key: "X-IMPROVED".to_string(), + expected: "regex".to_string(), + actual: "like".to_string(), + mismatch: "Mismatch with header 'X-IMPROVED': Expected 'like' to be equal to 'regex' for value at index 1".to_string(), } ])); diff --git a/rust/pact_matching/src/repeated_headers.rs b/rust/pact_matching/src/repeated_headers.rs index a60af24d6..2ae6dbc5e 100644 --- a/rust/pact_matching/src/repeated_headers.rs +++ b/rust/pact_matching/src/repeated_headers.rs @@ -217,7 +217,8 @@ pub(crate) fn match_repeated_header( if primary.is_empty() { return RepeatedHeaderResult::default(); } - if match_header_lines(key, expected, actual, context).is_empty() { + 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 { @@ -229,7 +230,8 @@ pub(crate) fn match_repeated_header( }; return RepeatedHeaderResult { mismatches: vec![], warning: Some(warning) }; } - return RepeatedHeaderResult { mismatches: primary, warning: None }; + // 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); @@ -307,6 +309,20 @@ mod tests { 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");