Home | History | Annotate | Download | only in utils
      1 /*
      2  * Copyright (C) 2018 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #include "utils/regex-match.h"
     18 
     19 #include <memory>
     20 
     21 #include "utils/utf8/unilib.h"
     22 #include "gmock/gmock.h"
     23 #include "gtest/gtest.h"
     24 
     25 namespace libtextclassifier3 {
     26 namespace {
     27 
     28 class LuaVerifierTest : public testing::Test {
     29  protected:
     30   LuaVerifierTest() : INIT_UNILIB_FOR_TESTING(unilib_) {}
     31   UniLib unilib_;
     32 };
     33 
     34 #ifdef TC3_UNILIB_ICU
     35 TEST_F(LuaVerifierTest, HandlesSimpleVerification) {
     36   EXPECT_TRUE(VerifyMatch(/*context=*/"", /*matcher=*/nullptr, "return true;"));
     37 }
     38 
     39 TEST_F(LuaVerifierTest, HandlesCustomVerification) {
     40   UnicodeText pattern = UTF8ToUnicodeText("(\\d{16})",
     41                                           /*do_copy=*/true);
     42   UnicodeText message = UTF8ToUnicodeText("cc: 4012888888881881",
     43                                           /*do_copy=*/true);
     44   const std::string verifier = R"(
     45 function luhn(candidate)
     46     local sum = 0
     47     local num_digits = string.len(candidate)
     48     local parity = num_digits % 2
     49     for pos = 1,num_digits do
     50       d = tonumber(string.sub(candidate, pos, pos))
     51       if pos % 2 ~= parity then
     52         d = d * 2
     53       end
     54       if d > 9 then
     55         d = d - 9
     56       end
     57       sum = sum + d
     58     end
     59     return (sum % 10) == 0
     60 end
     61 return luhn(match[1].text);
     62   )";
     63   auto regex_pattern = unilib_.CreateRegexPattern(pattern);
     64   ASSERT_TRUE(regex_pattern != nullptr);
     65   auto matcher = regex_pattern->Matcher(message);
     66   ASSERT_TRUE(matcher != nullptr);
     67   int status = UniLib::RegexMatcher::kNoError;
     68   ASSERT_TRUE(matcher->Find(&status) &&
     69               status == UniLib::RegexMatcher::kNoError);
     70 
     71   EXPECT_TRUE(VerifyMatch(message.ToUTF8String(), matcher.get(), verifier));
     72 }
     73 #endif
     74 
     75 }  // namespace
     76 }  // namespace libtextclassifier3
     77