Skip to content

Commit

Permalink
[ads] Add SmartNTT pref path “NOT” condition matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
tmancey committed Oct 29, 2024
1 parent b6fc1b8 commit a0c201c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ namespace brave_ads {

namespace {

constexpr char kNotOperatorPrefix[] = "[!]:";

std::string NormalizePrefPath(const std::string& pref_path) {
return pref_path.starts_with(kNotOperatorPrefix)
? pref_path.substr(/*pos=*/std::strlen(kNotOperatorPrefix))
: pref_path;
}

bool MatchCondition(const std::string_view value,
const std::string_view condition) {
return MatchOperator(value, condition) || MatchPattern(value, condition) ||
Expand All @@ -32,15 +40,18 @@ bool MatchConditions(
condition_matchers, [pref_provider](const auto& condition_matcher) {
const auto& [pref_path, condition] = condition_matcher;

// If `has_not_operator` is `true`, it means that the condition should
// match if the pref path does not exist.
const bool has_not_operator = pref_path.starts_with(kNotOperatorPrefix);

const std::string normalized_pref_path = NormalizePrefPath(pref_path);
if (const std::optional<std::string> value = MaybeGetPrefValueAsString(
pref_provider, normalized_pref_path)) {
return MatchCondition(*value, condition);
return !has_not_operator && MatchCondition(*value, condition);
}

// Do not serve the ad due to an unknown preference path or
// unsupported value type.
return false;
// Unknown pref path.
return has_not_operator;
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ TEST_F(BraveAdsNewTabPageAdServingConditionMatcherUtilTest,
EXPECT_FALSE(MatchConditions(&pref_provider_, condition_matchers));
}

TEST_F(BraveAdsNewTabPageAdServingConditionMatcherUtilTest,
MatchConditionsWithNotOperatorWhenPrefPathNotFound) {
// Arrange
const NewTabPageAdConditionMatcherMap condition_matchers = {
{"[!]:foo.bar", "baz"}};

// Act & Assert
EXPECT_TRUE(MatchConditions(&pref_provider_, condition_matchers));
}

TEST_F(BraveAdsNewTabPageAdServingConditionMatcherUtilTest,
DoNotMatchConditionsIfAllConditionsAreFalse) {
// Arrange
Expand Down

0 comments on commit a0c201c

Please sign in to comment.