From 2a000e2f5eb62ac9d8cac62fa85badf9d86f82e6 Mon Sep 17 00:00:00 2001 From: Sergey Shtubey Date: Wed, 4 Nov 2026 10:49:13 +0200 Subject: [PATCH 1/6] feat(ffi): support pact:matcher:combine OR in integration JSON Matchers in integration JSON can now be combined with OR using the `pact:matcher:combine` attribute. The rules are written to the pact file as an existing rule list combined with OR, so the pact file format is unchanged. --- .gitignore | 2 + rust/pact_ffi/IntegrationJson.md | 50 ++++++- rust/pact_ffi/src/mock_server/bodies.rs | 125 ++++++++++++++-- rust/pact_ffi/src/mock_server/handles.rs | 60 +++++--- rust/pact_ffi/src/mock_server/xml.rs | 21 +-- rust/pact_ffi/tests/tests.rs | 176 +++++++++++++++++++++++ rust/pact_matching/src/json.rs | 134 ++++++++++++++++- rust/pact_matching/src/tests.rs | 43 ++++++ 8 files changed, 559 insertions(+), 52 deletions(-) diff --git a/.gitignore b/.gitignore index 3a8ab2db8..a98d0825d 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,8 @@ target/ # Generated Release Artifacts release_artifacts +out/ + node_modules/ *.log .idea/ diff --git a/rust/pact_ffi/IntegrationJson.md b/rust/pact_ffi/IntegrationJson.md index 4de165257..5ba7bac6a 100644 --- a/rust/pact_ffi/IntegrationJson.md +++ b/rust/pact_ffi/IntegrationJson.md @@ -160,8 +160,9 @@ Here the `interests` attribute would be expanded to ## Supporting multiple matching rules -Matching rules can be combined. These rules will be evaluated with an AND (i.e. all the rules must match successfully -for the result to be successful). The main reason to do this is to combine the `EachKey` and `EachValue` matching rules +Matching rules can be combined. By default, these rules will be evaluated with an AND (i.e. all the rules must match +successfully for the result to be successful). See [Combining matching rules with OR](#combining-matching-rules-with-or) +to require only one of the rules to match. The main reason to do this is to combine the `EachKey` and `EachValue` matching rules on a map structure, but other rules make sense to combine (like the `include` matcher). To provide multiple matchers, you need to provide an array format. @@ -216,6 +217,51 @@ So the resulting intermediate JSON would be something like: } ``` +### Combining matching rules with OR + +The `pact:matcher:combine` attribute sets how the matching rules are combined. It can be either `AND` (the default, +all the rules must match) or `OR` (at least one of the rules must match). Any other value is an error, and the +matching rules will be ignored. + +For example, a `name` that is either a string or null: + +```json +{ + "name": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": "Fred" + } +} +``` + +The rules are written to the Pact file as a rule list combined with `OR`: + +```json +"$.name": { + "combine": "OR", + "matchers": [{ "match": "type" }, { "match": "null" }] +} +``` + +`OR` can be used for bodies (JSON and XML), headers and query parameters. + +#### Limitations + +* All the alternatives are applied to the top level `value`, so matchers that compare against the example (like + `type`) can only describe the shape of that example. For instance, `type OR null` on an object accepts an object of + the same shape or null, but not an array. +* Each matcher in the list must be a single matcher. A nested list of matchers is an error. +* The `regex` and `include` matchers convert non-string values to their JSON text before matching, so as an + alternative they can accept numbers, booleans, objects or arrays whose JSON text matches (for example, `^\w+$` + matches the number `5`). +* Use `OR` with care. Only the top level example value is used for the consumer test, so the other alternatives are + never exercised against your consumer code. +* The experimental V2 matching engine (`PACT_MATCHING_ENGINE=v2`) does not support `OR`. + ## Supporting matching rule definitions You can use the [matching rule definition expressions](https://docs.rs/pact_models/latest/pact_models/matchingrules/expressions/index.html) diff --git a/rust/pact_ffi/src/mock_server/bodies.rs b/rust/pact_ffi/src/mock_server/bodies.rs index 88ca0c414..f2fba0ad1 100644 --- a/rust/pact_ffi/src/mock_server/bodies.rs +++ b/rust/pact_ffi/src/mock_server/bodies.rs @@ -9,13 +9,13 @@ use lazy_static::lazy_static; use multipart_2021 as multipart; use regex::Regex; use serde_json::{Map, Value}; -use tracing::{debug, error, trace}; +use tracing::{debug, error, trace, warn}; use pact_models::bodies::OptionalBody; use pact_models::content_types::ContentTypeHint; use pact_models::generators::{Generator, GeneratorCategory, Generators}; use pact_models::json_utils::json_to_string; -use pact_models::matchingrules::{MatchingRule, MatchingRuleCategory, RuleLogic}; +use pact_models::matchingrules::{MatchingRule, MatchingRuleCategory, RuleList, RuleLogic}; use pact_models::matchingrules::expressions::{is_matcher_def, parse_matcher_def}; use pact_models::path_exp::DocPath; use pact_models::v4::http_parts::{HttpRequest, HttpResponse}; @@ -125,13 +125,13 @@ fn process_matcher( (index, category, generators.categories.get(&GeneratorCategory::BODY).cloned().unwrap_or_default()) }).collect(); - Ok((vec!(MatchingRule::ArrayContains(values)), Value::Array(json_values))) + Ok((RuleList::new(MatchingRule::ArrayContains(values)), Value::Array(json_values))) } _ => Err(anyhow!("ArrayContains 'variants' attribute is missing or not an array")) } } else { - matchers_from_integration_json(obj).map(|(rules, generator)| { - let has_values_matcher = rules.iter().any(MatchingRule::is_values_matcher); + rule_list_from_integration_json(obj).map(|(rule_list, generator)| { + let has_values_matcher = rule_list.rules.iter().any(MatchingRule::is_values_matcher); let json_value = match obj.get("value") { Some(inner) => match inner { @@ -147,11 +147,11 @@ fn process_matcher( generators.add_generator_with_subcategory(category, path.clone(), generator); } - if rules.iter().any(|rule| matches!(rule, MatchingRule::EachValue(_))) { + if rule_list.rules.iter().any(|rule| matches!(rule, MatchingRule::EachValue(_))) { add_each_value_rule_matchers(obj, matching_rules, path); } - (rules, json_value) + (rule_list, json_value) }) }; @@ -165,10 +165,8 @@ fn process_matcher( trace!("matching_rules = {matching_rule_result:?}"); match &matching_rule_result { - Ok((rules, value)) => { - for rule in rules { - matching_rules.add_rule(path.clone(), rule.clone(), RuleLogic::And); - } + Ok((rule_list, value)) => { + add_rule_list_to_category(matching_rules, path, rule_list); value.clone() }, Err(err) => { @@ -284,6 +282,47 @@ pub fn matchers_from_integration_json(m: &Map) -> anyhow::Result< } } +/// Builds a `RuleList` from a `Value` struct used by language integrations. The matching rules are +/// combined with the logic from the `pact:matcher:combine` attribute, which can be either `AND` +/// (the default, all the rules must match) or `OR` (at least one of the rules must match). +pub fn rule_list_from_integration_json(m: &Map) -> anyhow::Result<(RuleList, Option)> { + let rule_logic = rule_logic_from_integration_json(m)?; + let (rules, generator) = matchers_from_integration_json(m)?; + Ok((RuleList { rules, rule_logic, cascaded: false }, generator)) +} + +/// Returns the logic used to combine the matching rules, from the `pact:matcher:combine` attribute +fn rule_logic_from_integration_json(m: &Map) -> anyhow::Result { + match m.get("pact:matcher:combine") { + None | Some(Value::Null) => Ok(RuleLogic::And), + Some(Value::String(logic)) if logic.eq_ignore_ascii_case("and") => Ok(RuleLogic::And), + Some(Value::String(logic)) if logic.eq_ignore_ascii_case("or") => Ok(RuleLogic::Or), + Some(logic) => { + error!("Failed to create matching rules from JSON '{:?}': 'pact:matcher:combine' must be either 'AND' or 'OR', got {}", m, logic); + bail!("'pact:matcher:combine' must be either 'AND' or 'OR', got {}", logic) + } + } +} + +/// Adds the rules from the rule list to the category at the given path +pub(crate) fn add_rule_list_to_category( + matching_rules: &mut MatchingRuleCategory, + path: &DocPath, + rule_list: &RuleList +) { + for rule in &rule_list.rules { + matching_rules.add_rule(path.clone(), rule.clone(), rule_list.rule_logic); + } + if rule_list.rule_logic == RuleLogic::Or { + if let Some(existing) = matching_rules.rules.get_mut(path) { + if existing.rules.len() > rule_list.rules.len() { + warn!("Path '{}' already has matching rules, they will now be combined with OR", path); + } + existing.rule_logic = RuleLogic::Or; + } + } +} + /// Process a JSON body with embedded matching rules and generators pub fn process_json(body: String, matching_rules: &mut MatchingRuleCategory, generators: &mut Generators) -> String { trace!("process_json"); @@ -805,6 +844,70 @@ use pretty_assertions::assert_eq; expect!(generators).to(be_equal_to(Generators::default())); } + // Issue #249 + #[test_log::test] + fn process_object_with_matchers_combined_with_or() { + let json = json!({ + "a": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": "string" + } + }); + let mut matching_rules = MatchingRuleCategory::empty("body"); + let mut generators = Generators::default(); + let result = process_object(json.as_object().unwrap(), &mut matching_rules, + &mut generators, DocPath::root(), false); + + expect!(result).to(be_equal_to(json!({ "a": "string" }))); + expect!(matching_rules.rules.get(&DocPath::new_unwrap("$.a")).cloned()).to(be_some().value(RuleList { + rules: vec![ MatchingRule::Type, MatchingRule::Null ], + rule_logic: RuleLogic::Or, + cascaded: false + })); + } + + // Issue #249 + #[test_log::test] + fn process_object_with_invalid_matcher_combine_value() { + let json = json!({ + "a": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "XOR", + "value": "string" + } + }); + let mut matching_rules = MatchingRuleCategory::empty("body"); + let mut generators = Generators::default(); + let result = process_object(json.as_object().unwrap(), &mut matching_rules, + &mut generators, DocPath::root(), false); + + expect!(result).to(be_equal_to(json!({ "a": null }))); + expect!(matching_rules.is_empty()).to(be_true()); + } + + #[rstest] + #[case(json!({}), Some(RuleLogic::And))] + #[case(json!({ "pact:matcher:combine": null }), Some(RuleLogic::And))] + #[case(json!({ "pact:matcher:combine": "AND" }), Some(RuleLogic::And))] + #[case(json!({ "pact:matcher:combine": "and" }), Some(RuleLogic::And))] + #[case(json!({ "pact:matcher:combine": "OR" }), Some(RuleLogic::Or))] + #[case(json!({ "pact:matcher:combine": "or" }), Some(RuleLogic::Or))] + #[case(json!({ "pact:matcher:combine": "XOR" }), None)] + #[case(json!({ "pact:matcher:combine": true }), None)] + fn rule_list_from_integration_json_combine_test(#[case] json: Value, #[case] expected: Option) { + let mut json = json; + json["pact:matcher:type"] = json!([{ "pact:matcher:type": "type" }, { "pact:matcher:type": "null" }]); + let result = rule_list_from_integration_json(json.as_object().unwrap()); + expect!(result.ok().map(|(rule_list, _)| rule_list.rule_logic)).to(be_equal_to(expected)); + } + #[test_log::test] #[allow(deprecated)] fn matcher_from_integration_json_test() { diff --git a/rust/pact_ffi/src/mock_server/handles.rs b/rust/pact_ffi/src/mock_server/handles.rs index 466725ecd..b8ae1c284 100644 --- a/rust/pact_ffi/src/mock_server/handles.rs +++ b/rust/pact_ffi/src/mock_server/handles.rs @@ -155,9 +155,10 @@ use crate::models::async_message::generate_async_message_contents; use crate::models::sync_message::generate_sync_message_contents; #[allow(deprecated)] use crate::mock_server::bodies::{ + add_rule_list_to_category, empty_multipart_body, file_as_multipart_body, - matchers_from_integration_json, + rule_list_from_integration_json, MultipartBody, process_array, process_json, @@ -1026,7 +1027,7 @@ fn from_integration_json_v2( Value::Object(map) => { let result = if map.contains_key("pact:matcher:type") { debug!("detected pact:matcher:type, will configure any matchers"); - let rules = matchers_from_integration_json(map); + let rules = rule_list_from_integration_json(map); trace!("matching_rules = {rules:?}"); let (path, result_value) = match map.get("value") { @@ -1040,30 +1041,22 @@ fn from_integration_json_v2( None => (path.clone(), Value::Null) }; - if let Ok((rules, generator)) = &rules { + if let Ok((rule_list, generator)) = &rules { let path = if path_or_status { path.parent().unwrap_or(DocPath::root()) } else { path.clone() }; - if query_or_header { - if index > 0 { - // If the index > 0, and there is an existing entry with the base name, we need - // to re-key that with an index of 0 - let mut parent = path.parent().unwrap_or(DocPath::root()); - if let Entry::Occupied(rule_entry) = matching_rules.rules.entry(parent.clone()) { - let rules_list = rule_entry.remove(); - matching_rules.rules.insert(parent.push_index(0).clone(), rules_list); - } - } - for rule in rules { - matching_rules.add_rule(path.clone(), rule.clone(), RuleLogic::And); - } - } else { - for rule in rules { - matching_rules.add_rule(path.clone(), rule.clone(), RuleLogic::And); + if query_or_header && index > 0 { + // If the index > 0, and there is an existing entry with the base name, we need + // to re-key that with an index of 0 + let mut parent = path.parent().unwrap_or(DocPath::root()); + if let Entry::Occupied(rule_entry) = matching_rules.rules.entry(parent.clone()) { + let rules_list = rule_entry.remove(); + matching_rules.rules.insert(parent.push_index(0).clone(), rules_list); } } + add_rule_list_to_category(matching_rules, &path, rule_list); if let Some(generator) = generator { let category = generator_category(matching_rules); @@ -3447,6 +3440,35 @@ mod tests { use super::from_integration_json_v2; + // Issue #249 + #[test] + fn from_integration_json_v2_with_or_matchers_for_a_header() { + let mut rules = MatchingRules::default(); + let mut generators = Generators::default(); + let mut path = DocPath::root(); + path.push_field("x-id"); + let value = r#"{ + "pact:matcher:type": [ + { "pact:matcher:type": "regex", "regex": "^\\d+$" }, + { "pact:matcher:type": "regex", "regex": "^[a-f0-9-]{36}$" } + ], + "pact:matcher:combine": "OR", + "value": "100" + }"#; + + let result = from_integration_json_v2(&mut rules, &mut generators, value, path.clone(), "header", 0); + expect!(result).to(be_equal_to(Either::Left("100".to_string()))); + + let rule_list = rules.rules_for_category("header").unwrap().rules.get(&path).cloned().unwrap(); + expect!(rule_list.rule_logic).to(be_equal_to(pact_models::matchingrules::RuleLogic::Or)); + expect!(rule_list.rules.len()).to(be_equal_to(2)); + + let check = |actual: &str| pact_matching::matchingrules::match_values(&path, &rule_list, "100", actual); + expect!(check("12345")).to(be_ok()); + expect!(check("0f8b3c1e-9d2a-4b7c-8e6f-1a2b3c4d5e6f")).to(be_ok()); + expect!(check("not-an-id")).to(be_err()); + } + #[test] fn pact_handles() { let pact_handle = PactHandle::new("TestHandlesC", "TestHandlesP"); diff --git a/rust/pact_ffi/src/mock_server/xml.rs b/rust/pact_ffi/src/mock_server/xml.rs index bd0bc890e..ea9719293 100644 --- a/rust/pact_ffi/src/mock_server/xml.rs +++ b/rust/pact_ffi/src/mock_server/xml.rs @@ -15,10 +15,9 @@ use tracing::{debug, trace, warn}; use pact_models::generators::{Generator, GeneratorCategory, Generators}; use pact_models::json_utils::json_to_string; use pact_models::matchingrules::MatchingRuleCategory; -use pact_models::matchingrules::RuleLogic; use pact_models::path_exp::DocPath; -use crate::mock_server::bodies::matchers_from_integration_json; +use crate::mock_server::bodies::{add_rule_list_to_category, rule_list_from_integration_json}; pub fn generate_xml_body( attributes: &Map, @@ -75,10 +74,8 @@ fn create_element_from_json<'a>( updated_path.push(&name); let doc_path = DocPath::new(updated_path.join(".").to_string()).unwrap_or(DocPath::root()); - if let Ok((rules, generator)) = matchers_from_integration_json(object) { - for rule in rules { - matching_rules.add_rule(doc_path.clone(), rule, RuleLogic::And); - } + if let Ok((rule_list, generator)) = rule_list_from_integration_json(object) { + add_rule_list_to_category(matching_rules, &doc_path, &rule_list); if let Some(generator) = generator { generators.add_generator_with_subcategory(&GeneratorCategory::BODY, doc_path.clone(), generator); @@ -135,10 +132,8 @@ fn create_element_from_json<'a>( let doc_path = DocPath::new(&text_path.join(".")).unwrap_or(DocPath::root()); if let Value::Object(matcher) = matcher { - if let Ok((rules, generator)) = matchers_from_integration_json(matcher) { - for rule in rules { - matching_rules.add_rule(doc_path.clone(), rule, RuleLogic::And); - } + if let Ok((rule_list, generator)) = rule_list_from_integration_json(matcher) { + add_rule_list_to_category(matching_rules, &doc_path, &rule_list); if let Some(generator) = generator { generators.add_generator_with_subcategory(&GeneratorCategory::BODY, doc_path.clone(), generator); @@ -229,10 +224,8 @@ fn add_attributes( let value = match v { Value::Object(matcher_definition) => if matcher_definition.contains_key("pact:matcher:type") { let doc_path = DocPath::new(path).unwrap_or(DocPath::root()); - if let Ok((rules, generator)) = matchers_from_integration_json(matcher_definition) { - for rule in rules { - matching_rules.add_rule(doc_path.clone(), rule, RuleLogic::And); - } + if let Ok((rule_list, generator)) = rule_list_from_integration_json(matcher_definition) { + add_rule_list_to_category(matching_rules, &doc_path, &rule_list); if let Some(generator) = generator { generators.add_generator_with_subcategory(&GeneratorCategory::BODY, doc_path.clone(), generator); diff --git a/rust/pact_ffi/tests/tests.rs b/rust/pact_ffi/tests/tests.rs index bb797fa31..088e58527 100644 --- a/rust/pact_ffi/tests/tests.rs +++ b/rust/pact_ffi/tests/tests.rs @@ -1910,6 +1910,182 @@ fn combined_each_key_and_each_value_matcher() { }; } +// Issue #249 +#[rstest] +#[case::values_match_the_type(json!({ "name": "Mary", "address": { "street": "Other St" } }), 200)] +#[case::values_are_null(json!({ "name": null, "address": null }), 200)] +#[case::values_match_neither_rule(json!({ "name": 100, "address": "Other St" }), 500)] +fn matchers_combined_with_or(#[case] actual_body: Value, #[case] expected_status: u16) { + init_crypto(); + + let consumer_name = CString::new("combined_or_matcher-consumer").unwrap(); + let provider_name = CString::new("combined_or_matcher-provider").unwrap(); + let pact_handle = pactffi_new_pact(consumer_name.as_ptr(), provider_name.as_ptr()); + let description = CString::new("combined_or_matcher").unwrap(); + let interaction = pactffi_new_interaction(pact_handle.clone(), description.as_ptr()); + + let content_type = CString::new("application/json").unwrap(); + let path = CString::new("/person").unwrap(); + let json = json!({ + "name": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": "Fred" + }, + "address": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": { + "street": "Main St" + } + } + }); + let body = CString::new(json.to_string()).unwrap(); + let address = CString::new("127.0.0.1").unwrap(); + let method = CString::new("PUT").unwrap(); + + pactffi_upon_receiving(interaction.clone(), description.as_ptr()); + pactffi_with_request(interaction.clone(), method.as_ptr(), path.as_ptr()); + pactffi_with_body(interaction.clone(), InteractionPart::Request, content_type.as_ptr(), body.as_ptr()); + pactffi_response_status(interaction.clone(), 200); + + let port = pactffi_create_mock_server_for_transport(pact_handle.clone(), address.as_ptr(), 0, null(), null()); + + expect!(port).to(be_greater_than(0)); + + let client = http_client(); + let result = client.put(format!("http://127.0.0.1:{}/person", port).as_str()) + .header("Content-Type", "application/json") + .body(actual_body.to_string()) + .send(); + + let mismatches = pactffi_mock_server_mismatches(port); + println!("{}", unsafe { CStr::from_ptr(mismatches) }.to_string_lossy()); + + pactffi_cleanup_mock_server(port); + pactffi_free_pact_handle(pact_handle); + + match result { + Ok(res) => { + expect!(res.status().as_u16()).to(be_eq(expected_status)); + }, + Err(err) => { + panic!("expected {} response but request failed: {}", expected_status, err); + } + }; +} + +// Issue #249 +#[rstest] +#[case::digits("12345", 200)] +#[case::all("all", 200)] +#[case::other("some", 500)] +fn or_matchers_for_query_parameters(#[case] status: &str, #[case] expected_status: u16) { + init_crypto(); + + let consumer_name = CString::new("or_matchers_query-consumer").unwrap(); + let provider_name = CString::new("or_matchers_query-provider").unwrap(); + let pact_handle = pactffi_new_pact(consumer_name.as_ptr(), provider_name.as_ptr()); + let description = CString::new("or_matchers_query").unwrap(); + let interaction = pactffi_new_interaction(pact_handle.clone(), description.as_ptr()); + + let path = CString::new("/items").unwrap(); + let method = CString::new("GET").unwrap(); + let name = CString::new("status").unwrap(); + let value = CString::new(json!({ + "pact:matcher:type": [ + { "pact:matcher:type": "regex", "regex": "^\\d+$" }, + { "pact:matcher:type": "regex", "regex": "^all$" } + ], + "pact:matcher:combine": "OR", + "value": "100" + }).to_string()).unwrap(); + let address = CString::new("127.0.0.1").unwrap(); + + pactffi_upon_receiving(interaction.clone(), description.as_ptr()); + pactffi_with_request(interaction.clone(), method.as_ptr(), path.as_ptr()); + pactffi_with_query_parameter_v2(interaction.clone(), name.as_ptr(), 0, value.as_ptr()); + pactffi_response_status(interaction.clone(), 200); + + let port = pactffi_create_mock_server_for_transport(pact_handle.clone(), address.as_ptr(), 0, null(), null()); + expect!(port).to(be_greater_than(0)); + + let client = http_client(); + let result = client.get(format!("http://127.0.0.1:{}/items?status={}", port, status).as_str()).send(); + + let mismatches = pactffi_mock_server_mismatches(port); + println!("{}", unsafe { CStr::from_ptr(mismatches) }.to_string_lossy()); + + pactffi_cleanup_mock_server(port); + pactffi_free_pact_handle(pact_handle); + + match result { + Ok(res) => expect!(res.status().as_u16()).to(be_eq(expected_status)), + Err(err) => panic!("expected {} response but request failed: {}", expected_status, err) + }; +} + +// Issue #249 +#[rstest] +#[case::v4(PactSpecification::V4)] +#[case::v3(PactSpecification::V3)] +#[case::v2(PactSpecification::V2)] +fn or_matchers_are_written_to_the_pact_file(#[case] spec: PactSpecification) { + let consumer_name = CString::new(format!("or_matchers_file-{:?}-consumer", spec)).unwrap(); + let provider_name = CString::new("or_matchers_file-provider").unwrap(); + let pact_handle = pactffi_new_pact(consumer_name.as_ptr(), provider_name.as_ptr()); + pactffi_with_specification(pact_handle, spec); + let description = CString::new("or_matchers_file").unwrap(); + let interaction = pactffi_new_interaction(pact_handle.clone(), description.as_ptr()); + + let content_type = CString::new("application/json").unwrap(); + let path = CString::new("/contact").unwrap(); + let method = CString::new("PUT").unwrap(); + let body = CString::new(json!({ + "contact": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": { "email": "fred@example.com" } + } + }).to_string()).unwrap(); + + pactffi_upon_receiving(interaction.clone(), description.as_ptr()); + pactffi_with_request(interaction.clone(), method.as_ptr(), path.as_ptr()); + pactffi_with_body(interaction.clone(), InteractionPart::Request, content_type.as_ptr(), body.as_ptr()); + pactffi_response_status(interaction.clone(), 200); + + let tmp = tempfile::tempdir().unwrap(); + let tmp_dir = CString::new(tmp.path().to_string_lossy().as_bytes().to_vec()).unwrap(); + let result = pactffi_pact_handle_write_file(pact_handle, tmp_dir.as_ptr(), false); + let pact_file = pact_default_file_name(&pact_handle); + pactffi_free_pact_handle(pact_handle); + expect!(result).to(be_equal_to(0)); + + let json: Value = serde_json::from_reader(File::open(tmp.path().join(pact_file.unwrap())).unwrap()).unwrap(); + let request = &json["interactions"][0]["request"]; + let body = if spec == PactSpecification::V4 { &request["body"]["content"] } else { &request["body"] }; + expect!(body).to(be_equal_to(&json!({ "contact": { "email": "fred@example.com" } }))); + + if spec == PactSpecification::V2 { + // V2 has one rule per path, so only the first rule is written + expect!(&request["matchingRules"]).to(be_equal_to(&json!({ "$.body.contact": { "match": "type" } }))); + } else { + expect!(&request["matchingRules"]["body"]["$.contact"]).to(be_equal_to(&json!({ + "combine": "OR", + "matchers": [{ "match": "type" }, { "match": "null" }] + }))); + } +} + // Issue #399 #[test_log::test] fn matching_definition_expressions_matcher() { diff --git a/rust/pact_matching/src/json.rs b/rust/pact_matching/src/json.rs index f159a4437..ac07293ed 100644 --- a/rust/pact_matching/src/json.rs +++ b/rust/pact_matching/src/json.rs @@ -13,7 +13,7 @@ use serde_json::{json, Value}; use pact_models::http_parts::HttpPart; use pact_models::json_utils::json_to_string; -use pact_models::matchingrules::MatchingRule; +use pact_models::matchingrules::{MatchingRule, RuleLogic}; use pact_models::path_exp::DocPath; #[cfg(feature = "datetime")] use pact_models::time_utils::validate_datetime; use tracing::debug; @@ -409,6 +409,13 @@ pub fn compare_json( context: &(dyn MatchingContext + Send + Sync) ) -> Result<(), Vec> { debug!("compare: Comparing path {}", path); + let is_type_mismatch = (expected.is_object() && !actual.is_object()) || + (expected.is_array() && !actual.is_array()); + if is_type_mismatch && is_or_matcher_defined(path, context) { + // With OR logic, another rule may allow a different type (i.e. an object or null) + debug!("compare: Values at path {} are different types, but an OR matcher is defined", path); + return compare_values(path, expected, actual, context); + } match (expected, actual) { (&Value::Object(ref emap), &Value::Object(ref amap)) => compare_maps(path, emap, amap, context), (&Value::Object(_), _) => { @@ -434,6 +441,11 @@ pub fn compare_json( } } +fn is_or_matcher_defined(path: &DocPath, context: &(dyn MatchingContext + Send + Sync)) -> bool { + context.matcher_is_defined(path) && + context.select_best_matcher(path).rule_logic == RuleLogic::Or +} + fn compare_maps( path: &DocPath, expected: &serde_json::Map, @@ -458,11 +470,17 @@ fn compare_maps( if context.matcher_is_defined(path) { debug!("compare_maps: Matcher is defined for path {}", path); let rule_list = context.select_best_matcher(path); - for matcher in rule_list.rules { - let result1 = compare_maps_with_matchingrule(&matcher, rule_list.cascaded, path, &expected, &actual, context, &mut |p, expected, actual, context| { + let results = rule_list.rules.iter().map(|matcher| { + compare_maps_with_matchingrule(matcher, rule_list.cascaded, path, &expected, &actual, context, &mut |p, expected, actual, context| { compare_json(p, expected, actual, context) - }); - result = merge_result(result, result1); + }) + }).collect::>(); + if rule_list.rule_logic == RuleLogic::Or && results.iter().any(|result| result.is_ok()) { + debug!("compare_maps: At least one matcher for path {} matched with OR logic", path); + } else { + for result1 in results { + result = merge_result(result, result1); + } } } else { let expected_keys = expected.keys().cloned().collect(); @@ -1496,7 +1514,7 @@ mod tests2 { use serde_json::{json, Value}; use pact_models::matchingrules_list; - use pact_models::matchingrules::MatchingRule; + use pact_models::matchingrules::{MatchingRule, MatchingRuleCategory}; use crate::{CoreMatchingContext, DiffConfig}; use super::*; @@ -1574,4 +1592,108 @@ mod tests2 { expect!(result).to(be_err()); } } + + fn or_matching_rules(path: &'static str, rules: &[MatchingRule]) -> MatchingRuleCategory { + let mut category = MatchingRuleCategory::empty("body"); + for rule in rules { + category.add_rule(DocPath::new_unwrap(path), rule.clone(), RuleLogic::Or); + } + category + } + + // Issue #249 + #[rstest] + // actual_json, is_ok + #[case::matches_first_rule( json!({"a": "other string"}), true)] + #[case::matches_second_rule( json!({"a": null}), true)] + #[case::matches_no_rule( json!({"a": 100}), false)] + fn compare_json_with_or_matcher_on_value(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"a": "string"}); + let matchingrules = or_matching_rules("$.a", &[MatchingRule::Type, MatchingRule::Null]); + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &matchingrules, &hashmap!{}); + let result = compare_json(&DocPath::root(), &expected_json, &actual_json, &context); + if is_ok { + expect!(result).to(be_ok()); + } else { + expect!(result).to(be_err()); + } + } + + // Issue #249 + #[rstest] + // actual_json, is_ok + #[case::object_of_same_type( json!({"a": {"b": "other"}}), true)] + #[case::null_value( json!({"a": null}), true)] + #[case::string_value( json!({"a": "string"}), false)] + #[case::array_value( json!({"a": ["string"]}), false)] + #[case::object_with_child_mismatch( json!({"a": {"b": 100}}), false)] + fn compare_json_with_or_matcher_on_object(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"a": {"b": "string"}}); + let matchingrules = or_matching_rules("$.a", &[MatchingRule::Type, MatchingRule::Null]); + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &matchingrules, &hashmap!{}); + let result = compare_json(&DocPath::root(), &expected_json, &actual_json, &context); + if is_ok { + expect!(result).to(be_ok()); + } else { + expect!(result).to(be_err()); + } + } + + // Issue #249 + #[rstest] + // actual_json, is_ok + #[case::array_of_same_type( json!({"a": ["x", "y"]}), true)] + #[case::null_value( json!({"a": null}), true)] + #[case::object_value( json!({"a": {"b": "x"}}), false)] + fn compare_json_with_or_matcher_on_array(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"a": ["string"]}); + let matchingrules = or_matching_rules("$.a", &[MatchingRule::Type, MatchingRule::Null]); + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &matchingrules, &hashmap!{}); + let result = compare_json(&DocPath::root(), &expected_json, &actual_json, &context); + if is_ok { + expect!(result).to(be_ok()); + } else { + expect!(result).to(be_err()); + } + } + + #[test] + fn compare_json_with_and_matchers_on_object_still_requires_an_object() { + let expected_json = json!({"a": {"b": "string"}}); + let actual_json = json!({"a": null}); + let matchingrules = matchingrules_list! { + "body"; "$.a" => [ MatchingRule::Type, MatchingRule::Null ] + }; + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &matchingrules, &hashmap!{}); + let result = compare_json(&DocPath::root(), &expected_json, &actual_json, &context); + expect!(result).to(be_err()); + } + + // Issue #249 + #[rstest] + #[case::integer_or_decimal_with_integer( MatchingRule::Integer, MatchingRule::Decimal, json!(10), true)] + #[case::integer_or_decimal_with_decimal( MatchingRule::Integer, MatchingRule::Decimal, json!(10.5), true)] + #[case::integer_or_decimal_with_string( MatchingRule::Integer, MatchingRule::Decimal, json!("10"), false)] + #[case::date_or_null_with_date( MatchingRule::Date("yyyy-MM-dd".to_string()), MatchingRule::Null, json!("2026-11-02"), true)] + #[case::date_or_null_with_null( MatchingRule::Date("yyyy-MM-dd".to_string()), MatchingRule::Null, Value::Null, true)] + #[case::date_or_null_with_other_date( MatchingRule::Date("yyyy-MM-dd".to_string()), MatchingRule::Null, json!("02/11/2026"), false)] + #[case::boolean_or_number_with_boolean( MatchingRule::Boolean, MatchingRule::Number, json!(false), true)] + #[case::boolean_or_number_with_number( MatchingRule::Boolean, MatchingRule::Number, json!(1.5), true)] + #[case::boolean_or_number_with_object( MatchingRule::Boolean, MatchingRule::Number, json!({}), false)] + fn compare_json_with_or_matcher_on_scalar_values( + #[case] first: MatchingRule, + #[case] second: MatchingRule, + #[case] actual: Value, + #[case] is_ok: bool + ) { + let expected_json = json!({"a": 1}); + let matchingrules = or_matching_rules("$.a", &[first, second]); + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &matchingrules, &hashmap!{}); + let result = compare_json(&DocPath::root(), &expected_json, &json!({"a": actual}), &context); + if is_ok { + expect!(result).to(be_ok()); + } else { + expect!(result).to(be_err()); + } + } } diff --git a/rust/pact_matching/src/tests.rs b/rust/pact_matching/src/tests.rs index 967083bd8..e1ade8e03 100644 --- a/rust/pact_matching/src/tests.rs +++ b/rust/pact_matching/src/tests.rs @@ -1032,3 +1032,46 @@ fn match_metadata_value_with_content_type_test() { let result = match_metadata_value("key", &expected, &actual, &context); expect!(result).to(be_err()); } + +fn or_rules(category: &str, path: &'static str, rules: &[MatchingRule]) -> MatchingRuleCategory { + let mut category = MatchingRuleCategory::empty(category); + for rule in rules { + category.add_rule(DocPath::new_unwrap(path), rule.clone(), pact_models::matchingrules::RuleLogic::Or); + } + category +} + +// Issue #249 +#[rstest::rstest] +#[case::digits( "12345", true)] +#[case::all( "all", true)] +#[case::neither( "some", false)] +fn match_query_with_or_matchers(#[case] actual: &str, #[case] is_ok: bool) { + let expected = hashmap! { "id".to_string() => vec![Some("100".to_string())] }; + let actual = hashmap! { "id".to_string() => vec![Some(actual.to_string())] }; + let rules = or_rules("query", "id", &[ + MatchingRule::Regex("^\\d+$".to_string()), + MatchingRule::Regex("^all$".to_string()) + ]); + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &rules, &hashmap!{}); + let result = match_query(Some(expected), Some(actual), &context); + expect!(result.values().flatten().count() == 0).to(be_equal_to(is_ok)); +} + +// Issue #249 +#[rstest::rstest] +#[case::bearer_token("Bearer abc.def.ghi", true)] +#[case::api_key("ApiKey 1234", true)] +#[case::basic("Basic dXNlcg==", false)] +fn match_headers_with_or_matchers(#[case] actual: &str, #[case] is_ok: bool) { + let expected = hashmap! { "authorization".to_string() => vec!["Bearer token".to_string()] }; + let actual = hashmap! { "authorization".to_string() => vec![actual.to_string()] }; + let rules = or_rules("header", "authorization", &[ + MatchingRule::Regex("^Bearer \\S+$".to_string()), + MatchingRule::Regex("^ApiKey \\d+$".to_string()) + ]); + let context = crate::HeaderMatchingContext::new( + &CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &rules, &hashmap!{})); + let result = match_headers(Some(expected), Some(actual), &context); + expect!(result.values().flatten().count() == 0).to(be_equal_to(is_ok)); +} From c4892ba509fb0e813226f2d2c7b925bb36ebfde7 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 9 Nov 2026 17:11:53 +0000 Subject: [PATCH 2/6] fix(ffi): replace existing rules when integration JSON combines a path's rules with different logic add_rule_list_to_category used to append OR rules to an existing AND list (or the reverse), silently changing how the existing rules are combined. Rules with a different logic now replace the existing ones with a warning, as Pact-JVM's `or` DSL does, and rules with the same logic are appended. Co-Authored-By: Claude Opus 5.5 --- rust/pact_ffi/src/mock_server/bodies.rs | 181 ++++++++++++++++++++++-- 1 file changed, 172 insertions(+), 9 deletions(-) diff --git a/rust/pact_ffi/src/mock_server/bodies.rs b/rust/pact_ffi/src/mock_server/bodies.rs index f2fba0ad1..1bbd24853 100644 --- a/rust/pact_ffi/src/mock_server/bodies.rs +++ b/rust/pact_ffi/src/mock_server/bodies.rs @@ -304,21 +304,40 @@ fn rule_logic_from_integration_json(m: &Map) -> anyhow::Result rule_list.rules.len() { - warn!("Path '{}' already has matching rules, they will now be combined with OR", path); - } - existing.rule_logic = RuleLogic::Or; + match matching_rules.rules.get_mut(path) { + Some(existing) if !existing.rules.is_empty() && existing.rule_logic != rule_list.rule_logic => { + warn!("Path '{}' already has matching rules combined with {:?} ({:?}), they will be replaced \ + with the rules combined with {:?} ({:?})", path, existing.rule_logic, existing.rules, + rule_list.rule_logic, rule_list.rules); + existing.rules = rule_list.rules.clone(); + existing.rule_logic = rule_list.rule_logic; + } + Some(existing) => { + existing.rules.extend(rule_list.rules.iter().cloned()); + existing.rule_logic = rule_list.rule_logic; + } + None => { + matching_rules.rules.insert(path.clone(), RuleList { + rules: rule_list.rules.clone(), + rule_logic: rule_list.rule_logic, + cascaded: false + }); } } } @@ -908,6 +927,150 @@ use pretty_assertions::assert_eq; expect!(result.ok().map(|(rule_list, _)| rule_list.rule_logic)).to(be_equal_to(expected)); } + // Issue #249 + #[test] + fn rule_list_from_integration_json_combine_with_a_single_matcher() { + let json = json!({ + "pact:matcher:type": "regex", + "regex": "\\d+", + "pact:matcher:combine": "OR" + }); + let result = rule_list_from_integration_json(json.as_object().unwrap()); + expect!(result.ok().map(|(rule_list, _)| rule_list)).to(be_some().value(RuleList { + rules: vec![ MatchingRule::Regex("\\d+".to_string()) ], + rule_logic: RuleLogic::Or, + cascaded: false + })); + } + + fn rule_list(rules: Vec, rule_logic: RuleLogic) -> RuleList { + RuleList { rules, rule_logic, cascaded: false } + } + + // Issue #249 + #[rstest] + #[case::new_path( + None, + rule_list(vec![MatchingRule::Type, MatchingRule::Null], RuleLogic::Or), + rule_list(vec![MatchingRule::Type, MatchingRule::Null], RuleLogic::Or) + )] + #[case::existing_rules_with_the_same_logic_are_kept( + Some(rule_list(vec![MatchingRule::Integer], RuleLogic::Or)), + rule_list(vec![MatchingRule::Null], RuleLogic::Or), + rule_list(vec![MatchingRule::Integer, MatchingRule::Null], RuleLogic::Or) + )] + #[case::existing_and_rules_are_replaced_by_or_rules( + Some(rule_list(vec![MatchingRule::Regex("\\d+".to_string())], RuleLogic::And)), + rule_list(vec![MatchingRule::Type, MatchingRule::Null], RuleLogic::Or), + rule_list(vec![MatchingRule::Type, MatchingRule::Null], RuleLogic::Or) + )] + #[case::existing_or_rules_are_replaced_by_and_rules( + Some(rule_list(vec![MatchingRule::Type, MatchingRule::Null], RuleLogic::Or)), + rule_list(vec![MatchingRule::Integer], RuleLogic::And), + rule_list(vec![MatchingRule::Integer], RuleLogic::And) + )] + #[case::empty_rule_list_does_not_change_existing_rules( + Some(rule_list(vec![MatchingRule::Integer], RuleLogic::And)), + rule_list(vec![], RuleLogic::Or), + rule_list(vec![MatchingRule::Integer], RuleLogic::And) + )] + fn add_rule_list_to_category_test( + #[case] existing: Option, + #[case] rules: RuleList, + #[case] expected: RuleList + ) { + let path = DocPath::new_unwrap("$.a"); + let mut category = MatchingRuleCategory::empty("body"); + if let Some(existing) = existing { + category.rules.insert(path.clone(), existing); + } + add_rule_list_to_category(&mut category, &path, &rules); + expect!(category.rules.get(&path).cloned()).to(be_some().value(expected)); + } + + // Issue #249 + #[test_log::test] + fn process_object_with_or_matchers_on_an_object_with_nested_matchers() { + let json = json!({ + "a": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": { + "id": { "pact:matcher:type": "integer", "value": 100 }, + "name": "Fred" + } + } + }); + let mut matching_rules = MatchingRuleCategory::empty("body"); + let mut generators = Generators::default(); + let result = process_object(json.as_object().unwrap(), &mut matching_rules, + &mut generators, DocPath::root(), false); + + expect!(result).to(be_equal_to(json!({ "a": { "id": 100, "name": "Fred" } }))); + expect!(matching_rules.rules.get(&DocPath::new_unwrap("$.a")).cloned()).to(be_some().value( + rule_list(vec![ MatchingRule::Type, MatchingRule::Null ], RuleLogic::Or))); + expect!(matching_rules.rules.get(&DocPath::new_unwrap("$.a.id")).cloned()).to(be_some().value( + rule_list(vec![ MatchingRule::Integer ], RuleLogic::And))); + } + + // Issue #249 + #[test_log::test] + fn process_object_with_or_matchers_wrapping_another_matcher() { + // A path can only have one list of rules, so the outer OR rules replace the inner rule + let json = json!({ + "a": { + "pact:matcher:type": [ + { "pact:matcher:type": "integer" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": { "pact:matcher:type": "regex", "regex": "\\d+", "value": "100" } + } + }); + let mut matching_rules = MatchingRuleCategory::empty("body"); + let mut generators = Generators::default(); + let result = process_object(json.as_object().unwrap(), &mut matching_rules, + &mut generators, DocPath::root(), false); + + expect!(result).to(be_equal_to(json!({ "a": "100" }))); + expect!(matching_rules.rules.get(&DocPath::new_unwrap("$.a")).cloned()).to(be_some().value( + rule_list(vec![ MatchingRule::Integer, MatchingRule::Null ], RuleLogic::Or))); + } + + // Issue #249 + #[test_log::test] + fn process_object_with_or_matchers_in_array_items() { + let json = json!({ + "items": { + "pact:matcher:type": "type", + "min": 1, + "value": [ + { + "pact:matcher:type": [ + { "pact:matcher:type": "integer" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": 1 + } + ] + } + }); + let mut matching_rules = MatchingRuleCategory::empty("body"); + let mut generators = Generators::default(); + let result = process_object(json.as_object().unwrap(), &mut matching_rules, + &mut generators, DocPath::root(), false); + + expect!(result).to(be_equal_to(json!({ "items": [ 1 ] }))); + expect!(matching_rules.rules.get(&DocPath::new_unwrap("$.items")).cloned()).to(be_some().value( + rule_list(vec![ MatchingRule::MinType(1) ], RuleLogic::And))); + expect!(matching_rules.rules.get(&DocPath::new_unwrap("$.items[*]")).cloned()).to(be_some().value( + rule_list(vec![ MatchingRule::Integer, MatchingRule::Null ], RuleLogic::Or))); + } + #[test_log::test] #[allow(deprecated)] fn matcher_from_integration_json_test() { From 6b4fd1145abbdef2481d35a9a68934be2a068c2d Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 9 Nov 2026 17:24:46 +0000 Subject: [PATCH 3/6] docs(ffi): document nullable objects, wrapped matchers and invalid values for pact:matcher:combine * The combine value is not case-sensitive, and an invalid value writes null. * Rules inside an object value still apply to its children (null-or-object). * An OR matcher whose value is another matcher replaces that matcher's rules, with a warning, as Pact-JVM's or matcher does. * Remove the V2 matching engine limitation, now that it supports OR. Co-Authored-By: Claude Opus 5.5 --- rust/pact_ffi/IntegrationJson.md | 53 ++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/rust/pact_ffi/IntegrationJson.md b/rust/pact_ffi/IntegrationJson.md index 5ba7bac6a..64497daa1 100644 --- a/rust/pact_ffi/IntegrationJson.md +++ b/rust/pact_ffi/IntegrationJson.md @@ -220,8 +220,8 @@ So the resulting intermediate JSON would be something like: ### Combining matching rules with OR The `pact:matcher:combine` attribute sets how the matching rules are combined. It can be either `AND` (the default, -all the rules must match) or `OR` (at least one of the rules must match). Any other value is an error, and the -matching rules will be ignored. +all the rules must match) or `OR` (at least one of the rules must match). The value is not case-sensitive. Any other +value is logged as an error: the matching rules are ignored, and the value at that path is written as `null`. For example, a `name` that is either a string or null: @@ -249,6 +249,54 @@ The rules are written to the Pact file as a rule list combined with `OR`: `OR` can be used for bodies (JSON and XML), headers and query parameters. +#### Nullable objects + +If the example `value` is an object or array, any matching rules defined inside it are still applied to its +children. This lets you describe an optional object (for example, an address that is either null or an object whose +`number` is an integer): + +```json +{ + "address": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": { + "street": "Main St", + "number": { "pact:matcher:type": "integer", "value": 42 } + } + } +} +``` + +This writes an `OR` rule list for `$.address` and an `integer` rule for `$.address.number`. A request with +`"address": null` matches, and the rules for the children are only checked when the value is not null. + +#### Wrapping another matcher + +Each path in the Pact file has a single rule list, combined with either `AND` or `OR`. If the `value` of an `OR` +matcher is itself a matcher for the same path, its rules are replaced by the `OR` rules and a warning is logged. This +is the same as the `or` matcher in Pact-JVM. For example, this only writes `integer OR null` for `$.id`, not the +`regex` rule: + +```json +{ + "id": { + "pact:matcher:type": [ + { "pact:matcher:type": "integer" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": { "pact:matcher:type": "regex", "regex": "^\\d+$", "value": "100" } + } +} +``` + +Put all the alternatives in the one `pact:matcher:type` array instead. Rules for the same path that use the same +logic are added to the list. + #### Limitations * All the alternatives are applied to the top level `value`, so matchers that compare against the example (like @@ -260,7 +308,6 @@ The rules are written to the Pact file as a rule list combined with `OR`: matches the number `5`). * Use `OR` with care. Only the top level example value is used for the consumer test, so the other alternatives are never exercised against your consumer code. -* The experimental V2 matching engine (`PACT_MATCHING_ENGINE=v2`) does not support `OR`. ## Supporting matching rule definitions From 32460bcd8290300d2c754239903a9030c9831a27 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 9 Nov 2026 17:11:53 +0000 Subject: [PATCH 4/6] fix(matching): support rules combined with OR in the V2 matching engine * The `or` action folded its results from OK, so it never failed. It now folds from the first child result. * Errors from the branches of a successful `or` are no longer reported as mismatches. * An object with rules combined with OR that include a null matcher now accepts a null value, and only checks the object's entries when the value is not null (new `json:not-null` action). Co-Authored-By: Claude Opus 5.5 --- rust/pact_matching/src/engine/bodies/json.rs | 36 +++- rust/pact_matching/src/engine/interpreter.rs | 42 ++++- rust/pact_matching/src/engine/mod.rs | 11 +- rust/pact_matching/src/engine/tests/mod.rs | 1 + .../src/engine/tests/or_matcher_tests.rs | 175 ++++++++++++++++++ 5 files changed, 260 insertions(+), 5 deletions(-) create mode 100644 rust/pact_matching/src/engine/tests/or_matcher_tests.rs diff --git a/rust/pact_matching/src/engine/bodies/json.rs b/rust/pact_matching/src/engine/bodies/json.rs index e6da0c51b..b4a63b15f 100644 --- a/rust/pact_matching/src/engine/bodies/json.rs +++ b/rust/pact_matching/src/engine/bodies/json.rs @@ -99,7 +99,41 @@ impl JsonPlanBuilder { let each_value_context = Self::each_value_context(context, path, &rules, false); root_node.add(Self::build_for_each_value_node(&each_value_context, path, template)); } - } else if entries.is_empty() { + } else if Self::is_or_with_null(&rules) { + // The rules are combined with OR and allow a null value, so the actual value must match the + // rules, and the structure of the object is only checked if it is not null + root_node.add(ExecutionPlanNode::annotation(rules.generate_description(true))); + root_node.add(build_matching_rule_node(&ExecutionPlanNode::value_node(json.clone()), + &ExecutionPlanNode::resolve_current_value(path), &rules, true, + context.config.show_types_in_errors)); + let mut structure_node = ExecutionPlanNode::container(path); + Self::process_object_entries(context, path, &mut structure_node, entries); + for child in structure_node.children { + root_node.add( + ExecutionPlanNode::action("if") + .add(ExecutionPlanNode::action("json:not-null") + .add(ExecutionPlanNode::resolve_current_value(path))) + .add(child) + ); + } + } else { + Self::process_object_entries(context, path, root_node, entries); + } + } + + /// If the rules are combined with OR and include a null matcher + fn is_or_with_null(rules: &RuleList) -> bool { + !rules.cascaded && rules.rule_logic == RuleLogic::Or && rules.rules.len() > 1 && + rules.rules.iter().any(|rule| matches!(rule, MatchingRule::Null)) + } + + fn process_object_entries( + context: &PlanMatchingContext, + path: &DocPath, + root_node: &mut ExecutionPlanNode, + entries: &Map + ) { + if entries.is_empty() { root_node.add( ExecutionPlanNode::action("json:expect:empty") .add(ExecutionPlanNode::value_node("OBJECT")) diff --git a/rust/pact_matching/src/engine/interpreter.rs b/rust/pact_matching/src/engine/interpreter.rs index 899b80df0..5fc81e688 100644 --- a/rust/pact_matching/src/engine/interpreter.rs +++ b/rust/pact_matching/src/engine/interpreter.rs @@ -312,6 +312,7 @@ impl ExecutionPlanInterpreter { "json:expect:not-empty" => self.execute_json_expect_empty(action, value_resolver, node, &action_path, false), "json:match:length" => self.execute_json_match_length(action, value_resolver, node, &action_path), "json:expect:entries" => self.execute_json_expect_entries(action, value_resolver, node, &action_path), + "json:not-null" => self.execute_json_not_null(action, value_resolver, node, &action_path), "check:exists" => self.execute_check_exists(action, value_resolver, node, &action_path), "expect:entries" => self.execute_check_entries(action, value_resolver, node, &action_path), "expect:only-entries" => self.execute_check_entries(action, value_resolver, node, &action_path), @@ -1866,6 +1867,40 @@ impl ExecutionPlanInterpreter { } } + /// Returns a boolean value of true if the argument is a value that is not a JSON null. Unlike + /// the `json:expect:*` actions, it does not result in an error for a JSON null value. + fn execute_json_not_null( + &mut self, + action: &str, + value_resolver: &dyn ValueResolver, + node: ExecutionPlanNode, + action_path: &Vec + ) -> ExecutionPlanNode { + let ExecutionPlanNode { node_type, children, .. } = node; + match self.validate_one_arg(children, action, value_resolver, &action_path) { + Ok(value) => { + let not_null = match value.value().unwrap_or_default() { + NodeResult::VALUE(NodeValue::NULL) => false, + NodeResult::VALUE(NodeValue::JSON(Value::Null)) => false, + NodeResult::VALUE(_) => true, + _ => false + }; + ExecutionPlanNode { + node_type, + result: Some(NodeResult::VALUE(NodeValue::BOOL(not_null))), + children: vec![value] + } + } + Err(err) => { + ExecutionPlanNode { + node_type, + result: Some(NodeResult::ERROR(err.to_string())), + children: vec![] + } + } + } + } + fn execute_check_exists( &mut self, action: &str, @@ -2429,9 +2464,10 @@ impl ExecutionPlanInterpreter { Ok((result_children, values)) => { ExecutionPlanNode { node_type, - result: Some(values.iter().fold(NodeResult::OK, |result, value| { - result.or(value) - })), + // Fold from the first child result, as folding from OK would always result in OK + result: Some(values.split_first() + .map(|(first, rest)| rest.iter().fold(first.clone(), |result, value| result.or(value))) + .unwrap_or(NodeResult::OK)), children: result_children } } diff --git a/rust/pact_matching/src/engine/mod.rs b/rust/pact_matching/src/engine/mod.rs index b4e343b6f..79aeb2df8 100644 --- a/rust/pact_matching/src/engine/mod.rs +++ b/rust/pact_matching/src/engine/mod.rs @@ -1286,7 +1286,13 @@ impl ExecutionPlanNode { self.is_container() && !self.has_child_containers() } - /// If this node is a container + /// If this node is an OR action node that has been executed successfully + pub fn is_successful_or(&self) -> bool { + matches!(&self.node_type, PlanNodeType::ACTION(action) if action == "or") + && matches!(&self.result, Some(result) if !matches!(result, NodeResult::ERROR(_))) + } + + /// If this node is a container node pub fn is_container(&self) -> bool { if let PlanNodeType::CONTAINER(_) = &self.node_type { true @@ -1314,6 +1320,9 @@ impl ExecutionPlanNode { if child.is_container() && terminator == Terminator::ALL || !child.is_container() { if let Some(NodeResult::ERROR(error)) = &child.result { errors.push(error.clone()); + } else if child.is_successful_or() { + // Only one branch of an OR needs to succeed, so errors from the other branches are not mismatches + continue; } errors.extend_from_slice(child.child_errors(terminator).as_slice()); } diff --git a/rust/pact_matching/src/engine/tests/mod.rs b/rust/pact_matching/src/engine/tests/mod.rs index cf45868e7..7371603a9 100644 --- a/rust/pact_matching/src/engine/tests/mod.rs +++ b/rust/pact_matching/src/engine/tests/mod.rs @@ -31,6 +31,7 @@ mod each_value_tests; mod walk_tree_tests; mod query_tests; mod header_tests; +mod or_matcher_tests; #[rstest( case("", "''"), diff --git a/rust/pact_matching/src/engine/tests/or_matcher_tests.rs b/rust/pact_matching/src/engine/tests/or_matcher_tests.rs new file mode 100644 index 000000000..b1b9b1428 --- /dev/null +++ b/rust/pact_matching/src/engine/tests/or_matcher_tests.rs @@ -0,0 +1,175 @@ +//! Tests for matching rules combined with OR (`RuleLogic::Or`) in the V2 matching engine + +use bytes::Bytes; +use pretty_assertions::assert_eq; + +use pact_models::bodies::OptionalBody; +use pact_models::content_types::JSON; +use pact_models::matchingrules::{MatchingRule, MatchingRuleCategory, MatchingRules, RuleLogic}; +use pact_models::path_exp::DocPath; +use pact_models::prelude::v4::SynchronousHttp; +use pact_models::v4::http_parts::HttpResponse; +use pact_models::v4::interaction::V4Interaction; + +use crate::engine::{build_response_plan, execute_response_plan, PlanMatchingContext}; +use crate::engine::context::MatchingConfiguration; +use crate::Mismatch; + +fn body_rules(rules: Vec<(&str, MatchingRule, RuleLogic)>) -> MatchingRuleCategory { + let mut category = MatchingRuleCategory::empty("body"); + for (path, rule, logic) in rules { + category.add_rule(DocPath::new(path).unwrap(), rule, logic); + } + category +} + +/// Matches the actual body to the expected one with the V2 engine, and returns the body mismatches +/// as `path: mismatch` +fn mismatches(rules: &MatchingRuleCategory, expected: &str, actual: &str) -> Vec { + let mut matching_rules = MatchingRules::default(); + matching_rules.add_rules("body", rules.clone()); + let expected_response = HttpResponse { + body: OptionalBody::Present(Bytes::from(expected.to_string()), Some(JSON.clone()), None), + matching_rules, + .. HttpResponse::default() + }; + let actual_response = HttpResponse { + body: OptionalBody::Present(Bytes::from(actual.to_string()), Some(JSON.clone()), None), + .. HttpResponse::default() + }; + let interaction = SynchronousHttp { + response: expected_response.clone(), + .. SynchronousHttp::default() + }; + let context = PlanMatchingContext { + interaction: interaction.boxed_v4(), + config: MatchingConfiguration { + allow_unexpected_entries: true, + log_plan_summary: false, + .. MatchingConfiguration::default() + }, + .. PlanMatchingContext::default() + }; + let plan = build_response_plan(&expected_response, &context).unwrap(); + let executed_plan = execute_response_plan(&plan, &actual_response, &context).unwrap(); + let mismatches: Vec = executed_plan.into(); + mismatches.iter() + .filter_map(|m| match m { + Mismatch::BodyMismatch { path, mismatch, .. } => Some(format!("{}: {}", path, mismatch)), + _ => None + }) + .collect() +} + + +fn regex(r: &str) -> MatchingRule { MatchingRule::Regex(r.to_string()) } + +#[test_log::test] +fn scalar_with_type_or_null() { + let rules = body_rules(vec![ + ("$.a", MatchingRule::Type, RuleLogic::Or), + ("$.a", MatchingRule::Null, RuleLogic::Or) + ]); + let expected = r#"{"a":"string"}"#; + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":"other"}"#)); + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":null}"#)); + assert_eq!(false, mismatches(&rules, expected, r#"{"a":100}"#).is_empty()); +} + +#[test_log::test] +fn scalar_with_two_regexes() { + let rules = body_rules(vec![ + ("$.a", regex("^\\d+$"), RuleLogic::Or), + ("$.a", regex("^[a-z]+$"), RuleLogic::Or) + ]); + let expected = r#"{"a":"100"}"#; + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":"200"}"#)); + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":"abc"}"#)); + assert_eq!(false, mismatches(&rules, expected, r#"{"a":"ABC"}"#).is_empty()); +} + +#[test_log::test] +fn integer_or_decimal() { + let rules = body_rules(vec![ + ("$.a", MatchingRule::Integer, RuleLogic::Or), + ("$.a", MatchingRule::Decimal, RuleLogic::Or) + ]); + let expected = r#"{"a":100}"#; + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":1}"#)); + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":1.5}"#)); + assert_eq!(false, mismatches(&rules, expected, r#"{"a":"1"}"#).is_empty()); +} + +#[test_log::test] +fn object_with_type_or_null() { + let rules = body_rules(vec![ + ("$.a", MatchingRule::Type, RuleLogic::Or), + ("$.a", MatchingRule::Null, RuleLogic::Or) + ]); + let expected = r#"{"a":{"b":"string"}}"#; + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":{"b":"other"}}"#)); + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":null}"#)); +} + +#[test_log::test] +fn array_with_type_or_null() { + let rules = body_rules(vec![ + ("$.a", MatchingRule::MinType(1), RuleLogic::Or), + ("$.a", MatchingRule::Null, RuleLogic::Or) + ]); + let expected = r#"{"a":[1]}"#; + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":[2,3]}"#)); + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":null}"#)); +} + +#[test_log::test] +fn object_with_type_or_null_rejects_other_types() { + let rules = body_rules(vec![ + ("$.a", MatchingRule::Type, RuleLogic::Or), + ("$.a", MatchingRule::Null, RuleLogic::Or) + ]); + let expected = r#"{"a":{"b":"string"}}"#; + let result = mismatches(&rules, expected, r#"{"a":"string"}"#); + assert_eq!(false, result.is_empty()); + assert!(result.iter().all(|m| m.starts_with("$.a")), "{:?}", result); +} + +#[test_log::test] +fn object_with_type_or_null_still_applies_the_nested_rules() { + let rules = body_rules(vec![ + ("$.a", MatchingRule::Type, RuleLogic::Or), + ("$.a", MatchingRule::Null, RuleLogic::Or), + ("$.a.id", MatchingRule::Integer, RuleLogic::And) + ]); + let expected = r#"{"a":{"id":100}}"#; + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":{"id":200}}"#)); + assert_eq!(Vec::::new(), mismatches(&rules, expected, r#"{"a":null}"#)); + assert_eq!(vec!["$.a.id: Expected '200' (String) to be an integer".to_string()], + mismatches(&rules, expected, r#"{"a":{"id":"200"}}"#)); + assert_eq!(false, mismatches(&rules, expected, r#"{"a":{}}"#).is_empty()); +} + +#[test_log::test] +fn a_successful_or_does_not_report_the_errors_from_the_other_branches() { + let rules = body_rules(vec![ + ("$.a", MatchingRule::Integer, RuleLogic::Or), + ("$.a", MatchingRule::Null, RuleLogic::Or), + ("$.b", MatchingRule::Integer, RuleLogic::And) + ]); + let expected = r#"{"a":100,"b":100}"#; + assert_eq!(vec!["$.b: Expected 'x' (String) to be an integer".to_string()], + mismatches(&rules, expected, r#"{"a":null,"b":"x"}"#)); + assert_eq!(vec!["$.b: Expected 'x' (String) to be an integer".to_string()], + mismatches(&rules, expected, r#"{"a":200,"b":"x"}"#)); +} + +#[test_log::test] +fn a_failed_or_reports_the_errors_from_all_the_branches() { + let rules = body_rules(vec![ + ("$.a", MatchingRule::Integer, RuleLogic::Or), + ("$.a", MatchingRule::Null, RuleLogic::Or) + ]); + let result = mismatches(&rules, r#"{"a":100}"#, r#"{"a":"x"}"#); + assert!(result.iter().any(|m| m.contains("to be an integer")), "{:?}", result); + assert!(result.iter().any(|m| m.to_lowercase().contains("null")), "{:?}", result); +} From cd99ca30f4113f97ea8da1dabcfca834899b3eb0 Mon Sep 17 00:00:00 2001 From: Sergey Shtubey Date: Fri, 13 Nov 2026 16:37:52 +0200 Subject: [PATCH 5/6] fix(ffi): keep the example value when pact:matcher:combine is invalid An invalid `pact:matcher:combine` value wrote the body value as `null`, while headers and query parameters kept it. The rules are still ignored and the error logged, but the example value (and any rules nested in it) is now kept for bodies too. Also documents that a generator must be on the outer object of an OR list. Co-Authored-By: Claude Opus 5.5 --- rust/pact_ffi/IntegrationJson.md | 24 +++++++++++- rust/pact_ffi/src/mock_server/bodies.rs | 37 +++++++++++++++++- rust/pact_ffi/src/mock_server/handles.rs | 48 ++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 3 deletions(-) diff --git a/rust/pact_ffi/IntegrationJson.md b/rust/pact_ffi/IntegrationJson.md index 64497daa1..5090bf33c 100644 --- a/rust/pact_ffi/IntegrationJson.md +++ b/rust/pact_ffi/IntegrationJson.md @@ -221,7 +221,10 @@ So the resulting intermediate JSON would be something like: The `pact:matcher:combine` attribute sets how the matching rules are combined. It can be either `AND` (the default, all the rules must match) or `OR` (at least one of the rules must match). The value is not case-sensitive. Any other -value is logged as an error: the matching rules are ignored, and the value at that path is written as `null`. +value is logged as an error, and the matching rules (and any generator from `pact:matcher:type`) for that value are +ignored. The example `value` is still used, along with any matching rules nested in it, for bodies, headers, query +parameters and paths alike. The FFI function still returns success, so check the logs if the rules are missing from +the Pact file. For example, a `name` that is either a string or null: @@ -249,6 +252,25 @@ The rules are written to the Pact file as a rule list combined with `OR`: `OR` can be used for bodies (JSON and XML), headers and query parameters. +A `pact:generator:type` inside an entry of the `pact:matcher:type` array is ignored, as it is for any list of +matchers. Put the generator on the outer object instead: + +```json +{ + "id": { + "pact:matcher:type": [ + { "pact:matcher:type": "integer" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "pact:generator:type": "RandomInt", + "min": 1, + "max": 1000, + "value": 42 + } +} +``` + #### Nullable objects If the example `value` is an object or array, any matching rules defined inside it are still applied to its diff --git a/rust/pact_ffi/src/mock_server/bodies.rs b/rust/pact_ffi/src/mock_server/bodies.rs index 1bbd24853..e168ed018 100644 --- a/rust/pact_ffi/src/mock_server/bodies.rs +++ b/rust/pact_ffi/src/mock_server/bodies.rs @@ -130,7 +130,13 @@ fn process_matcher( _ => Err(anyhow!("ArrayContains 'variants' attribute is missing or not an array")) } } else { - rule_list_from_integration_json(obj).map(|(rule_list, generator)| { + let rule_list_result = match rule_logic_from_integration_json(obj) { + // The rules can't be combined, so they are ignored, but the example value is kept (the same + // as for headers and query parameters) + Err(_) => Ok((RuleList::empty(RuleLogic::And), None)), + Ok(_) => rule_list_from_integration_json(obj) + }; + rule_list_result.map(|(rule_list, generator)| { let has_values_matcher = rule_list.rules.iter().any(MatchingRule::is_values_matcher); let json_value = match obj.get("value") { @@ -907,10 +913,37 @@ use pretty_assertions::assert_eq; let result = process_object(json.as_object().unwrap(), &mut matching_rules, &mut generators, DocPath::root(), false); - expect!(result).to(be_equal_to(json!({ "a": null }))); + // The rules are ignored, but the example value is kept + expect!(result).to(be_equal_to(json!({ "a": "string" }))); expect!(matching_rules.is_empty()).to(be_true()); } + // Issue #249 + #[test_log::test] + fn process_object_with_invalid_matcher_combine_value_keeps_the_nested_matchers() { + let json = json!({ + "a": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "XOR", + "value": { + "id": { "pact:matcher:type": "integer", "value": 100 } + } + } + }); + let mut matching_rules = MatchingRuleCategory::empty("body"); + let mut generators = Generators::default(); + let result = process_object(json.as_object().unwrap(), &mut matching_rules, + &mut generators, DocPath::root(), false); + + expect!(result).to(be_equal_to(json!({ "a": { "id": 100 } }))); + expect!(matching_rules.rules.get(&DocPath::new_unwrap("$.a"))).to(be_none()); + expect!(matching_rules.rules.get(&DocPath::new_unwrap("$.a.id")).cloned()).to(be_some().value( + RuleList::new(MatchingRule::Integer))); + } + #[rstest] #[case(json!({}), Some(RuleLogic::And))] #[case(json!({ "pact:matcher:combine": null }), Some(RuleLogic::And))] diff --git a/rust/pact_ffi/src/mock_server/handles.rs b/rust/pact_ffi/src/mock_server/handles.rs index b8ae1c284..dc93e994e 100644 --- a/rust/pact_ffi/src/mock_server/handles.rs +++ b/rust/pact_ffi/src/mock_server/handles.rs @@ -3469,6 +3469,54 @@ mod tests { expect!(check("not-an-id")).to(be_err()); } + // Issue #249 + #[test] + fn from_integration_json_v2_with_an_invalid_matcher_combine_value_keeps_the_example() { + let mut rules = MatchingRules::default(); + let mut generators = Generators::default(); + let mut path = DocPath::root(); + path.push_field("x-id"); + let value = r#"{ + "pact:matcher:type": [ + { "pact:matcher:type": "regex", "regex": "^\\d+$" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "XOR", + "value": "100" + }"#; + + let result = from_integration_json_v2(&mut rules, &mut generators, value, path.clone(), "header", 0); + expect!(result).to(be_equal_to(Either::Left("100".to_string()))); + expect!(rules.rules_for_category("header").map(|category| category.is_empty()).unwrap_or(true)).to(be_true()); + } + + // Issue #249 + #[test] + fn from_integration_json_v2_with_or_matchers_and_a_generator() { + let mut rules = MatchingRules::default(); + let mut generators = Generators::default(); + let mut path = DocPath::root(); + path.push_field("x-id"); + let value = r#"{ + "pact:matcher:type": [ + { "pact:matcher:type": "regex", "regex": "^\\d+$" }, + { "pact:matcher:type": "regex", "regex": "^none$" } + ], + "pact:matcher:combine": "OR", + "pact:generator:type": "RandomInt", + "min": 1, + "max": 1000, + "value": "42" + }"#; + + let result = from_integration_json_v2(&mut rules, &mut generators, value, path.clone(), "header", 0); + expect!(result).to(be_equal_to(Either::Left("42".to_string()))); + let rule_list = rules.rules_for_category("header").unwrap().rules.get(&path).cloned().unwrap(); + expect!(rule_list.rule_logic).to(be_equal_to(pact_models::matchingrules::RuleLogic::Or)); + expect!(generators.categories.get(&generators::GeneratorCategory::HEADER).and_then(|category| category.get(&path)).cloned()) + .to(be_some().value(generators::Generator::RandomInt(1, 1000))); + } + #[test] fn pact_handles() { let pact_handle = PactHandle::new("TestHandlesC", "TestHandlesP"); From 8c68fa70acd9c915e4a1f130c63a43192492bce4 Mon Sep 17 00:00:00 2001 From: Sergey Shtubey Date: Fri, 13 Nov 2026 17:22:24 +0200 Subject: [PATCH 6/6] Remove changes in .gitignore --- .gitignore | 2 -- 1 file changed, 2 deletions(-) diff --git a/.gitignore b/.gitignore index a98d0825d..3a8ab2db8 100644 --- a/.gitignore +++ b/.gitignore @@ -13,8 +13,6 @@ target/ # Generated Release Artifacts release_artifacts -out/ - node_modules/ *.log .idea/