diff --git a/rust/pact_ffi/tests/tests.rs b/rust/pact_ffi/tests/tests.rs index c01bbe9b9..1c54ff263 100644 --- a/rust/pact_ffi/tests/tests.rs +++ b/rust/pact_ffi/tests/tests.rs @@ -2644,3 +2644,43 @@ fn https_mock_server_starts_and_responds_over_tls() { expect!(matched).to(be_true()); expect!(mismatches).to(be_equal_to("[]")); } + +// Each value of a repeated header or query parameter can have its own matcher. These must all +// survive being written to a pact file and read back. +#[test] +fn matchers_for_each_header_and_query_value_survive_writing_the_pact_file() { + let pact_handle = PactHandle::new("IndexedMatchersC", "IndexedMatchersP"); + pactffi_with_specification(pact_handle, PactSpecification::V4); + let description = CString::new("repeated values with matchers").unwrap(); + let i_handle = pactffi_new_interaction(pact_handle, description.as_ptr()); + let method = CString::new("GET").unwrap(); + let path = CString::new("/request").unwrap(); + pactffi_with_request(i_handle, method.as_ptr(), path.as_ptr()); + let name = CString::new("X-Request").unwrap(); + let first = CString::new(r#"{"value":"first-1","pact:matcher:type":"regex","regex":"^first-\\d+$"}"#).unwrap(); + let second = CString::new(r#"{"value":"second-1","pact:matcher:type":"regex","regex":"^second-\\d+$"}"#).unwrap(); + pactffi_with_header_v2(i_handle, InteractionPart::Request, name.as_ptr(), 0, first.as_ptr()); + pactffi_with_header_v2(i_handle, InteractionPart::Request, name.as_ptr(), 1, second.as_ptr()); + pactffi_with_query_parameter_v2(i_handle, name.as_ptr(), 0, first.as_ptr()); + pactffi_with_query_parameter_v2(i_handle, name.as_ptr(), 1, second.as_ptr()); + pactffi_response_status(i_handle, 200); + + let tmp = TempDir::new().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(), true); + let file_name = pact_default_file_name(&pact_handle); + pactffi_free_pact_handle(pact_handle); + expect!(result).to(be_equal_to(0)); + + let pact = pact_models::pact::read_pact(&tmp.path().join(file_name.unwrap())).unwrap(); + let request = pact.interactions()[0].as_request_response().unwrap().request; + for category in ["header", "query"] { + let rules = request.matching_rules.rules_for_category(category).unwrap(); + // Adding a matcher for a later value moves the first value's matcher to index 0 + let base = DocPath::root().join("X-Request"); + expect!(rules.rules.get(&base.join("0")).map(|r| r.rules.clone())) + .to(be_some().value(vec![MatchingRule::Regex("^first-\\d+$".to_string())])); + expect!(rules.rules.get(&base.join("1")).map(|r| r.rules.clone())) + .to(be_some().value(vec![MatchingRule::Regex("^second-\\d+$".to_string())])); + } +} diff --git a/rust/pact_models/src/generators/mod.rs b/rust/pact_models/src/generators/mod.rs index c7df37ed8..0b29797da 100644 --- a/rust/pact_models/src/generators/mod.rs +++ b/rust/pact_models/src/generators/mod.rs @@ -26,7 +26,7 @@ use crate::bodies::OptionalBody; use crate::expression_parser::{contains_expressions, DataType, DataValue, MapValueResolver, parse_expression}; #[cfg(feature = "datetime")] use crate::generators::datetime_expressions::{execute_date_expression, execute_datetime_expression, execute_time_expression}; use crate::json_utils::{get_field_as_string, json_to_string, JsonToNum, resolve_path}; -use crate::matchingrules::{Category, MatchingRuleCategory}; +use crate::matchingrules::{Category, MatchingRuleCategory, indexed_field_path, v3_field_key}; use crate::PactSpecification; use crate::path_exp::DocPath; use crate::plugins::plugin_support; @@ -667,7 +667,9 @@ impl Generators { match sub_v { &Value::Object(ref map) => { if *category == GeneratorCategory::QUERY || *category == GeneratorCategory::HEADER { - self.parse_generator_from_map(category, map, Some(DocPath::root().push_field(sub_k).clone())); + let path = indexed_field_path(sub_k) + .unwrap_or_else(|| DocPath::root().push_field(sub_k).clone()); + self.parse_generator_from_map(category, map, Some(path)); } else { self.parse_generator_from_map(category, map, Some(DocPath::new(sub_k)?)); } @@ -726,9 +728,7 @@ impl Generators { for (key, val) in category { let json = val.to_json(); if let Some(json) = json { - let name = key.first_field().map(|v| v.to_string()) - .unwrap_or_else(|| key.to_string()); - generators.insert(name, json); + generators.insert(v3_field_key(key, category.keys()), json); } } map.insert(cat.clone(), Value::Object(generators)); @@ -2437,6 +2437,26 @@ mod tests { expect!(json.to_string()).to_not(be_equal_to("{}")); } + #[test] + fn generators_for_each_header_and_query_value_round_trip_through_json() { + let path = DocPath::root().join("X-Request"); + let mut generators = Generators::default(); + for category in [GeneratorCategory::HEADER, GeneratorCategory::QUERY] { + generators.add_generator_with_subcategory(&category, path.clone(), Generator::RandomInt(1, 10)); + generators.add_generator_with_subcategory(&category, path.join("1"), Generator::RandomInt(20, 30)); + } + + let json = generators_to_json(&generators, &PactSpecification::V4); + let expected = json!({ + "X-Request": { "type": "RandomInt", "min": 1, "max": 10 }, + "$['X-Request'][1]": { "type": "RandomInt", "min": 20, "max": 30 } + }); + assert_eq!(json, json!({ "header": expected, "query": expected })); + + let loaded = generators_from_json(&json!({ "generators": json })).unwrap(); + assert_eq!(loaded, generators); + } + #[test] fn hash_test_for_generators() { let g1 = Generators::default(); diff --git a/rust/pact_models/src/matchingrules/mod.rs b/rust/pact_models/src/matchingrules/mod.rs index 2c7b7b68d..d93e5a1d1 100644 --- a/rust/pact_models/src/matchingrules/mod.rs +++ b/rust/pact_models/src/matchingrules/mod.rs @@ -1123,9 +1123,7 @@ impl MatchingRuleCategory { Value::Object(self.rules.iter().fold(serde_json::Map::new(), |mut map, (category, rulelist)| { match self.name { Category::HEADER | Category::QUERY => { - let name = category.first_field().map(|v| v.to_string()) - .unwrap_or_else(|| category.to_string()); - map.insert(name, rulelist.to_v3_json()); + map.insert(v3_field_key(category, self.rules.keys()), rulelist.to_v3_json()); } _ => { map.insert(String::from(category), rulelist.to_v3_json()); @@ -1255,8 +1253,11 @@ impl MatchingRuleCategory { self.add_rule_list(DocPath::empty(), rules)?; } else if self.name == Category::QUERY || self.name == Category::HEADER { for (k, v) in m { - let mut path = DocPath::root(); - path.push_field(k); + let path = indexed_field_path(k).unwrap_or_else(|| { + let mut path = DocPath::root(); + path.push_field(k); + path + }); self.add_rule_list(path, v)?; } } else { @@ -1627,6 +1628,36 @@ impl Display for MatchingRules { } } +/// Key used for a header or query parameter rule or generator in V3+ format. Entries for a single +/// value (`$.name[1]`) keep their full path, as the bare name would collide with the entries for +/// the other values. An entry for the first value is written as the bare name when it is the only +/// entry for that name, which is how it has always been written. +pub(crate) fn v3_field_key<'a>(path: &DocPath, keys: impl Iterator) -> String { + match path.tokens().as_slice() { + [PathToken::Root, PathToken::Field(name)] => name.clone(), + [PathToken::Root, PathToken::Field(name), PathToken::Index(index)] => { + let mut keys = keys; + let shares_name = keys.any(|other| other != path && other.first_field() == Some(name.as_str())); + if *index == 0 && !shares_name { + name.clone() + } else { + path.to_string() + } + } + _ => path.first_field().map(|v| v.to_string()).unwrap_or_else(|| path.to_string()) + } +} + +/// Parses a V3+ header or query parameter key written for a single value (`$.name[1]` or +/// `$['name'][1]`). Any other key is a plain header or parameter name. +pub(crate) fn indexed_field_path(key: &str) -> Option { + if !key.starts_with('$') { + return None; + } + DocPath::new(key).ok().filter(|path| matches!(path.tokens().as_slice(), + [PathToken::Root, PathToken::Field(_), PathToken::Index(_)])) +} + /// Parses the matching rules from the Value structure pub fn matchers_from_json(value: &Value, deprecated_name: &Option ) -> anyhow::Result { @@ -3018,4 +3049,87 @@ mod tests { })); expect!(rule.can_cascade()).to(be_false()); } + + fn indexed_field_rules(category: &str) -> MatchingRuleCategory { + let mut rules = MatchingRuleCategory::empty(category); + let path = DocPath::root().join("X-Request"); + rules.add_rule(path.clone(), MatchingRule::Regex("^first-\\d+$".to_string()), RuleLogic::And); + rules.add_rule(path.join("1"), MatchingRule::Regex("^second-\\d+$".to_string()), RuleLogic::And); + rules + } + + #[test] + fn to_v3_json_keeps_rules_for_each_header_and_query_value() { + let mut matching_rules = MatchingRules::default(); + matching_rules.add_rules("header", indexed_field_rules("header")); + matching_rules.add_rules("query", indexed_field_rules("query")); + + let expected = json!({ + "X-Request": { + "combine": "AND", + "matchers": [ { "match": "regex", "regex": "^first-\\d+$" } ] + }, + "$['X-Request'][1]": { + "combine": "AND", + "matchers": [ { "match": "regex", "regex": "^second-\\d+$" } ] + } + }); + for spec in [PactSpecification::V3, PactSpecification::V4] { + let json = matchers_to_json(&matching_rules, &spec); + assert_eq!(json, json!({ "header": expected, "query": expected })); + } + } + + #[test] + fn rules_for_each_header_and_query_value_round_trip_through_json() { + let mut matching_rules = MatchingRules::default(); + matching_rules.add_rules("header", indexed_field_rules("header")); + matching_rules.add_rules("query", indexed_field_rules("query")); + + let json = json!({ "matchingRules": matchers_to_json(&matching_rules, &PactSpecification::V4) }); + let loaded = matchers_from_json(&json, &None).unwrap(); + + assert_eq!(loaded, matching_rules); + } + + #[test] + fn to_v3_json_writes_a_lone_first_value_rule_as_the_bare_name() { + let mut rules = MatchingRuleCategory::empty("query"); + rules.add_rule(DocPath::root().join("a").join("0"), MatchingRule::Type, RuleLogic::And); + + expect!(rules.to_v3_json()).to(be_equal_to(json!({ + "a": { "combine": "AND", "matchers": [ { "match": "type" } ] } + }))); + } + + #[test] + fn to_v3_json_keeps_the_first_value_index_when_other_values_have_rules() { + let mut rules = MatchingRuleCategory::empty("query"); + let path = DocPath::root().join("a"); + rules.add_rule(path.join("0"), MatchingRule::Type, RuleLogic::And); + rules.add_rule(path.join("1"), MatchingRule::Integer, RuleLogic::And); + + expect!(rules.to_v3_json()).to(be_equal_to(json!({ + "$.a[0]": { "combine": "AND", "matchers": [ { "match": "type" } ] }, + "$.a[1]": { "combine": "AND", "matchers": [ { "match": "integer" } ] } + }))); + } + + #[test] + fn add_v3_rules_from_json_treats_bracketed_names_as_plain_names() { + let mut rules = MatchingRuleCategory::empty("query"); + rules.add_v3_rules_from_json(&json!({ + "ids[0]": { "matchers": [ { "match": "type" } ] }, + "$filter": { "matchers": [ { "match": "type" } ] }, + "$.a[2]": { "matchers": [ { "match": "type" } ] } + })).unwrap(); + + let mut paths = rules.rules.keys().map(|p| p.tokens().clone()).collect::>(); + paths.sort_by_key(|tokens| format!("{:?}", tokens)); + expect!(paths).to(be_equal_to(vec![ + vec![PathToken::Root, PathToken::Field("$filter".to_string())], + vec![PathToken::Root, PathToken::Field("a".to_string()), PathToken::Index(2)], + vec![PathToken::Root, PathToken::Field("ids[0]".to_string())] + ])); + } }