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/compatibility-suite/pact-compatibility-suite/features/V3/matching_rules.feature b/compatibility-suite/pact-compatibility-suite/features/V3/matching_rules.feature index ec9af8e64..6b3b4caf3 100644 --- a/compatibility-suite/pact-compatibility-suite/features/V3/matching_rules.feature +++ b/compatibility-suite/pact-compatibility-suite/features/V3/matching_rules.feature @@ -269,3 +269,89 @@ Feature: V3 era Matching Rules When the request is compared to the expected one Then the comparison should NOT be OK And the mismatches will contain a mismatch with error "$.four" -> "Expected 100 (Integer) to be the same type as 'a' (String)" + + Scenario: Supports matching rules combined with OR (positive case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-regex-matcher-v3.json | + And the following requests are received: + | body | desc | + | JSON: { "one": "100", "two": "b" } | matches the first rule | + | JSON: { "one": "abc", "two": "b" } | matches the second rule | + When the requests are compared to the expected one + Then the comparison should be OK + + Scenario: Supports matching rules combined with OR (negative case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-regex-matcher-v3.json | + And a request is received with the following: + | body | + | JSON: { "one": "A1", "two": "b" } | + When the request is compared to the expected one + Then the comparison should NOT be OK + And the mismatches will contain a mismatch with error "$.one" -> "Expected 'A1' to match '^\d+$'" + And the mismatches will contain a mismatch with error "$.one" -> "Expected 'A1' to match '^[a-z]+$'" + + Scenario: Supports an integer or decimal matcher combined with OR (positive case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-number-matcher-v3.json | + And the following requests are received: + | body | desc | + | JSON: { "one": 100, "two": "b" } | integer | + | JSON: { "one": 100.25, "two": "b" } | decimal | + When the requests are compared to the expected one + Then the comparison should be OK + + Scenario: Supports an integer or decimal matcher combined with OR (negative case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-number-matcher-v3.json | + And a request is received with the following: + | body | + | JSON: { "one": true, "two": "b" } | + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: Supports a type matcher combined with a null matcher with OR (positive case) + Given an expected request configured with the following: + | body | matching rules | + | file: 3-level.json | or-null-matcher-v3.json | + And the following requests are received: + | body | desc | + | JSON: { "one": { "a": { "ids": [1], "status": "OK" } }, "two": [ { "ids": [1], "status": "BAD" } ] } | an object | + | JSON: { "one": null, "two": [ { "ids": [1], "status": "BAD" } ] } | null | + When the requests are compared to the expected one + Then the comparison should be OK + + Scenario: Supports a type matcher combined with a null matcher with OR (negative case) + Given an expected request configured with the following: + | body | matching rules | + | file: 3-level.json | or-null-matcher-v3.json | + And a request is received with the following: + | body | + | JSON: { "one": "a string", "two": [ { "ids": [1], "status": "BAD" } ] } | + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: Supports header and query matching rules combined with OR (positive case) + Given an expected request configured with the following: + | query | headers | matching rules | + | a=1234 | 'X-TEST: 1234' | or-matcher-header-query-v3.json | + And the following requests are received: + | query | headers | desc | + | a=100 | 'X-TEST: 100' | matches the first rule | + | a=ABC | 'X-TEST: ABC' | matches the second rule | + When the requests are compared to the expected one + Then the comparison should be OK + + Scenario: Supports header and query matching rules combined with OR (negative case) + Given an expected request configured with the following: + | query | headers | matching rules | + | a=1234 | 'X-TEST: 1234' | or-matcher-header-query-v3.json | + And a request is received with the following: + | query | headers | + | a=abc | 'X-TEST: abc' | + When the request is compared to the expected one + Then the comparison should NOT be OK diff --git a/compatibility-suite/pact-compatibility-suite/features/V4/matching_rules.feature b/compatibility-suite/pact-compatibility-suite/features/V4/matching_rules.feature index a20ce3e04..1bab7b39e 100644 --- a/compatibility-suite/pact-compatibility-suite/features/V4/matching_rules.feature +++ b/compatibility-suite/pact-compatibility-suite/features/V4/matching_rules.feature @@ -155,3 +155,33 @@ Feature: V4 era Matching Rules When the request is compared to the expected one Then the comparison should NOT be OK And the mismatches will contain a mismatch with error "$.actions" -> "Variant at index 1 ({\"href\":\"http://api.x.io/orders/42/items\",\"method\":\"DELETE\",\"name\":\"delete-item\",\"title\":\"Delete Item\"}) was not found in the actual list" + + Scenario: Supports a not empty matcher combined with a null matcher with OR (positive case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-notempty-matcher-v4.json | + And a request is received with the following: + | body | + | JSON: { "one": "a", "two": "b" } | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: Supports a not empty matcher combined with a null matcher with OR (positive case, null value) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-notempty-matcher-v4.json | + And a request is received with the following: + | body | + | JSON: { "one": null, "two": "b" } | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: Supports a not empty matcher combined with a null matcher with OR (negative case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-notempty-matcher-v4.json | + And a request is received with the following: + | body | + | JSON: { "one": "", "two": "b" } | + When the request is compared to the expected one + Then the comparison should NOT be OK diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-matcher-header-query-v3.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-matcher-header-query-v3.json new file mode 100644 index 000000000..31846873a --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-matcher-header-query-v3.json @@ -0,0 +1,32 @@ +{ + "header": { + "X-TEST": { + "combine": "OR", + "matchers": [ + { + "match": "regex", + "regex": "^\\d+$" + }, + { + "match": "regex", + "regex": "^[A-Z]+$" + } + ] + } + }, + "query": { + "a": { + "combine": "OR", + "matchers": [ + { + "match": "regex", + "regex": "^\\d+$" + }, + { + "match": "regex", + "regex": "^[A-Z]+$" + } + ] + } + } +} diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-notempty-matcher-v4.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-notempty-matcher-v4.json new file mode 100644 index 000000000..49a8fceb3 --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-notempty-matcher-v4.json @@ -0,0 +1,15 @@ +{ + "body": { + "$.one": { + "combine": "OR", + "matchers": [ + { + "match": "notEmpty" + }, + { + "match": "null" + } + ] + } + } +} diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-null-matcher-v3.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-null-matcher-v3.json new file mode 100644 index 000000000..54ea9c1f0 --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-null-matcher-v3.json @@ -0,0 +1,15 @@ +{ + "body": { + "$.one": { + "combine": "OR", + "matchers": [ + { + "match": "type" + }, + { + "match": "null" + } + ] + } + } +} diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-number-matcher-v3.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-number-matcher-v3.json new file mode 100644 index 000000000..66848bb19 --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-number-matcher-v3.json @@ -0,0 +1,15 @@ +{ + "body": { + "$.one": { + "combine": "OR", + "matchers": [ + { + "match": "integer" + }, + { + "match": "decimal" + } + ] + } + } +} diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-regex-matcher-v3.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-regex-matcher-v3.json new file mode 100644 index 000000000..56ca4663d --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-regex-matcher-v3.json @@ -0,0 +1,17 @@ +{ + "body": { + "$.one": { + "combine": "OR", + "matchers": [ + { + "match": "regex", + "regex": "^\\d+$" + }, + { + "match": "regex", + "regex": "^[a-z]+$" + } + ] + } + } +} diff --git a/rust/pact_ffi/IntegrationJson.md b/rust/pact_ffi/IntegrationJson.md index 4de165257..64497daa1 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,98 @@ 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). 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: + +```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. + +#### 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 + `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. + ## 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..1bbd24853 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,66 @@ 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. +/// +/// A path can only have one list of rules, combined with a single logic (AND or OR). If the path +/// already has rules combined with the same logic, the new rules are appended to them. If it has +/// rules combined with a different logic, the combination (i.e. `A AND (B OR C)`) can not be +/// represented, so the new rules replace the existing ones (as setting an OR group does in +/// Pact-JVM) and a warning is logged. Merging them would silently change the meaning of the +/// existing rules. +pub(crate) fn add_rule_list_to_category( + matching_rules: &mut MatchingRuleCategory, + path: &DocPath, + rule_list: &RuleList +) { + if rule_list.rules.is_empty() { + return; + } + 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 + }); + } + } +} + /// 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 +863,214 @@ 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)); + } + + // 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() { 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/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); +} 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)); +}