Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion rust/pact_matching/src/engine/bodies/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,41 @@ impl JsonPlanBuilder {
let each_value_context = Self::each_value_context(context, path, &rules, false);
root_node.add(Self::build_for_each_value_node(&each_value_context, path, template));
}
} else if entries.is_empty() {
} else if Self::is_or_with_null(&rules) {
// The rules are combined with OR and allow a null value, so the actual value must match the
// rules, and the structure of the object is only checked if it is not null
root_node.add(ExecutionPlanNode::annotation(rules.generate_description(true)));
root_node.add(build_matching_rule_node(&ExecutionPlanNode::value_node(json.clone()),
&ExecutionPlanNode::resolve_current_value(path), &rules, true,
context.config.show_types_in_errors));
let mut structure_node = ExecutionPlanNode::container(path);
Self::process_object_entries(context, path, &mut structure_node, entries);
for child in structure_node.children {
root_node.add(
ExecutionPlanNode::action("if")
.add(ExecutionPlanNode::action("json:not-null")
.add(ExecutionPlanNode::resolve_current_value(path)))
.add(child)
);
}
} else {
Self::process_object_entries(context, path, root_node, entries);
}
}

/// If the rules are combined with OR and include a null matcher
fn is_or_with_null(rules: &RuleList) -> bool {
!rules.cascaded && rules.rule_logic == RuleLogic::Or && rules.rules.len() > 1 &&
rules.rules.iter().any(|rule| matches!(rule, MatchingRule::Null))
}

