class RulesetMatcher(object): def __init__(self): # type: () -> None super(RulesetMatcher, self).__init__() self._matcher = RuleMatcher() def is_matching(self, match_object, ruleset): # type: (RulesetMatchObject, List[Dict]) -> bool """Compute outcome of a ruleset set that just says yes/no The binary match only cares about the first matching rule of an object. Depending on the value the outcome is negated or not. Replaces in_binary_hostlist / in_boolean_serviceconf_list""" for rule in ruleset: if rule.get("options", {}).get("disabled", False): continue if self._matcher.match(match_object.to_dict(), rule["condition"]): return rule["value"] return False def get_merged_dict(self, match_object, ruleset): # type: (RulesetMatchObject, List[Dict]) -> Dict """Returns a dictionary of the merged dict values of the matched rules The first dict setting a key defines the final value. Replaces host_extra_conf_merged / service_extra_conf_merged""" rule_dict = {} # type: Dict for value_dict in self.get_values(match_object, ruleset): for key, value in value_dict.items(): rule_dict.setdefault(key, value) return rule_dict def get_values(self, match_object, ruleset): # type: (RulesetMatchObject, List) -> List[Any] """Returns a list of the values of the matched rules Replaces host_extra_conf / service_extra_conf""" return [r["value"] for r in self.get_matching_rules(match_object, ruleset)] def get_matching_rules(self, match_object, ruleset): # type: (RulesetMatchObject, List) -> List[Dict] """Filter the ruleset of this matcher for the given object and return the filtered rule list """ return [ rule for rule in ruleset if not rule.get("options", {}).get("disabled", False) and self._matcher.match(match_object.to_dict(), rule["condition"]) ]
def __init__(self): # type: () -> None super(RulesetMatcher, self).__init__() self._matcher = RuleMatcher()
def test_rule_condition_matcher_mixed_operator_object(): with pytest.raises(MatchingError, match="Unknown value operator"): RuleMatcher().match({"a": "b"}, {"a": {"$eq": "b", "mix": "up"}})
def test_rule_condition_matcher_unknown_value_operator(): with pytest.raises(MatchingError): RuleMatcher().match({"a": "b"}, {"a": {"$zz": ""}})
def test_rule_condition_matcher_invalid_document(): with pytest.raises(MatchingError): RuleMatcher().match(None, {})
def test_rule_condition_matcher_invalid_expression(): with pytest.raises(MatchingError): RuleMatcher().match({}, None)
def test_rule_condition_matcher(test_case): matched = [h for h in HOSTS if RuleMatcher().match(h, test_case.condition)] assert matched == test_case.expected_result