1 /*
2 * Copyright (C) 2017 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 <memory>
18
19 #include "tests/functions.h"
20 #include "gtest/gtest.h"
21
22 namespace libtextclassifier {
23 namespace nlp_core {
24 namespace functions {
25
TEST(RegistryTest,InstantiateFunctionsByName)26 TEST(RegistryTest, InstantiateFunctionsByName) {
27 // First, we need to register the functions we are interested in:
28 Exp::RegisterClass();
29 Inc::RegisterClass();
30 Cos::RegisterClass();
31
32 // RegisterClass methods can be called in any order, even multiple times :)
33 Cos::RegisterClass();
34 Inc::RegisterClass();
35 Inc::RegisterClass();
36 Cos::RegisterClass();
37 Inc::RegisterClass();
38
39 // NOTE: we intentionally do not register Dec. Attempts to create an instance
40 // of that function by name should fail.
41
42 // Instantiate a few functions and check that the created functions produce
43 // the expected results for a few sample values.
44 std::unique_ptr<Function> f1(Function::Create("cos"));
45 ASSERT_NE(f1, nullptr);
46 std::unique_ptr<Function> f2(Function::Create("exp"));
47 ASSERT_NE(f2, nullptr);
48 EXPECT_NEAR(f1->Evaluate(-3), -0.9899, 0.0001);
49 EXPECT_NEAR(f2->Evaluate(2.3), 9.9741, 0.0001);
50
51 std::unique_ptr<IntFunction> f3(IntFunction::Create("inc"));
52 ASSERT_NE(f3, nullptr);
53 EXPECT_EQ(f3->Evaluate(7), 8);
54
55 // Instantiating unknown functions should return nullptr, but not crash
56 // anything.
57 EXPECT_EQ(Function::Create("mambo"), nullptr);
58
59 // Functions that are defined in the code, but are not registered are unknown.
60 EXPECT_EQ(IntFunction::Create("dec"), nullptr);
61
62 // Function and IntFunction use different registries.
63 EXPECT_EQ(IntFunction::Create("exp"), nullptr);
64 }
65
66 } // namespace functions
67 } // namespace nlp_core
68 } // namespace libtextclassifier
69