fn process_object_entries(
context: &PlanMatchingContext,
path: &DocPath,
root_node: &mut ExecutionPlanNode,
entries: &Map<String, Value>
) {
if entries.is_empty() {
root_node.add(
ExecutionPlanNode::action("json:expect:empty")
.add(ExecutionPlanNode::value_node("OBJECT"))
Expand Down
42 changes: 39 additions & 3 deletions rust/pact_matching/src/engine/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ impl ExecutionPlanInterpreter {
"json:expect:not-empty" => self.execute_json_expect_empty(action, value_resolver, node, &action_path, false),
"json:match:length" => self.execute_json_match_length(action, value_resolver, node, &action_path),
"json:expect:entries" => self.execute_json_expect_entries(action, value_resolver, node, &action_path),
"json:not-null" => self.execute_json_not_null(action, value_resolver, node, &action_path),
"check:exists" => self.execute_check_exists(action, value_resolver, node, &action_path),
"expect:entries" => self.execute_check_entries(action, value_resolver, node, &action_path),
"expect:only-entries" => self.execute_check_entries(action, value_resolver, node, &action_path),
Expand Down Expand Up @@ -1866,6 +1867,40 @@ impl ExecutionPlanInterpreter {
}
}

/// Returns a boolean value of true if the argument is a value that is not a JSON null. Unlike
/// the `json:expect:*` actions, it does not result in an error for a JSON null value.
fn execute_json_not_null(
&mut self,
action: &str,
value_resolver: &dyn ValueResolver,
node: ExecutionPlanNode,
action_path: &Vec<String>
) -> ExecutionPlanNode {
let ExecutionPlanNode { node_type, children, .. } = node;
match self.validate_one_arg(children, action, value_resolver, &action_path) {
Ok(value) => {
let not_null = match value.value().unwrap_or_default() {
NodeResult::VALUE(NodeValue::NULL) => false,
NodeResult::VALUE(NodeValue::JSON(Value::Null)) => false,
NodeResult::VALUE(_) => true,
_ => false
};
ExecutionPlanNode {
node_type,
result: Some(NodeResult::VALUE(NodeValue::BOOL(not_null))),
children: vec![value]
}
}
Err(err) => {
ExecutionPlanNode {
node_type,
result: Some(NodeResult::ERROR(err.to_string())),
children: vec![]
}
}
}
}

fn execute_check_exists(
&mut self,
action: &str,
Expand Down Expand Up @@ -2429,9 +2464,10 @@ impl ExecutionPlanInterpreter {
Ok((result_children, values)) => {
ExecutionPlanNode {
node_type,
result: Some(values.iter().fold(NodeResult::OK, |result, value| {
result.or(value)
})),
// Fold from the first child result, as folding from OK would always result in OK
result: Some(values.split_first()
.map(|(first, rest)| rest.iter().fold(first.clone(), |result, value| result.or(value)))
.unwrap_or(NodeResult::OK)),
children: result_children
}
}
Expand Down
11 changes: 10 additions & 1 deletion rust/pact_matching/src/engine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1286,7 +1286,13 @@ impl ExecutionPlanNode {
self.is_container() && !self.has_child_containers()
}

/// If this node is a container
/// If this node is an OR action node that has been executed successfully
pub fn is_successful_or(&self) -> bool {
matches!(&self.node_type, PlanNodeType::ACTION(action) if action == "or")
&& matches!(&self.result, Some(result) if !matches!(result, NodeResult::ERROR(_)))
}

/// If this node is a container node
pub fn is_container(&self) -> bool {
if let PlanNodeType::CONTAINER(_) = &self.node_type {
true
Expand Down Expand Up @@ -1314,6 +1320,9 @@ impl ExecutionPlanNode {
if child.is_container() && terminator == Terminator::ALL || !child.is_container() {
if let Some(NodeResult::ERROR(error)) = &child.result {
errors.push(error.clone());
} else if child.is_successful_or() {
// Only one branch of an OR needs to succeed, so errors from the other branches are not mismatches
continue;
}
errors.extend_from_slice(child.child_errors(terminator).as_slice());
}
Expand Down
1 change: 1 addition & 0 deletions rust/pact_matching/src/engine/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ mod each_value_tests;
mod walk_tree_tests;
mod query_tests;
mod header_tests;
mod or_matcher_tests;

#[rstest(
case("", "''"),
Expand Down
175 changes: 175 additions & 0 deletions rust/pact_matching/src/engine/tests/or_matcher_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
//! Tests for matching rules combined with OR (`RuleLogic::Or`) in the V2 matching engine

use bytes::Bytes;
use pretty_assertions::assert_eq;

use pact_models::bodies::OptionalBody;
use pact_models::content_types::JSON;
use pact_models::matchingrules::{MatchingRule, MatchingRuleCategory, MatchingRules, RuleLogic};
use pact_models::path_exp::DocPath;
use pact_models::prelude::v4::SynchronousHttp;
use pact_models::v4::http_parts::HttpResponse;
use pact_models::v4::interaction::V4Interaction;

use crate::engine::{build_response_plan, execute_response_plan, PlanMatchingContext};
use crate::engine::context::MatchingConfiguration;
use crate::Mismatch;

fn body_rules(rules: Vec<(&str, MatchingRule, RuleLogic)>) -> MatchingRuleCategory {
let mut category = MatchingRuleCategory::empty("body");
for (path, rule, logic) in rules {
category.add_rule(DocPath::new(path).unwrap(), rule, logic);
}
category
}

/// Matches the actual body to the expected one with the V2 engine, and returns the body mismatches
/// as `path: mismatch`
fn mismatches(rules: &MatchingRuleCategory, expected: &str, actual: &str) -> Vec<String> {
let mut matching_rules = MatchingRules::default();
matching_rules.add_rules("body", rules.clone());
let expected_response = HttpResponse {
body: OptionalBody::Present(Bytes::from(expected.to_string()), Some(JSON.clone()), None),
matching_rules,
.. HttpResponse::default()
};
let actual_response = HttpResponse {
body: OptionalBody::Present(Bytes::from(actual.to_string()), Some(JSON.clone()), None),
.. HttpResponse::default()
};
let interaction = SynchronousHttp {
response: expected_response.clone(),
.. SynchronousHttp::default()
};
let context = PlanMatchingContext {
interaction: interaction.boxed_v4(),
config: MatchingConfiguration {
allow_unexpected_entries: true,
log_plan_summary: false,
.. MatchingConfiguration::default()
},
.. PlanMatchingContext::default()
};
let plan = build_response_plan(&expected_response, &context).unwrap();
let executed_plan = execute_response_plan(&plan, &actual_response, &context).unwrap();
let mismatches: Vec<Mismatch> = executed_plan.into();
mismatches.iter()
.filter_map(|m| match m {
Mismatch::BodyMismatch { path, mismatch, .. } => Some(format!("{}: {}", path, mismatch)),
_ => None
})
.collect()
}


fn regex(r: &str) -> MatchingRule { MatchingRule::Regex(r.to_string()) }

#[test_log::test]
fn scalar_with_type_or_null() {
let rules = body_rules(vec![
("$.a", MatchingRule::Type, RuleLogic::Or),
("$.a", MatchingRule::Null, RuleLogic::Or)
]);
let expected = r#"{"a":"string"}"#;
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":"other"}"#));
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":null}"#));
assert_eq!(false, mismatches(&rules, expected, r#"{"a":100}"#).is_empty());
}

#[test_log::test]
fn scalar_with_two_regexes() {
let rules = body_rules(vec![
("$.a", regex("^\\d+$"), RuleLogic::Or),
("$.a", regex("^[a-z]+$"), RuleLogic::Or)
]);
let expected = r#"{"a":"100"}"#;
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":"200"}"#));
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":"abc"}"#));
assert_eq!(false, mismatches(&rules, expected, r#"{"a":"ABC"}"#).is_empty());
}

#[test_log::test]
fn integer_or_decimal() {
let rules = body_rules(vec![
("$.a", MatchingRule::Integer, RuleLogic::Or),
("$.a", MatchingRule::Decimal, RuleLogic::Or)
]);
let expected = r#"{"a":100}"#;
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":1}"#));
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":1.5}"#));
assert_eq!(false, mismatches(&rules, expected, r#"{"a":"1"}"#).is_empty());
}

#[test_log::test]
fn object_with_type_or_null() {
let rules = body_rules(vec![
("$.a", MatchingRule::Type, RuleLogic::Or),
("$.a", MatchingRule::Null, RuleLogic::Or)
]);
let expected = r#"{"a":{"b":"string"}}"#;
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":{"b":"other"}}"#));
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":null}"#));
}

#[test_log::test]
fn array_with_type_or_null() {
let rules = body_rules(vec![
("$.a", MatchingRule::MinType(1), RuleLogic::Or),
("$.a", MatchingRule::Null, RuleLogic::Or)
]);
let expected = r#"{"a":[1]}"#;
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":[2,3]}"#));
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":null}"#));
}

#[test_log::test]
fn object_with_type_or_null_rejects_other_types() {
let rules = body_rules(vec![
("$.a", MatchingRule::Type, RuleLogic::Or),
("$.a", MatchingRule::Null, RuleLogic::Or)
]);
let expected = r#"{"a":{"b":"string"}}"#;
let result = mismatches(&rules, expected, r#"{"a":"string"}"#);
assert_eq!(false, result.is_empty());
assert!(result.iter().all(|m| m.starts_with("$.a")), "{:?}", result);
}

#[test_log::test]
fn object_with_type_or_null_still_applies_the_nested_rules() {
let rules = body_rules(vec![
("$.a", MatchingRule::Type, RuleLogic::Or),
("$.a", MatchingRule::Null, RuleLogic::Or),
("$.a.id", MatchingRule::Integer, RuleLogic::And)
]);
let expected = r#"{"a":{"id":100}}"#;
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":{"id":200}}"#));
assert_eq!(Vec::<String>::new(), mismatches(&rules, expected, r#"{"a":null}"#));
assert_eq!(vec!["$.a.id: Expected '200' (String) to be an integer".to_string()],
mismatches(&rules, expected, r#"{"a":{"id":"200"}}"#));
assert_eq!(false, mismatches(&rules, expected, r#"{"a":{}}"#).is_empty());
}

#[test_log::test]
fn a_successful_or_does_not_report_the_errors_from_the_other_branches() {
let rules = body_rules(vec![
("$.a", MatchingRule::Integer, RuleLogic::Or),
("$.a", MatchingRule::Null, RuleLogic::Or),
("$.b", MatchingRule::Integer, RuleLogic::And)
]);
let expected = r#"{"a":100,"b":100}"#;
assert_eq!(vec!["$.b: Expected 'x' (String) to be an integer".to_string()],
mismatches(&rules, expected, r#"{"a":null,"b":"x"}"#));
assert_eq!(vec!["$.b: Expected 'x' (String) to be an integer".to_string()],
mismatches(&rules, expected, r#"{"a":200,"b":"x"}"#));
}

#[test_log::test]
fn a_failed_or_reports_the_errors_from_all_the_branches() {
let rules = body_rules(vec![
("$.a", MatchingRule::Integer, RuleLogic::Or),
("$.a", MatchingRule::Null, RuleLogic::Or)
]);
let result = mismatches(&rules, r#"{"a":100}"#, r#"{"a":"x"}"#);
assert!(result.iter().any(|m| m.contains("to be an integer")), "{:?}", result);
assert!(result.iter().any(|m| m.to_lowercase().contains("null")), "{:?}", result);
}
Loading