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..f3589bcb9 100644 --- a/rust/pact_ffi/IntegrationJson.md +++ b/rust/pact_ffi/IntegrationJson.md @@ -4,7 +4,7 @@ To make setting up matching rules and generators easier for language implementat JSON format can be used with embedded rules in it. This JSON can be used for most interaction values (i.e. headers, query parameters, etc.) -For each value were matching rules or generators are required, a JSON object can be passed in with the following +For each value were matching rules or generators are required, a JSON object can be passed in with the following attributes: | Attribute | Description | Values | @@ -18,7 +18,7 @@ documented at [V4 matching rules](https://github.com/pact-foundation/pact-specif generators at [V4 generators](https://github.com/pact-foundation/pact-specification/tree/version-4#generators). For example: Assuming we want to use a regex matcher on the request path. The `pactffi_with_request` function allows us -to pass the JSON value in as the path value. So instead of calling +to pass the JSON value in as the path value. So instead of calling ```js pactffi_with_request(handle, "PUT", "/path/to/100") @@ -40,8 +40,8 @@ For paths, the value used must be a string value (or a primitive value that will Example JSON: ```json { - "value": "/path/to/100", - "pact:matcher:type": "regex", + "value": "/path/to/100", + "pact:matcher:type": "regex", "regex": "\\/path\\/to\\/\\d+" } ``` @@ -58,18 +58,18 @@ array should be used for the value). Single parameter JSON: ```json { - "value": "100", - "pact:matcher:type": "regex", + "value": "100", + "pact:matcher:type": "regex", "regex": "\\d+" } ``` -Multiple parameter JSON (this example doesn't make much sense, because query parameters are always string values, so +Multiple parameter JSON (this example doesn't make much sense, because query parameters are always string values, so will always have the same type. But it will check the minimum length): ```json { - "value": ["1"], - "pact:matcher:type": "type", + "value": ["1"], + "pact:matcher:type": "type", "min": 1 } ``` @@ -86,8 +86,8 @@ array should be used for the value). Single header value JSON: ```json { - "value": "100", - "pact:matcher:type": "regex", + "value": "100", + "pact:matcher:type": "regex", "regex": "\\d+" } ``` @@ -122,7 +122,7 @@ For example, add a type matcher to an `id` attribute and a regex matcher to the }, "created": { "value": "maybe", - "pact:matcher:type": "regex", + "pact:matcher:type": "regex", "regex": "(yes|no|maybe)" } } @@ -160,11 +160,12 @@ 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. +To provide multiple matchers, you need to provide an array format. For example, assume you have an API that returns results for a document store where the documents are keyed based on some index: ```json @@ -216,9 +217,137 @@ 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. + +The top level `value` is the example used for the consumer test. + +#### Alternatives with their own example values + +Each matcher in an `OR` list can have its own `value`. This makes it a complete alternative: the value is the +example for that alternative, and can contain matchers of its own. The alternatives can be any shape, so a value +can be an object of one shape or another, an object or an array, an array or a string, and so on. + +For example, a `contact` that can either be an object with an email, an object with a phone number, a non-empty +array of contacts, or null: + +```json +{ + "contact": { + "pact:matcher:type": [ + { + "pact:matcher:type": "type", + "value": { + "email": { "pact:matcher:type": "regex", "regex": "^[^@ ]+@[^@ ]+$", "value": "fred@example.com" } + } + }, + { + "pact:matcher:type": "type", + "value": { + "phone": { "pact:matcher:type": "regex", "regex": "^\\d+$", "value": "0123456789" } + } + }, + { "pact:matcher:type": "type", "min": 1, "value": [{ "email": "fred@example.com" }] }, + { "pact:matcher:type": "null", "value": null } + ], + "pact:matcher:combine": "OR", + "value": { "email": "fred@example.com" } + } +} +``` + +A value matches an alternative if it matches the alternative's example using the alternative's matchers, in the +same way as any other value and matchers. + +In the Pact file, the alternatives are stored as the matchers of a rule list combined with `OR`. Each one has a +`variant` attribute with its example value and its matching rules, with paths relative to the example value: + +```json +"$.contact": { + "combine": "OR", + "matchers": [ + { + "match": "type", + "variant": { + "value": { "email": "fred@example.com" }, + "rules": { + "$": { "combine": "AND", "matchers": [{ "match": "type" }] }, + "$.email": { "combine": "AND", "matchers": [{ "match": "regex", "regex": "^[^@ ]+@[^@ ]+$" }] } + } + } + }, + ... + ] +} +``` + +Implementations that don't support the `variant` attribute will ignore it, and use the matchers as a simple `OR`. + +#### Alternatives without example values + +If a matcher in an `OR` list doesn't have a `value`, it is applied to the top level example value. This is enough +when the alternatives can be checked without an example, like a field 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" + } +} +``` + +Matchers that compare against the example (like `type`) can only describe the shape of the top level example, so +use alternatives with their own example values for anything else. Also, 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`). + +An alternative can also be a list of matchers combined with `AND` or `OR`, as long as it has its own `value`: + +```json +{ + "id": { + "pact:matcher:type": [ + { + "pact:matcher:type": [ + { "pact:matcher:type": "regex", "regex": "^\\d+$" }, + { "pact:matcher:type": "include", "value": "1" } + ], + "value": "100" + }, + { "pact:matcher:type": "null", "value": null } + ], + "pact:matcher:combine": "OR", + "value": "100" + } +} +``` + +#### Headers, query parameters, paths and XML + +Alternatives also work for headers, query parameters, paths, status codes, and XML attributes and text. These +values are not JSON, so only the matchers for the alternative value itself are applied, and they are compared +against the alternative's example value (i.e. an `equality` alternative compares against its own `value`). + +#### Limitations + +* 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. +* XML elements can not have alternatives with their own example values, only simple `OR` lists. This is because the + matching rules for XML are keyed by the element names, so an alternative element would need the same name. +* Other Pact implementations may not support the `variant` attribute, and will use the matchers as a simple `OR`. +* 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) +You can use the [matching rule definition expressions](https://docs.rs/pact_models/latest/pact_models/matchingrules/expressions/index.html) in the `pact:matcher:type` field. For example, with the previous document result JSON, you could then use the following for the `relatesTo` field: diff --git a/rust/pact_ffi/src/mock_server/bodies.rs b/rust/pact_ffi/src/mock_server/bodies.rs index 88ca0c414..ec0cb3949 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, MatchingRuleVariant, 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,94 @@ 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). +/// +/// If the matching rules are combined with OR, each matcher that has its own example value becomes +/// a [`MatchingRule::Variant`], so the alternatives can be different shapes (i.e. an object or an +/// array). +pub fn rule_list_from_integration_json(m: &Map) -> anyhow::Result<(RuleList, Option)> { + build_rule_list(m, true) +} + +/// Builds a `RuleList` from a `Value` struct used by language integrations, like +/// [`rule_list_from_integration_json`], but without variants. This is for values that are not +/// JSON examples (i.e. XML elements). +pub(crate) fn plain_rule_list_from_integration_json(m: &Map) -> anyhow::Result<(RuleList, Option)> { + build_rule_list(m, false) +} + +fn build_rule_list(m: &Map, with_variants: bool) -> anyhow::Result<(RuleList, Option)> { + let rule_logic = rule_logic_from_integration_json(m)?; + let (rules, generator) = match m.get("pact:matcher:type") { + Some(Value::Array(matchers)) if rule_logic == RuleLogic::Or && with_variants => + (or_matchers_from_integration_json(matchers)?, None), + _ => matchers_from_integration_json(m)? + }; + Ok((RuleList { rules, rule_logic, cascaded: false }, generator)) +} + +/// Builds the matching rules for a list of matchers combined with OR. Each matcher that has its own +/// example value becomes a variant. +fn or_matchers_from_integration_json(matchers: &[Value]) -> anyhow::Result> { + let mut rules = vec![]; + for matcher in matchers { + match matcher { + Value::Object(map) if map.contains_key("value") => rules.push(variant_from_integration_json(map)?), + Value::Object(map) if map.get("pact:matcher:type").is_some_and(Value::is_array) => + bail!("Failed to create matching rule from JSON '{}': combined matchers in an OR list must have a value", matcher), + Value::Object(map) => rules.extend(matchers_from_integration_json(map)?.0), + _ => bail!("Failed to create matching rule from JSON '{}': it is not an object", matcher) + } + } + Ok(rules) +} + +/// Builds a [`MatchingRule::Variant`] from a matcher with its own example value. The matcher can +/// also be a list of matchers combined with `AND` or `OR`. +fn variant_from_integration_json(m: &Map) -> anyhow::Result { + let (rule_list, _) = rule_list_from_integration_json(m)?; + let rule = rule_list.rules.first().cloned() + .ok_or_else(|| anyhow!("Failed to create matching rule from JSON '{:?}': no matching rule found", m))?; + let mut variant_rules = MatchingRuleCategory::empty("body"); + let mut generators = Generators::default(); + let value = process_object(m, &mut variant_rules, &mut generators, DocPath::root(), false); + Ok(MatchingRule::Variant(Box::new(rule), Box::new(MatchingRuleVariant { value, rules: variant_rules }))) +} + +/// 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 +891,218 @@ 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()); + } + + // Issue #249 + #[test_log::test] + fn process_object_with_or_matchers_that_have_their_own_values() { + let json = json!({ + "a": { + "pact:matcher:type": [ + { + "pact:matcher:type": "type", + "value": { "street": { "pact:matcher:type": "regex", "regex": "\\w+", "value": "Main" } } + }, + { "pact:matcher:type": "type", "min": 1, "value": ["Main"] }, + { "pact:matcher:type": "null", "value": null } + ], + "pact:matcher:combine": "OR", + "value": { "street": "Main" } + } + }); + 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); + + let mut object_rules = MatchingRuleCategory::empty("body"); + object_rules.add_rule(DocPath::root(), MatchingRule::Type, RuleLogic::And); + object_rules.add_rule(DocPath::new_unwrap("$.street"), MatchingRule::Regex("\\w+".to_string()), RuleLogic::And); + let mut array_rules = MatchingRuleCategory::empty("body"); + array_rules.add_rule(DocPath::root(), MatchingRule::MinType(1), RuleLogic::And); + let mut null_rules = MatchingRuleCategory::empty("body"); + null_rules.add_rule(DocPath::root(), MatchingRule::Null, RuleLogic::And); + + expect!(result).to(be_equal_to(json!({ "a": { "street": "Main" } }))); + expect!(matching_rules.rules.get(&DocPath::new_unwrap("$.a")).cloned()).to(be_some().value(RuleList { + rules: vec![ + MatchingRule::Variant(Box::new(MatchingRule::Type), Box::new(MatchingRuleVariant { + value: json!({ "street": "Main" }), + rules: object_rules + })), + MatchingRule::Variant(Box::new(MatchingRule::MinType(1)), Box::new(MatchingRuleVariant { + value: json!(["Main"]), + rules: array_rules + })), + MatchingRule::Variant(Box::new(MatchingRule::Null), Box::new(MatchingRuleVariant { + value: Value::Null, + rules: null_rules + })) + ], + rule_logic: RuleLogic::Or, + cascaded: false + })); + // The example value only has the rules from the variants, not any of its own + expect!(matching_rules.rules.len()).to(be_equal_to(1)); + } + + // Issue #249 + #[test_log::test] + fn process_object_with_combined_matchers_as_or_alternatives() { + let json = json!({ + "a": { + "pact:matcher:type": [ + { + "pact:matcher:type": [ + { "pact:matcher:type": "regex", "regex": "^\\d+$" }, + { "pact:matcher:type": "include", "value": "1" } + ], + "value": "100" + }, + { + "pact:matcher:type": [ + { "pact:matcher:type": "type", "value": true }, + { "pact:matcher:type": "integer", "value": 1 } + ], + "pact:matcher:combine": "OR", + "value": true + } + ], + "pact:matcher:combine": "OR", + "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" }))); + let rule_list = matching_rules.rules.get(&DocPath::new_unwrap("$.a")).cloned().unwrap(); + expect!(rule_list.rule_logic).to(be_equal_to(RuleLogic::Or)); + + let MatchingRule::Variant(_, and_variant) = &rule_list.rules[0] else { panic!("expected a variant") }; + expect!(&and_variant.value).to(be_equal_to(&json!("100"))); + expect!(and_variant.rules.rules.get(&DocPath::root()).cloned()).to(be_some().value(RuleList { + rules: vec![ MatchingRule::Regex("^\\d+$".to_string()), MatchingRule::Include("1".to_string()) ], + rule_logic: RuleLogic::And, + cascaded: false + })); + + let MatchingRule::Variant(_, or_variant) = &rule_list.rules[1] else { panic!("expected a variant") }; + expect!(&or_variant.value).to(be_equal_to(&json!(true))); + let nested = or_variant.rules.rules.get(&DocPath::root()).cloned().unwrap(); + expect!(nested.rule_logic).to(be_equal_to(RuleLogic::Or)); + expect!(nested.rules.iter().all(|rule| matches!(rule, MatchingRule::Variant(..)))).to(be_true()); + } + + // Issue #249 + #[test_log::test] + fn process_object_with_combined_or_alternative_without_a_value() { + let json = json!({ + "a": { + "pact:matcher:type": [ + { "pact:matcher:type": [{ "pact:matcher:type": "type" }, { "pact:matcher:type": "null" }] }, + { "pact:matcher:type": "null", "value": null } + ], + "pact:matcher:combine": "OR", + "value": "x" + } + }); + 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_with_or_and_example_values() { + let json = json!({ + "pact:matcher:type": [ + { "pact:matcher:type": "type", "value": { "street": "Main" } }, + { "pact:matcher:type": "null", "value": null }, + { "pact:matcher:type": "number" } + ], + "pact:matcher:combine": "OR" + }); + let (rule_list, generator) = rule_list_from_integration_json(json.as_object().unwrap()).unwrap(); + + expect!(rule_list.rule_logic).to(be_equal_to(RuleLogic::Or)); + expect!(generator).to(be_none()); + expect!(matches!(&rule_list.rules[0], MatchingRule::Variant(rule, variant) + if **rule == MatchingRule::Type && variant.value == json!({ "street": "Main" }))).to(be_true()); + expect!(matches!(&rule_list.rules[1], MatchingRule::Variant(rule, variant) + if **rule == MatchingRule::Null && variant.value == Value::Null)).to(be_true()); + // A matcher without an example value is a plain rule + expect!(&rule_list.rules[2]).to(be_equal_to(&MatchingRule::Number)); + } + #[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..07baf707f 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,39 @@ mod tests { use super::from_integration_json_v2; + // Issue #249 + #[test] + fn from_integration_json_v2_with_or_matcher_variants_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+$", "value": "100" }, + { "pact:matcher:type": "regex", "regex": "^[a-f0-9-]{36}$", "value": "4a9f6b5e-2a0f-4c8e-9a3d-5c1b8e7f0a12" }, + { "pact:matcher:type": "equality", "value": "none" } + ], + "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.iter().all(|rule| matches!(rule, MatchingRule::Variant(..)))).to(be_true()); + + 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()); + // The equality alternative compares against its own example, not the top level one + expect!(check("none")).to(be_ok()); + expect!(check("100")).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..885203af7 100644 --- a/rust/pact_ffi/src/mock_server/xml.rs +++ b/rust/pact_ffi/src/mock_server/xml.rs @@ -15,10 +15,13 @@ 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, + plain_rule_list_from_integration_json, + rule_list_from_integration_json +}; pub fn generate_xml_body( attributes: &Map, @@ -75,10 +78,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)) = plain_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 +136,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 +228,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/src/models/expressions.rs b/rust/pact_ffi/src/models/expressions.rs index 9c887ab2d..2bd577020 100644 --- a/rust/pact_ffi/src/models/expressions.rs +++ b/rust/pact_ffi/src/models/expressions.rs @@ -295,7 +295,9 @@ impl MatchingRuleIterator { MatchingRule::EachValue(_) => None, // A plugin rule's configuration is a map of arbitrary keys, so unlike every other // rule there is no single scalar to expose. The JSON form carries all of it. - MatchingRule::Plugin { values, .. } => Some(CString::new(values.to_string()).unwrap()) + MatchingRule::Plugin { values, .. } => Some(CString::new(values.to_string()).unwrap()), + // Variants only come from rule lists combined with OR, never from an expression + MatchingRule::Variant(..) => None }; let rule_value = val.as_ref().map(|v| v.as_ptr()).unwrap_or_else(|| null()); let rule_result = MatchingRuleResult::MatchingRule(rule_id(rule), rule_value, rule.clone()); @@ -350,7 +352,8 @@ fn rule_id(rule: &MatchingRule) -> u16 { MatchingRule::Semver => 21, MatchingRule::EachKey(_) => 22, MatchingRule::EachValue(_) => 23, - MatchingRule::Plugin { .. } => 24 + MatchingRule::Plugin { .. } => 24, + MatchingRule::Variant(rule, _) => rule_id(rule) } } diff --git a/rust/pact_ffi/tests/tests.rs b/rust/pact_ffi/tests/tests.rs index bb797fa31..4cf57fc3d 100644 --- a/rust/pact_ffi/tests/tests.rs +++ b/rust/pact_ffi/tests/tests.rs @@ -1393,7 +1393,7 @@ fn merging_duplicate_http_interaction_without_state_with_pact_containing_two_htt pactffi_with_header_v2(i_handle2, InteractionPart::Request, accept.as_ptr(), 0, header.as_ptr()); let result_2 = pactffi_pact_handle_write_file(pact_handle, tmp_dir.as_ptr(), false); - // Clear pact handle + // Clear pact handle let _existing_pact_file: Option = pact_default_file_name(&pact_handle); pactffi_free_pact_handle(pact_handle); @@ -1522,7 +1522,7 @@ fn merging_duplicate_message_interaction_without_state_with_pact_containing_two_ expect!(result_1).to(be_equal_to(0)); expect!(result_2).to(be_equal_to(0)); - // Clear pact handle + // Clear pact handle let pact_file: Option = pact_default_file_name(&pact_handle); pactffi_free_pact_handle(pact_handle); @@ -1664,11 +1664,11 @@ fn allow_creation_v4_spec_message() { let body_bytes = request_body_with_matchers.as_bytes(); pactffi_message_with_contents(message_handle.clone(), content_type.as_ptr(), body_bytes.as_ptr(), body_bytes.len()); let _res: *const c_char = pactffi_message_reify(message_handle.clone()); - let result_2 = pactffi_write_message_pact_file(message_pact_handle.clone(), tmp_dir.as_ptr(), false); + let result_2 = pactffi_write_message_pact_file(message_pact_handle.clone(), tmp_dir.as_ptr(), false); expect!(result_1).to(be_equal_to(0)); expect!(result_2).to(be_equal_to(0)); let pact_file: Option = pact_default_file_name(&pact_handle); - // Clear pact handle + // Clear pact handle pactffi_free_pact_handle(pact_handle); // end setup new pact @@ -1910,6 +1910,439 @@ 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::first_object_shape(json!({ "contact": { "email": "fred@example.com" } }), 200)] +#[case::second_object_shape(json!({ "contact": { "phone": "0123456789" } }), 200)] +#[case::array_of_contacts(json!({ "contact": [{ "email": "a@b.c" }, { "email": "x@y.z" }] }), 200)] +#[case::array_item_of_another_shape(json!({ "contact": [{ "email": "a@b.c" }, { "phone": "1" }] }), 500)] +#[case::null_contact(json!({ "contact": null }), 200)] +#[case::bad_email(json!({ "contact": { "email": "not an email" } }), 500)] +#[case::empty_array(json!({ "contact": [] }), 500)] +#[case::string_contact(json!({ "contact": "fred@example.com" }), 500)] +fn or_matchers_with_variants(#[case] actual_body: Value, #[case] expected_status: u16) { + init_crypto(); + + let consumer_name = CString::new("or_variants-consumer").unwrap(); + let provider_name = CString::new("or_variants-provider").unwrap(); + let pact_handle = pactffi_new_pact(consumer_name.as_ptr(), provider_name.as_ptr()); + let description = CString::new("or_variants").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 json = json!({ + "contact": { + "pact:matcher:type": [ + { + "pact:matcher:type": "type", + "value": { + "email": { "pact:matcher:type": "regex", "regex": "^[^@ ]+@[^@ ]+$", "value": "fred@example.com" } + } + }, + { + "pact:matcher:type": "type", + "value": { "phone": { "pact:matcher:type": "regex", "regex": "^\\d+$", "value": "0123456789" } } + }, + { "pact:matcher:type": "type", "min": 1, "value": [{ "email": "fred@example.com" }] }, + { "pact:matcher:type": "null", "value": null } + ], + "pact:matcher:combine": "OR", + "value": { "email": "fred@example.com" } + } + }); + 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:{}/contact", 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::integer_id_and_digits("123", 200)] +#[case::uuid_id_and_unknown("unknown", 200)] +#[case::bad_id("123", 500)] +#[case::bad_phone("call me", 500)] +fn or_matchers_with_variants_for_xml(#[case] actual_body: &str, #[case] expected_status: u16) { + init_crypto(); + + let consumer_name = CString::new("or_variants_xml-consumer").unwrap(); + let provider_name = CString::new("or_variants_xml-provider").unwrap(); + let pact_handle = pactffi_new_pact(consumer_name.as_ptr(), provider_name.as_ptr()); + let description = CString::new("or_variants_xml").unwrap(); + let interaction = pactffi_new_interaction(pact_handle.clone(), description.as_ptr()); + + let content_type = CString::new("application/xml").unwrap(); + let path = CString::new("/contact").unwrap(); + let json = json!({ + "version": "1.0", + "charset": "UTF-8", + "root": { + "name": "contact", + "attributes": { + "id": { + "pact:matcher:type": [ + { "pact:matcher:type": "integer", "value": 1 }, + { "pact:matcher:type": "regex", "regex": "^[a-f0-9-]{36}$", "value": "4a9f6b5e-2a0f-4c8e-9a3d-5c1b8e7f0a12" } + ], + "pact:matcher:combine": "OR", + "value": 1 + } + }, + "children": [ + { + "name": "phone", + "attributes": {}, + "children": [ + { + "matcher": { + "pact:matcher:type": [ + { "pact:matcher:type": "regex", "regex": "^\\d+$", "value": "0123456789" }, + { "pact:matcher:type": "equality", "value": "unknown" } + ], + "pact:matcher:combine": "OR" + }, + "content": "0123456789" + } + ] + } + ] + } + }); + 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:{}/contact", port).as_str()) + .header("Content-Type", "application/xml") + .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 - integer() OR { d: eachLike(string() OR number()) } +#[rstest] +#[case::integer(json!({ "a": 5 }), 200)] +#[case::object_with_strings_and_numbers(json!({ "a": { "d": ["x", 2, "y", 3.5] } }), 200)] +#[case::object_with_one_string(json!({ "a": { "d": ["only"] } }), 200)] +#[case::decimal(json!({ "a": 5.5 }), 500)] +#[case::string(json!({ "a": "5" }), 500)] +#[case::item_that_is_neither(json!({ "a": { "d": ["x", true] } }), 500)] +#[case::empty_list(json!({ "a": { "d": [] } }), 500)] +#[case::list_is_not_an_array(json!({ "a": { "d": "x" } }), 500)] +fn or_matchers_with_nested_matchers_in_an_alternative(#[case] actual_body: Value, #[case] expected_status: u16) { + init_crypto(); + + let consumer_name = CString::new("or_nested-consumer").unwrap(); + let provider_name = CString::new("or_nested-provider").unwrap(); + let pact_handle = pactffi_new_pact(consumer_name.as_ptr(), provider_name.as_ptr()); + let description = CString::new("or_nested").unwrap(); + let interaction = pactffi_new_interaction(pact_handle.clone(), description.as_ptr()); + + let content_type = CString::new("application/json").unwrap(); + let path = CString::new("/nested").unwrap(); + let json = json!({ + "a": { + "pact:matcher:type": [ + { "pact:matcher:type": "integer", "value": 1 }, + { + "pact:matcher:type": "type", + "value": { + "d": { + "pact:matcher:type": "type", + "min": 1, + "value": [ + { + "pact:matcher:type": [ + { "pact:matcher:type": "type", "value": "x" }, + { "pact:matcher:type": "number", "value": 1 } + ], + "pact:matcher:combine": "OR", + "value": "x" + } + ] + } + } + } + ], + "pact:matcher:combine": "OR", + "value": 1 + } + }); + 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:{}/nested", 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_with_variants_for_query_parameters(#[case] status: &str, #[case] expected_status: u16) { + init_crypto(); + + let consumer_name = CString::new("or_variants_query-consumer").unwrap(); + let provider_name = CString::new("or_variants_query-provider").unwrap(); + let pact_handle = pactffi_new_pact(consumer_name.as_ptr(), provider_name.as_ptr()); + let description = CString::new("or_variants_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+$", "value": "100" }, + { "pact:matcher:type": "equality", "value": "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_with_variants_are_written_to_the_pact_file(#[case] spec: PactSpecification) { + let consumer_name = CString::new(format!("or_variants_file-{:?}-consumer", spec)).unwrap(); + let provider_name = CString::new("or_variants_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_variants_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", "value": { "email": "fred@example.com" } }, + { "pact:matcher:type": "null", "value": 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 and no variants, 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", + "variant": { + "value": { "email": "fred@example.com" }, + "rules": { "$": { "combine": "AND", "matchers": [{ "match": "type" }] } } + } + }, + { + "match": "null", + "variant": { + "value": null, + "rules": { "$": { "combine": "AND", "matchers": [{ "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..45afdc678 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, RuleList, RuleLogic}; use pact_models::path_exp::DocPath; #[cfg(feature = "datetime")] use pact_models::time_utils::validate_datetime; use tracing::debug; @@ -409,6 +409,21 @@ pub fn compare_json( context: &(dyn MatchingContext + Send + Sync) ) -> Result<(), Vec> { debug!("compare: Comparing path {}", path); + if context.matcher_is_defined(path) { + let rule_list = context.select_best_matcher(path); + if rule_list.rule_logic == RuleLogic::Or && !rule_list.cascaded && + rule_list.rules.iter().any(|rule| matches!(rule, MatchingRule::Variant(..))) { + return compare_json_with_variants(path, expected, actual, &rule_list, context); + } + } + + 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 +449,64 @@ pub fn compare_json( } } +/// Compares the actual value against each alternative of a rule list combined with OR, where some +/// of the alternatives are variants with their own example value and matching rules. Matches if +/// any of the alternatives match. +fn compare_json_with_variants( + path: &DocPath, + expected: &Value, + actual: &Value, + rule_list: &RuleList, + context: &(dyn MatchingContext + Send + Sync) +) -> Result<(), Vec> { + debug!("compare_json_with_variants: Comparing path {} against {} alternatives", path, rule_list.rules.len()); + let mut mismatches = vec![]; + for rule in &rule_list.rules { + let result = match rule { + MatchingRule::Variant(_, variant) => { + let variant_context = context.clone_with(&variant.rules); + compare_json(&DocPath::root(), &variant.value, actual, variant_context.as_ref()) + .map_err(|mismatches| mismatches.into_iter() + .map(|mismatch| CommonMismatch { + path: rebase_path(&mismatch.path, path), + .. mismatch + }) + .collect()) + } + _ => { + // Apply just this rule to the expected value at this path. The OR list is removed, so it + // can't be selected again for this path + let mut matchers = context.matchers().clone(); + matchers.rules.retain(|_, rules| rules != rule_list); + matchers.rules.insert(path.clone(), RuleList::new(rule.clone())); + let rule_context = context.clone_with(&matchers); + compare_json(path, expected, actual, rule_context.as_ref()) + } + }; + match result { + Ok(()) => { + debug!("compare_json_with_variants: Alternative {} matched at path {}", rule.name(), path); + return Ok(()); + } + Err(errors) => mismatches.extend(errors) + } + } + Err(mismatches) +} + +/// Rebases a path relative to a variant example (starting with `$`) onto the path of the variant +fn rebase_path(variant_path: &str, path: &DocPath) -> String { + match variant_path.strip_prefix('$') { + Some(rest) => format!("{}{}", path, rest), + None => variant_path.to_string() + } +} + +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 +531,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 +1575,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 +1653,334 @@ 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()); + } + + fn variant(rule: MatchingRule, value: Value, rules: &[(&'static str, MatchingRule)]) -> MatchingRule { + let mut category = MatchingRuleCategory::empty("body"); + for (path, rule) in rules { + category.add_rule(DocPath::new_unwrap(path), rule.clone(), RuleLogic::And); + } + MatchingRule::Variant(Box::new(rule), Box::new(pact_models::matchingrules::MatchingRuleVariant { + value, + rules: category + })) + } + + fn variant_rules() -> MatchingRuleCategory { + or_matching_rules("$.a", &[ + // An object with an integer id + variant(MatchingRule::Type, json!({"id": 1}), &[ + ("$", MatchingRule::Type), ("$.id", MatchingRule::Integer) + ]), + // A different object, with a name matching a regex + variant(MatchingRule::Type, json!({"name": "Fred"}), &[ + ("$", MatchingRule::Type), ("$.name", MatchingRule::Regex("^[A-Z][a-z]+$".to_string())) + ]), + // An array of strings with at least one item + variant(MatchingRule::MinType(1), json!(["x"]), &[("$", MatchingRule::MinType(1))]), + // A string of digits + variant(MatchingRule::Regex("^\\d+$".to_string()), json!("100"), &[ + ("$", MatchingRule::Regex("^\\d+$".to_string())) + ]), + // Or null + variant(MatchingRule::Null, Value::Null, &[("$", MatchingRule::Null)]) + ]) + } + + // Issue #249 + #[rstest] + // actual_json, is_ok + #[case::first_object_shape( json!({"a": {"id": 100}}), true)] + #[case::second_object_shape( json!({"a": {"name": "Mary"}}), true)] + #[case::second_object_shape_bad_child( json!({"a": {"name": "mary"}}), false)] + #[case::first_object_shape_bad_child( json!({"a": {"id": "x"}}), false)] + #[case::array_of_strings( json!({"a": ["y", "z"]}), true)] + #[case::array_of_numbers( json!({"a": [1, 2]}), false)] + #[case::empty_array( json!({"a": []}), false)] + #[case::string_of_digits( json!({"a": "12345"}), true)] + #[case::other_string( json!({"a": "abc"}), false)] + #[case::null_value( json!({"a": null}), true)] + #[case::boolean( json!({"a": true}), false)] + fn compare_json_with_or_matcher_variants(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"a": {"id": 1}}); + let matchingrules = variant_rules(); + 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 + #[test] + fn compare_json_with_or_matcher_variants_reports_mismatches_at_the_full_path() { + let expected_json = json!({"a": {"id": 1}}); + let matchingrules = or_matching_rules("$.a", &[ + variant(MatchingRule::Type, json!({"id": 1}), &[ + ("$", MatchingRule::Type), ("$.id", MatchingRule::Integer) + ]), + variant(MatchingRule::Null, Value::Null, &[("$", MatchingRule::Null)]) + ]); + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &matchingrules, &hashmap!{}); + let result = compare_json(&DocPath::root(), &expected_json, &json!({"a": {"id": "x"}}), &context); + let paths = result.unwrap_err().iter().map(|mismatch| mismatch.path.clone()).collect::>(); + expect!(paths).to(be_equal_to(vec!["$.a.id".to_string(), "$.a".to_string()])); + } + + // Issue #249 + #[rstest] + #[case::object_item( json!({"items": [{"id": 1}, null, {"name": "Mary"}]}), true)] + #[case::bad_item( json!({"items": [{"id": 1}, "x"]}), false)] + fn compare_json_with_or_matcher_variants_for_array_items(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"items": [{"id": 1}]}); + let mut matchingrules = or_matching_rules("$.items[*]", &[ + variant(MatchingRule::Type, json!({"id": 1}), &[("$", MatchingRule::Type)]), + variant(MatchingRule::Type, json!({"name": "Fred"}), &[("$", MatchingRule::Type)]), + variant(MatchingRule::Null, Value::Null, &[("$", MatchingRule::Null)]) + ]); + matchingrules.add_rule(DocPath::new_unwrap("$.items"), MatchingRule::MinType(1), RuleLogic::And); + 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] + #[case::strings_and_arrays( json!({"items": ["Mary", [2, 3]]}), true)] + #[case::object_item( json!({"items": ["Mary", {"b": 1}]}), false)] + fn compare_json_with_or_matcher_mixing_variants_and_plain_rules_for_array_items(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"items": ["Fred"]}); + let mut matchingrules = or_matching_rules("$.items[*]", &[ + MatchingRule::Type, + variant(MatchingRule::Type, json!([1]), &[("$", MatchingRule::Type)]) + ]); + matchingrules.add_rule(DocPath::new_unwrap("$.items"), MatchingRule::MinType(1), RuleLogic::And); + 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 + #[test] + fn compare_json_with_or_matcher_mixing_variants_and_plain_rules() { + let expected_json = json!({"a": "Fred"}); + let matchingrules = or_matching_rules("$.a", &[ + MatchingRule::Type, + variant(MatchingRule::Type, json!([1]), &[("$", MatchingRule::Type)]) + ]); + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &matchingrules, &hashmap!{}); + expect!(compare_json(&DocPath::root(), &expected_json, &json!({"a": "Mary"}), &context)).to(be_ok()); + expect!(compare_json(&DocPath::root(), &expected_json, &json!({"a": [2, 3]}), &context)).to(be_ok()); + expect!(compare_json(&DocPath::root(), &expected_json, &json!({"a": {"b": 1}}), &context)).to(be_err()); + } + + // Issue #249 + #[rstest] + #[case::digits_with_a_one( json!({"a": "100"}), true)] + #[case::digits_without_one( json!({"a": "200"}), false)] + #[case::nested_boolean( json!({"a": false}), true)] + #[case::nested_integer( json!({"a": 7}), true)] + #[case::nested_decimal( json!({"a": 7.5}), false)] + fn compare_json_with_combined_matchers_as_or_alternatives(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"a": "100"}); + // (regex AND include) OR (boolean OR integer) + let mut and_rules = MatchingRuleCategory::empty("body"); + and_rules.add_rule(DocPath::root(), MatchingRule::Regex("^\\d+$".to_string()), RuleLogic::And); + and_rules.add_rule(DocPath::root(), MatchingRule::Include("1".to_string()), RuleLogic::And); + let and_variant = MatchingRule::Variant(Box::new(MatchingRule::Regex("^\\d+$".to_string())), + Box::new(pact_models::matchingrules::MatchingRuleVariant { value: json!("100"), rules: and_rules })); + let mut or_rules = MatchingRuleCategory::empty("body"); + or_rules.add_rule(DocPath::root(), variant(MatchingRule::Boolean, json!(true), &[("$", MatchingRule::Boolean)]), RuleLogic::Or); + or_rules.add_rule(DocPath::root(), variant(MatchingRule::Integer, json!(1), &[("$", MatchingRule::Integer)]), RuleLogic::Or); + let or_variant = MatchingRule::Variant(Box::new(MatchingRule::Boolean), + Box::new(pact_models::matchingrules::MatchingRuleVariant { value: json!(true), rules: or_rules })); + + let matchingrules = or_matching_rules("$.a", &[and_variant, or_variant]); + 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] + #[case::exact_keys( json!({"a": {"id": 1}}), true)] + #[case::unexpected_key( json!({"a": {"id": 1, "x": 2}}), false)] + #[case::other_variant( json!({"a": {"name": "Mary"}}), true)] + fn compare_json_with_or_matcher_variants_and_no_unexpected_keys(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"a": {"id": 1}}); + let matchingrules = or_matching_rules("$.a", &[ + variant(MatchingRule::Type, json!({"id": 1}), &[("$", MatchingRule::Type)]), + variant(MatchingRule::Type, json!({"name": "Fred"}), &[("$", MatchingRule::Type)]) + ]); + let context = CoreMatchingContext::new(DiffConfig::NoUnexpectedKeys, &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] + #[case::object( json!({"id": 100}), true)] + #[case::array( json!([{"id": 1}]), true)] + #[case::string( json!("abc"), false)] + fn compare_json_with_or_matcher_variants_at_the_root(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"id": 1}); + let matchingrules = or_matching_rules("$", &[ + variant(MatchingRule::Type, json!({"id": 1}), &[("$", MatchingRule::Type), ("$.id", MatchingRule::Integer)]), + variant(MatchingRule::MinType(1), json!([{"id": 1}]), &[("$", MatchingRule::MinType(1))]) + ]); + 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] + #[case::integer_id( json!({"a": {"id": 1}}), true)] + #[case::null_id( json!({"a": {"id": null}}), true)] + #[case::string_id( json!({"a": {"id": "x"}}), false)] + fn compare_json_with_an_or_matcher_inside_a_variant(#[case] actual_json: Value, #[case] is_ok: bool) { + let expected_json = json!({"a": {"id": 1}}); + let mut variant_rules = MatchingRuleCategory::empty("body"); + variant_rules.add_rule(DocPath::root(), MatchingRule::Type, RuleLogic::And); + variant_rules.add_rule(DocPath::new_unwrap("$.id"), MatchingRule::Integer, RuleLogic::Or); + variant_rules.add_rule(DocPath::new_unwrap("$.id"), MatchingRule::Null, RuleLogic::Or); + let object_variant = MatchingRule::Variant(Box::new(MatchingRule::Type), + Box::new(pact_models::matchingrules::MatchingRuleVariant { value: json!({"id": 1}), rules: variant_rules })); + let matchingrules = or_matching_rules("$.a", &[ + object_variant, + variant(MatchingRule::Null, Value::Null, &[("$", 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] + #[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/matchingrules.rs b/rust/pact_matching/src/matchingrules.rs index 62c429034..a7e75e67c 100644 --- a/rust/pact_matching/src/matchingrules.rs +++ b/rust/pact_matching/src/matchingrules.rs @@ -224,6 +224,44 @@ pub trait Matches { /// If the actual value matches self given the matching rule fn matches_with(&self, actual: A, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()>; + + /// If the actual value matches the example value of a variant (one alternative of a rule list + /// combined with OR) given the matching rule. The default implementation uses self as the + /// example, for values that can not be created from the JSON form of the example. + fn matches_variant_with( + &self, + _example: &Value, + actual: A, + matcher: &MatchingRule, + cascaded: bool + ) -> anyhow::Result<()> { + self.matches_with(actual, matcher, cascaded) + } +} + +/// Returns the example of a variant as a string, if it is a JSON string or number +fn variant_example_as_string(example: &Value) -> Option { + match example { + Value::String(s) => Some(s.clone()), + Value::Number(n) => Some(n.to_string()), + Value::Bool(b) => Some(b.to_string()), + _ => None + } +} + +/// Matches the actual string against the example of a variant, falling back to the expected value +/// if the example is not a scalar value +fn match_string_variant( + expected: &str, + example: &Value, + actual: &str, + matcher: &MatchingRule, + cascaded: bool +) -> anyhow::Result<()> { + match variant_example_as_string(example) { + Some(example) => matcher.match_value(example.as_str(), actual, cascaded, false), + None => matcher.match_value(expected, actual, cascaded, false) + } } #[allow(deprecated)] @@ -232,6 +270,10 @@ impl Matches for String { fn matches_with(&self, actual: String, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { self.as_str().matches_with(actual.as_str(), matcher, cascaded) } + + fn matches_variant_with(&self, example: &Value, actual: String, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { + match_string_variant(self.as_str(), example, actual.as_str(), matcher, cascaded) + } } #[allow(deprecated)] @@ -240,6 +282,10 @@ impl Matches<&String> for String { fn matches_with(&self, actual: &String, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { self.as_str().matches_with(actual.as_str(), matcher, cascaded) } + + fn matches_variant_with(&self, example: &Value, actual: &String, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { + match_string_variant(self.as_str(), example, actual.as_str(), matcher, cascaded) + } } #[allow(deprecated)] @@ -248,6 +294,10 @@ impl Matches<&String> for &String { fn matches_with(&self, actual: &String, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { self.as_str().matches_with(actual.as_str(), matcher, cascaded) } + + fn matches_variant_with(&self, example: &Value, actual: &String, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { + match_string_variant(self.as_str(), example, actual.as_str(), matcher, cascaded) + } } #[allow(deprecated)] @@ -256,6 +306,10 @@ impl Matches<&str> for String { fn matches_with(&self, actual: &str, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { matcher.match_value(self.as_str(), actual, cascaded, false) } + + fn matches_variant_with(&self, example: &Value, actual: &str, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { + match_string_variant(self.as_str(), example, actual, matcher, cascaded) + } } #[allow(deprecated)] @@ -264,6 +318,10 @@ impl Matches<&str> for &str { fn matches_with(&self, actual: &str, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { matcher.match_value(*self, actual, cascaded, false) } + + fn matches_variant_with(&self, example: &Value, actual: &str, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { + match_string_variant(*self, example, actual, matcher, cascaded) + } } #[allow(deprecated)] @@ -323,6 +381,13 @@ impl Matches for u64 { fn matches_with(&self, actual: u64, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { matcher.match_value(*self, actual, cascaded, false) } + + fn matches_variant_with(&self, example: &Value, actual: u64, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { + match example.as_u64() { + Some(example) => example.matches_with(actual, matcher, cascaded), + None => self.matches_with(actual, matcher, cascaded) + } + } } #[allow(deprecated)] @@ -483,6 +548,13 @@ impl Matches for u16 { debug!("u16 -> u16: comparing {} to {} using {:?}", self, actual, matcher); (*self as u64).matches_with(actual as u64, matcher, cascaded) } + + fn matches_variant_with(&self, example: &Value, actual: u16, matcher: &MatchingRule, cascaded: bool) -> anyhow::Result<()> { + match example.as_u64().and_then(|example| u16::try_from(example).ok()) { + Some(example) => example.matches_with(actual, matcher, cascaded), + None => self.matches_with(actual, matcher, cascaded) + } + } } #[allow(deprecated)] @@ -751,6 +823,12 @@ impl Matches<&BTreeMap> for MatchingRule::EachKey(_) => Ok(()), MatchingRule::EachValue(_) => Ok(()), MatchingRule::Values => Ok(()), + // A variant applies to each item, so only its length restrictions apply to the collection + MatchingRule::Variant(rule, _) => if rule.is_length_type_matcher() { + self.matches_with(actual, rule, cascaded) + } else { + Ok(()) + }, _ => Err(anyhow!("Unable to match {} using {:?}", self.for_mismatch(), matcher)) }; debug!("Comparing '{:?}' to '{:?}' using {:?} -> {:?}", self, actual, matcher, result); @@ -1049,6 +1127,12 @@ impl DoMatch<&[T]> for MatchingRule { MatchingRule::ContentType(_) => Ok(()), MatchingRule::Boolean => Ok(()), MatchingRule::Semver => Ok(()), + // A variant applies to each item, so only its length restrictions apply to the collection + MatchingRule::Variant(rule, _) => if rule.is_length_type_matcher() { + rule.match_value(expected_value, actual_value, cascaded, show_types) + } else { + Ok(()) + }, _ => Err(anyhow!("Unable to match {} using {:?}", actual_value.for_mismatch(), self)) }; debug!("Comparing '{:?}' to '{:?}' using {:?} -> {:?}", self, actual_value, self, result); @@ -1212,6 +1296,12 @@ impl DoMatch<&BTreeMap> for MatchingRule { MatchingRule::EachKey(_) => Ok(()), MatchingRule::EachValue(_) => Ok(()), MatchingRule::Values => Ok(()), + // A variant applies to each item, so only its length restrictions apply to the collection + MatchingRule::Variant(rule, _) => if rule.is_length_type_matcher() { + rule.match_value(expected_value, actual_value, cascaded, _show_types) + } else { + Ok(()) + }, _ => Err(anyhow!("Unable to match {:?} using {:?}", actual_value, self)) }; debug!("Comparing '{:?}' to '{:?}' using {:?} -> {:?}", expected_value, actual_value, self, result); @@ -1277,6 +1367,12 @@ impl DoMatch<&HashMap> for MatchingRule { MatchingRule::EachKey(_) => Ok(()), MatchingRule::EachValue(_) => Ok(()), MatchingRule::Values => Ok(()), + // A variant applies to each item, so only its length restrictions apply to the collection + MatchingRule::Variant(rule, _) => if rule.is_length_type_matcher() { + rule.match_value(expected_value, actual_value, cascaded, _show_types) + } else { + Ok(()) + }, _ => Err(anyhow!("Unable to match {:?} using {:?}", actual_value, self)) }; debug!("Comparing '{:?}' to '{:?}' using {:?} -> {:?}", expected_value, actual_value, self, result); @@ -1331,6 +1427,35 @@ impl DisplayForMismatch for BTreeSet { } +/// Matches a value against a variant (one alternative of a rule list combined with OR). Only the +/// rules for the variant value itself apply, as the actual value is not JSON. +#[allow(deprecated)] +fn match_variant(expected: &E, actual: A, rule: &MatchingRule, cascaded: bool) -> anyhow::Result<()> + where E: Matches, A: Clone { + let MatchingRule::Variant(inner, variant) = rule else { + return expected.matches_with(actual, rule, cascaded); + }; + let rule_list = variant.rules.rules.get(&DocPath::root()) + .filter(|rules| !rules.is_empty()) + .cloned() + .unwrap_or_else(|| RuleList::new(inner.as_ref().clone())); + let mut results = rule_list.rules.iter().map(|rule| match rule { + MatchingRule::Variant(..) => match_variant(expected, actual.clone(), rule, cascaded), + _ => expected.matches_variant_with(&variant.value, actual.clone(), rule, cascaded) + }); + match rule_list.rule_logic { + RuleLogic::And => results.find(|result| result.is_err()).unwrap_or(Ok(())), + RuleLogic::Or => { + let results = results.collect::>(); + if results.iter().any(|result| result.is_ok()) { + Ok(()) + } else { + results.into_iter().next().unwrap_or(Ok(())) + } + } + } +} + /// Match the provided values using the path and matching rules #[allow(deprecated)] pub fn match_values(path: &DocPath, matching_rules: &RuleList, expected: E, actual: A) -> Result<(), Vec> @@ -1342,7 +1467,10 @@ where E: Matches, A: Clone { // So that a plugin-provided rule knows where the value it is being applied to lives let _scope = FieldMatchScope::path(path); let results = matching_rules.rules.iter().map(|rule| { - expected.matches_with(actual.clone(), rule, matching_rules.cascaded) + match rule { + MatchingRule::Variant(..) => match_variant(&expected, actual.clone(), rule, matching_rules.cascaded), + _ => expected.matches_with(actual.clone(), rule, matching_rules.cascaded) + } }).collect::>>(); let result = match matching_rules.rule_logic { RuleLogic::And => { @@ -2572,7 +2700,8 @@ mod tests { MatchingRule::ArrayContains(_) | MatchingRule::Values | MatchingRule::Boolean | MatchingRule::StatusCode(_) | MatchingRule::NotEmpty | MatchingRule::Semver | MatchingRule::EachKey(_) | MatchingRule::EachValue(_) => {}, - MatchingRule::Plugin { .. } => panic!("a plugin rule is not a core catalogue entry") + MatchingRule::Plugin { .. } => panic!("a plugin rule is not a core catalogue entry"), + MatchingRule::Variant(..) => panic!("a variant wraps a core rule, it is not a catalogue entry") } } @@ -2670,4 +2799,89 @@ mod tests { .to(be_true()); } } + + fn status_variant(example: Value) -> RuleList { + let mut rules = MatchingRuleCategory::empty("status"); + rules.add_rule(DocPath::root(), MatchingRule::Equality, RuleLogic::And); + RuleList { + rules: vec![ + MatchingRule::Variant(Box::new(MatchingRule::Equality), + Box::new(pact_models::matchingrules::MatchingRuleVariant { value: example, rules })) + ], + rule_logic: RuleLogic::Or, + cascaded: false + } + } + + // Issue #249 + #[test] + fn match_values_with_a_variant_uses_its_example_for_status_codes() { + let path = DocPath::root(); + expect!(match_values(&path, &status_variant(json!(404)), 200_u16, 404_u16)).to(be_ok()); + expect!(match_values(&path, &status_variant(json!(404)), 200_u16, 200_u16)).to(be_err()); + } + + // Issue #249 + #[test] + fn match_values_with_a_variant_ignores_an_example_that_is_not_a_status_code() { + // 70000 is not a valid u16, so the expected value is used instead of a truncated example + let path = DocPath::root(); + expect!(match_values(&path, &status_variant(json!(70000)), 200_u16, 200_u16)).to(be_ok()); + expect!(match_values(&path, &status_variant(json!(70000)), 200_u16, 4464_u16)).to(be_err()); + } + + fn string_variant(rule: MatchingRule, example: Value) -> MatchingRule { + let mut rules = MatchingRuleCategory::empty("header"); + rules.add_rule(DocPath::root(), rule.clone(), RuleLogic::And); + MatchingRule::Variant(Box::new(rule), + Box::new(pact_models::matchingrules::MatchingRuleVariant { value: example, rules })) + } + + fn or_list(rules: Vec) -> RuleList { + RuleList { rules, rule_logic: RuleLogic::Or, cascaded: false } + } + + // Issue #249 + #[rstest::rstest] + #[case::true_value("true", true)] + #[case::number_value("10", true)] + #[case::other_value("yes", false)] + fn match_values_with_variants_converts_scalar_examples_to_strings(#[case] actual: &str, #[case] is_ok: bool) { + let rule_list = or_list(vec![ + string_variant(MatchingRule::Equality, json!(true)), + string_variant(MatchingRule::Equality, json!(10)) + ]); + let result = match_values(&DocPath::root(), &rule_list, "expected", actual); + expect!(result.is_ok()).to(be_equal_to(is_ok)); + } + + // Issue #249 + #[rstest::rstest] + #[case::first_nested_alternative("abc", true)] + #[case::second_nested_alternative("123", true)] + #[case::outer_alternative("none", true)] + #[case::no_alternative("ABC", false)] + fn match_values_with_nested_variants(#[case] actual: &str, #[case] is_ok: bool) { + let mut nested_rules = MatchingRuleCategory::empty("header"); + nested_rules.add_rule(DocPath::root(), string_variant(MatchingRule::Regex("^[a-z]+$".to_string()), json!("abc")), RuleLogic::Or); + nested_rules.add_rule(DocPath::root(), string_variant(MatchingRule::Regex("^\\d+$".to_string()), json!("1")), RuleLogic::Or); + let nested = MatchingRule::Variant(Box::new(MatchingRule::Regex("^[a-z]+$".to_string())), + Box::new(pact_models::matchingrules::MatchingRuleVariant { value: json!("abc"), rules: nested_rules })); + let rule_list = or_list(vec![nested, string_variant(MatchingRule::Equality, json!("none"))]); + let result = match_values(&DocPath::root(), &rule_list, "abc", actual); + expect!(result.is_ok()).to(be_equal_to(is_ok)); + } + + // Issue #249 + #[test] + fn match_values_with_a_variant_without_root_rules_uses_the_inner_rule() { + let variant = MatchingRule::Variant(Box::new(MatchingRule::Equality), + Box::new(pact_models::matchingrules::MatchingRuleVariant { + value: json!("none"), + rules: MatchingRuleCategory::empty("header") + })); + let rule_list = or_list(vec![variant]); + expect!(match_values(&DocPath::root(), &rule_list, "abc", "none")).to(be_ok()); + expect!(match_values(&DocPath::root(), &rule_list, "abc", "abc")).to(be_err()); + } } diff --git a/rust/pact_matching/src/tests.rs b/rust/pact_matching/src/tests.rs index 967083bd8..c934fc225 100644 --- a/rust/pact_matching/src/tests.rs +++ b/rust/pact_matching/src/tests.rs @@ -3,12 +3,12 @@ use std::collections::HashMap; use expectest::prelude::*; use pretty_assertions::{assert_eq, assert_ne}; -use pact_models::{matchingrules, matchingrules_list}; -use pact_models::matchingrules::expressions::{MatchingRuleDefinition, ValueType}; +use pact_models::HttpStatus; use pact_models::bodies::OptionalBody; use pact_models::content_types::{JSON, TEXT}; -use pact_models::HttpStatus; +use pact_models::matchingrules::expressions::{MatchingRuleDefinition, ValueType}; use pact_models::request::Request; +use pact_models::{matchingrules, matchingrules_list}; use super::*; @@ -1032,3 +1032,69 @@ fn match_metadata_value_with_content_type_test() { let result = match_metadata_value("key", &expected, &actual, &context); expect!(result).to(be_err()); } + +fn or_variant(rule: MatchingRule, value: serde_json::Value) -> MatchingRule { + let mut rules = MatchingRuleCategory::empty("body"); + rules.add_rule(DocPath::root(), rule.clone(), pact_models::matchingrules::RuleLogic::And); + MatchingRule::Variant(Box::new(rule), + Box::new(pact_models::matchingrules::MatchingRuleVariant { value, rules })) +} + +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::equal_to_all("all", true)] +#[case::neither( "some", false)] +fn match_query_with_or_matcher_variants(#[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", &[ + or_variant(MatchingRule::Regex("^\\d+$".to_string()), serde_json::json!("100")), + or_variant(MatchingRule::Equality, serde_json::json!("all")) + ]); + 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 +#[test] +fn match_query_with_or_matcher_variants_applies_to_every_value() { + let expected = hashmap! { "id".to_string() => vec![Some("100".to_string())] }; + let rules = or_rules("query", "id", &[ + or_variant(MatchingRule::Regex("^\\d+$".to_string()), serde_json::json!("100")), + or_variant(MatchingRule::Equality, serde_json::json!("all")) + ]); + let context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys, &rules, &hashmap!{}); + + let actual = hashmap! { "id".to_string() => vec![Some("1".to_string()), Some("all".to_string())] }; + expect!(match_query(Some(expected.clone()), Some(actual), &context).values().flatten().count()).to(be_equal_to(0)); + let actual = hashmap! { "id".to_string() => vec![Some("1".to_string()), Some("some".to_string())] }; + expect!(match_query(Some(expected), Some(actual), &context).values().flatten().count()).to(be_greater_than(0)); +} + +// 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_matcher_variants(#[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", &[ + or_variant(MatchingRule::Regex("^Bearer \\S+$".to_string()), serde_json::json!("Bearer token")), + or_variant(MatchingRule::Regex("^ApiKey \\d+$".to_string()), serde_json::json!("ApiKey 1")) + ]); + 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)); +} diff --git a/rust/pact_models/src/matchingrules/mod.rs b/rust/pact_models/src/matchingrules/mod.rs index 2c7b7b68d..0a0dbdcf8 100644 --- a/rust/pact_models/src/matchingrules/mod.rs +++ b/rust/pact_models/src/matchingrules/mod.rs @@ -70,6 +70,53 @@ fn plugin_rule_values(attributes: &Map, strip_example: bool) -> V .collect()) } +/// Example value and matching rules for one alternative of a rule list combined with OR. This +/// allows an alternative to be a completely different shape to the example value, like an array +/// instead of an object. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MatchingRuleVariant { + /// Example value for this alternative + pub value: Value, + /// Matching rules for this alternative. The paths are relative to the example value, so `$` is + /// the value itself. + pub rules: MatchingRuleCategory +} + +impl MatchingRuleVariant { + /// Builds the variant from its JSON form, i.e. `{ "value": ..., "rules": { ... } }` + pub fn from_json(json: &Value) -> anyhow::Result { + match json { + Value::Object(map) => { + let mut rules = MatchingRuleCategory::empty("body"); + if let Some(rules_json) = map.get("rules") { + rules.add_rules_from_json(rules_json) + .with_context(|| format!("Unable to parse the variant matching rules: {:?}", rules_json))?; + } + Ok(MatchingRuleVariant { + value: map.get("value").cloned().unwrap_or_default(), + rules + }) + } + _ => Err(anyhow!("Matching rule 'variant' attribute is not an Object")) + } + } + + /// Converts this variant to its JSON form + pub fn to_json(&self) -> Value { + json!({ + "value": self.value, + "rules": self.rules.to_v3_json() + }) + } +} + +impl Hash for MatchingRuleVariant { + fn hash(&self, state: &mut H) { + self.value.to_string().hash(state); + self.rules.hash(state); + } +} + /// Set of all matching rules #[derive(Debug, Clone, Eq)] pub enum MatchingRule { @@ -127,13 +174,25 @@ pub enum MatchingRule { name: String, /// Configuration values for the rule, stored alongside the name in the Pact file values: Value - } + }, + /// One alternative of a rule list combined with OR, which has its own example value and matching + /// rules. It is stored in the Pact file as the inner rule with an additional `variant` attribute, + /// so readers that don't support variants can still use the inner rule. + Variant(Box, Box) } impl MatchingRule { /// Builds a `MatchingRule` from a `Value` struct pub fn from_json(value: &Value) -> anyhow::Result { + if let Value::Object(m) = value && let Some(variant) = m.get("variant") { + let variant = MatchingRuleVariant::from_json(variant)?; + let mut inner = m.clone(); + inner.remove("variant"); + let rule = MatchingRule::from_json(&Value::Object(inner))?; + return Ok(MatchingRule::Variant(Box::new(rule), Box::new(variant))); + } + match value { Value::Object(m) => match m.get("match").or_else(|| m.get("pact:matcher:type")) { Some(match_val) => { @@ -266,6 +325,13 @@ impl MatchingRule { } map } + MatchingRule::Variant(rule, variant) => { + let mut json = rule.to_json(); + if let Some(map) = json.as_object_mut() { + map.insert("variant".to_string(), variant.to_json()); + } + json + } } } @@ -274,6 +340,7 @@ impl MatchingRule { match self { MatchingRule::ArrayContains(variants) => variants.iter() .any(|(_, _, generators)| !generators.is_empty()), + MatchingRule::Variant(rule, _) => rule.has_generators(), _ => false } } @@ -282,14 +349,17 @@ impl MatchingRule { pub fn generators(&self) -> Vec { match self { MatchingRule::ArrayContains(variants) => vec![Generator::ArrayContains(variants.clone())], + MatchingRule::Variant(rule, _) => rule.generators(), _ => vec![] } } /// Returns the type name of this matching rule pub fn name(&self) -> String { - if let MatchingRule::Plugin { name, .. } = self { - return name.clone(); + match self { + MatchingRule::Plugin { name, .. } => return name.clone(), + MatchingRule::Variant(rule, _) => return rule.name(), + _ => () } match self { MatchingRule::Equality => "equality", @@ -315,7 +385,7 @@ impl MatchingRule { MatchingRule::Semver => "semver", MatchingRule::EachKey(_) => "each-key", MatchingRule::EachValue(_) => "each-value", - MatchingRule::Plugin { .. } => unreachable!("handled above") + MatchingRule::Plugin { .. } | MatchingRule::Variant(..) => unreachable!("handled above") }.to_string() } @@ -331,6 +401,11 @@ impl MatchingRule { .collect(), _ => HashMap::default() } + MatchingRule::Variant(rule, variant) => { + let mut map = rule.value_map(); + map.insert("variant".to_string(), variant.to_json()); + map + } #[allow(deprecated)] _ => self.values().iter() .map(|(k, v)| (k.to_string(), v.clone())) @@ -394,7 +469,12 @@ impl MatchingRule { map } - MatchingRule::Plugin { .. } => empty + MatchingRule::Plugin { .. } => empty, + MatchingRule::Variant(rule, variant) => { + let mut map = rule.values(); + map.insert("variant", variant.to_json()); + map + } } } @@ -570,6 +650,7 @@ impl MatchingRule { /// collection as a whole rather than to individual elements. pub fn is_values_matcher(&self) -> bool { match self { + MatchingRule::Variant(rule, _) => rule.is_values_matcher(), MatchingRule::Values => true, MatchingRule::EachValue(_) => true, MatchingRule::ArrayContains(_) => true, @@ -580,6 +661,7 @@ impl MatchingRule { /// If this matching rule is a type matcher pub fn is_type_matcher(&self) -> bool { match self { + MatchingRule::Variant(rule, _) => rule.is_type_matcher(), MatchingRule::Type => true, MatchingRule::MinType(_) => true, MatchingRule::MaxType(_) => true, @@ -591,6 +673,7 @@ impl MatchingRule { /// If this matching rule is a type matcher that includes a length restriction pub fn is_length_type_matcher(&self) -> bool { match self { + MatchingRule::Variant(rule, _) => rule.is_length_type_matcher(), MatchingRule::MinType(_) => true, MatchingRule::MaxType(_) => true, MatchingRule::MinMaxType(_, _) => true, @@ -606,6 +689,8 @@ impl MatchingRule { MatchingRule::EachKey(_) => false, // A plugin rule applies to the value at its path, not to that value's children MatchingRule::Plugin { .. } => false, + // A variant has its own rules for the children of its example value + MatchingRule::Variant(..) => false, _ => true } } @@ -659,7 +744,8 @@ impl MatchingRule { MatchingRule::Semver => "must match a semver version".to_string(), MatchingRule::EachKey(m) => format!("each key must match '{}'", m.expression()), MatchingRule::EachValue(m) => format!("each value must match '{}'", m.expression()), - MatchingRule::Plugin { name, .. } => format!("must match the '{}' rule provided by a plugin", name) + MatchingRule::Plugin { name, .. } => format!("must match the '{}' rule provided by a plugin", name), + MatchingRule::Variant(_, variant) => format!("must match the variant {}", variant.value) } } @@ -671,6 +757,8 @@ impl MatchingRule { MatchingRule::MinType(_) => MatchingRule::Type, MatchingRule::MaxType(_) => MatchingRule::Type, MatchingRule::MinMaxType(_, _) => MatchingRule::Type, + MatchingRule::Variant(rule, variant) => + MatchingRule::Variant(Box::new(rule.for_single_item()), variant.clone()), _ => self.clone() } } @@ -684,6 +772,7 @@ impl MatchingRule { MatchingRule::Equality => true, MatchingRule::Include(_) => true, MatchingRule::Regex(_) => content_type.is_text(), + MatchingRule::Variant(rule, _) => rule.can_match(content_type), _ => false } } @@ -719,6 +808,10 @@ impl Hash for MatchingRule { name.hash(state); values.to_string().hash(state); } + MatchingRule::Variant(rule, variant) => { + rule.hash(state); + variant.hash(state); + } _ => () } } @@ -740,6 +833,7 @@ impl PartialEq for MatchingRule { (MatchingRule::EachKey(definition1), MatchingRule::EachKey(definition2)) => definition1 == definition2, (MatchingRule::EachValue(definition1), MatchingRule::EachValue(definition2)) => definition1 == definition2, (MatchingRule::Plugin { name: n1, values: v1 }, MatchingRule::Plugin { name: n2, values: v2 }) => n1 == n2 && v1 == v2, + (MatchingRule::Variant(rule1, variant1), MatchingRule::Variant(rule2, variant2)) => rule1 == rule2 && variant1 == variant2, _ => mem::discriminant(self) == mem::discriminant(other) } } @@ -817,6 +911,8 @@ impl RuleList { fn to_v2_json(&self) -> Value { match self.rules.get(0) { + // V2 Pact files have no variants, so only the inner rule is written + Some(MatchingRule::Variant(rule, _)) => rule.to_json(), Some(rule) => rule.to_json(), None => json!({}) } @@ -3018,4 +3114,161 @@ mod tests { })); expect!(rule.can_cascade()).to(be_false()); } + + fn address_variant() -> MatchingRule { + let mut rules = MatchingRuleCategory::empty("body"); + rules.add_rule(DocPath::root(), MatchingRule::Type, RuleLogic::And); + rules.add_rule(DocPath::new_unwrap("$.street"), MatchingRule::Regex("\\w+".to_string()), RuleLogic::And); + MatchingRule::Variant(Box::new(MatchingRule::Type), Box::new(MatchingRuleVariant { + value: json!({ "street": "Main" }), + rules + })) + } + + // Issue #249 + #[test] + fn variant_matching_rule_to_json() { + expect!(address_variant().to_json()).to(be_equal_to(json!({ + "match": "type", + "variant": { + "value": { "street": "Main" }, + "rules": { + "$": { "combine": "AND", "matchers": [{ "match": "type" }] }, + "$.street": { "combine": "AND", "matchers": [{ "match": "regex", "regex": "\\w+" }] } + } + } + }))); + } + + // Issue #249 + #[test] + fn variant_matching_rule_from_json() { + let rule = MatchingRule::from_json(&address_variant().to_json()).unwrap(); + expect!(&rule).to(be_equal_to(&address_variant())); + expect!(rule.name()).to(be_equal_to("type".to_string())); + expect!(rule.is_type_matcher()).to(be_true()); + expect!(rule.can_cascade()).to(be_false()); + } + + // Issue #249 + #[test] + fn variant_matching_rules_in_a_rule_list_combined_with_or() { + let json = json!({ + "body": { + "$.address": { + "combine": "OR", + "matchers": [ + address_variant().to_json(), + { "match": "null", "variant": { "value": null, "rules": { "$": { "matchers": [{ "match": "null" }] } } } } + ] + } + } + }); + let mut matching_rules = MatchingRules::default(); + matching_rules.load_from_v3_map(json.as_object().unwrap()).unwrap(); + let rule_list = matching_rules.rules_for_category("body").unwrap() + .rules.get(&DocPath::new_unwrap("$.address")).cloned().unwrap(); + + expect!(rule_list.rule_logic).to(be_equal_to(RuleLogic::Or)); + expect!(rule_list.rules.len()).to(be_equal_to(2)); + expect!(&rule_list.rules[0]).to(be_equal_to(&address_variant())); + expect!(matches!(&rule_list.rules[1], MatchingRule::Variant(rule, _) if **rule == MatchingRule::Null)).to(be_true()); + expect!(rule_list.to_v3_json()).to(be_equal_to(json!({ + "combine": "OR", + "matchers": [ + address_variant().to_json(), + { "match": "null", "variant": { "value": null, "rules": { "$": { "combine": "AND", "matchers": [{ "match": "null" }] } } } } + ] + }))); + } + + // Issue #249 + #[test] + fn variant_matching_rules_are_written_without_the_variant_for_v2() { + let mut rules = MatchingRuleCategory::empty("body"); + rules.add_rule(DocPath::new_unwrap("$.address"), address_variant(), RuleLogic::Or); + rules.add_rule(DocPath::new_unwrap("$.address"), MatchingRule::Null, RuleLogic::Or); + let matching_rules = MatchingRules { rules: hashmap!{ Category::BODY => rules } }; + + expect!(matchers_to_json(&matching_rules, &PactSpecification::V2)).to(be_equal_to(json!({ + "$.body.address": { "match": "type" } + }))); + } + + // Issue #249 + #[rstest::rstest] + #[case::v3(PactSpecification::V3)] + #[case::v4(PactSpecification::V4)] + fn variant_matching_rules_round_trip_through_the_pact_file_format(#[case] spec: PactSpecification) { + let mut body = MatchingRuleCategory::empty("body"); + body.add_rule(DocPath::new_unwrap("$.address"), address_variant(), RuleLogic::Or); + body.add_rule(DocPath::new_unwrap("$.address"), MatchingRule::Null, RuleLogic::Or); + let mut header = MatchingRuleCategory::empty("header"); + let mut header_rules = MatchingRuleCategory::empty("body"); + header_rules.add_rule(DocPath::root(), MatchingRule::Equality, RuleLogic::And); + header.add_rule(DocPath::root().join("x-id"), MatchingRule::Variant(Box::new(MatchingRule::Equality), + Box::new(MatchingRuleVariant { value: json!("none"), rules: header_rules })), RuleLogic::Or); + header.add_rule(DocPath::root().join("x-id"), MatchingRule::Integer, RuleLogic::Or); + let matching_rules = MatchingRules { + rules: hashmap!{ Category::BODY => body, Category::HEADER => header } + }; + + let json = json!({ "matchingRules": matchers_to_json(&matching_rules, &spec) }); + let restored = matchers_from_json(&json, &None).unwrap(); + + expect!(restored).to(be_equal_to(matching_rules)); + } + + // Issue #249 + #[test] + fn variant_matching_rule_keeps_the_configuration_of_the_inner_rule() { + let variant = json!({ "value": [1], "rules": { "$": { "matchers": [{ "match": "type", "min": 1 }] } } }); + let rule = MatchingRule::from_json(&json!({ "match": "type", "min": 1, "variant": variant })).unwrap(); + expect!(matches!(&rule, MatchingRule::Variant(inner, _) if **inner == MatchingRule::MinType(1))).to(be_true()); + expect!(rule.is_length_type_matcher()).to(be_true()); + expect!(rule.for_single_item().is_length_type_matcher()).to(be_false()); + } + + // Issue #249 + #[test] + fn variant_attribute_is_not_stored_with_a_plugin_rule() { + let variant = json!({ "value": "x", "rules": {} }); + let rule = MatchingRule::from_json(&json!({ "match": "my-plugin-rule", "size": 3, "variant": variant })).unwrap(); + match rule { + MatchingRule::Variant(inner, _) => { + expect!(*inner).to(be_equal_to(MatchingRule::Plugin { + name: "my-plugin-rule".to_string(), + values: json!({ "size": 3 }) + })); + } + _ => panic!("Expected a variant, got {:?}", rule) + } + } + + // Issue #249 + #[test] + fn variant_matching_rules_hash_and_compare_by_their_example_and_rules() { + let other_value = MatchingRule::Variant(Box::new(MatchingRule::Type), Box::new(MatchingRuleVariant { + value: json!({ "street": "Other" }), + rules: MatchingRuleCategory::empty("body") + })); + let mut hasher1 = DefaultHasher::new(); + address_variant().hash(&mut hasher1); + let mut hasher2 = DefaultHasher::new(); + address_variant().hash(&mut hasher2); + let mut hasher3 = DefaultHasher::new(); + other_value.hash(&mut hasher3); + + expect!(address_variant()).to(be_equal_to(address_variant())); + expect!(address_variant()).to_not(be_equal_to(other_value.clone())); + expect!(address_variant()).to_not(be_equal_to(MatchingRule::Type)); + expect!(hasher1.finish()).to(be_equal_to(hasher2.finish())); + expect!(hasher1.finish()).to_not(be_equal_to(hasher3.finish())); + } + + // Issue #249 + #[test] + fn variant_attribute_must_be_an_object() { + expect!(MatchingRule::from_json(&json!({ "match": "type", "variant": "nope" }))).to(be_err()); + } }