1 /*
2  * Copyright (C) 2022 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 #define LOG_TAG "methodstatistics_tests"
18 
19 #include <mediautils/MethodStatistics.h>
20 
21 #include <atomic>
22 #include <gtest/gtest.h>
23 #include <utils/Log.h>
24 
25 using namespace android::mediautils;
26 using CodeType = size_t;
27 
28 constexpr CodeType HELLO_CODE = 10;
29 constexpr const char * HELLO_NAME = "hello";
30 constexpr float HELLO_EVENTS[] = { 1.f, 3.f }; // needs lossless average
31 
32 constexpr CodeType WORLD_CODE = 21;
33 constexpr const char * WORLD_NAME = "world";
34 
35 constexpr CodeType UNKNOWN_CODE = 12345;
36 
TEST(methodstatistics_tests,method_names)37 TEST(methodstatistics_tests, method_names) {
38     const MethodStatistics<CodeType> methodStatistics{
39             {HELLO_CODE, HELLO_NAME},
40             {WORLD_CODE, WORLD_NAME},
41     };
42 
43     ASSERT_EQ(std::string(HELLO_NAME), methodStatistics.getMethodForCode(HELLO_CODE));
44     ASSERT_EQ(std::string(WORLD_NAME), methodStatistics.getMethodForCode(WORLD_CODE));
45     // an unknown code returns itself as a number.
46     ASSERT_EQ(std::to_string(UNKNOWN_CODE), methodStatistics.getMethodForCode(UNKNOWN_CODE));
47 }
48 
TEST(methodstatistics_tests,events)49 TEST(methodstatistics_tests, events) {
50     MethodStatistics<CodeType> methodStatistics{
51             {HELLO_CODE, HELLO_NAME},
52             {WORLD_CODE, WORLD_NAME},
53     };
54 
55     size_t n = 0;
56     float sum = 0.f;
57     for (const auto event : HELLO_EVENTS) {
58         methodStatistics.event(HELLO_CODE, event);
59         sum += event;
60         ++n;
61     }
62 
63     const auto helloStats = methodStatistics.getStatistics(HELLO_CODE);
64     ASSERT_EQ((signed)n, helloStats.getN());
65     ASSERT_EQ(sum / n, helloStats.getMean());
66     ASSERT_EQ(n, methodStatistics.getMethodCount(HELLO_CODE));
67 
68     const auto unsetStats = methodStatistics.getStatistics(UNKNOWN_CODE);
69     ASSERT_EQ(0, unsetStats.getN());
70     ASSERT_EQ(0.f, unsetStats.getMean());
71     ASSERT_EQ(0U, methodStatistics.getMethodCount(UNKNOWN_CODE));
72 }
73