• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <thread>
18 
19 #include <gtest/gtest.h>
20 
21 #include "vhal_v2_0/RecurrentTimer.h"
22 
23 namespace {
24 
25 using std::chrono::nanoseconds;
26 using std::chrono::milliseconds;
27 
28 #define ASSERT_EQ_WITH_TOLERANCE(val1, val2, tolerance) \
29 ASSERT_LE(val1 - tolerance, val2); \
30 ASSERT_GE(val1 + tolerance, val2); \
31 
32 
TEST(RecurrentTimerTest,oneInterval)33 TEST(RecurrentTimerTest, oneInterval) {
34     std::atomic<int64_t> counter { 0L };
35     auto counterRef = std::ref(counter);
36     RecurrentTimer timer([&counterRef](const std::vector<int32_t>& cookies) {
37         ASSERT_EQ(1u, cookies.size());
38         ASSERT_EQ(0xdead, cookies.front());
39         counterRef.get()++;
40     });
41 
42     timer.registerRecurrentEvent(milliseconds(100), 0xdead);
43     std::this_thread::sleep_for(milliseconds(1000));
44     // This test is unstable, so set the tolerance to 5.
45     ASSERT_EQ_WITH_TOLERANCE(10, counter.load(), 5);
46 }
47 
TEST(RecurrentTimerTest,multipleIntervals)48 TEST(RecurrentTimerTest, multipleIntervals) {
49     std::atomic<int64_t> counter100ms { 0L };
50     std::atomic<int64_t> counter50ms { 0L };
51     auto counter100msRef = std::ref(counter100ms);
52     auto counter50msRef = std::ref(counter50ms);
53     RecurrentTimer timer(
54             [&counter100msRef, &counter50msRef](const std::vector<int32_t>& cookies) {
55         for (int32_t cookie : cookies) {
56             if (cookie == 0xdead) {
57                 counter100msRef.get()++;
58             } else if (cookie == 0xbeef) {
59                 counter50msRef.get()++;
60             } else {
61                 FAIL();
62             }
63         }
64     });
65 
66     timer.registerRecurrentEvent(milliseconds(100), 0xdead);
67     timer.registerRecurrentEvent(milliseconds(50), 0xbeef);
68 
69     std::this_thread::sleep_for(milliseconds(1000));
70     // This test is unstable, so set the tolerance to 5.
71     ASSERT_EQ_WITH_TOLERANCE(10, counter100ms.load(), 5);
72     ASSERT_EQ_WITH_TOLERANCE(20, counter50ms.load(), 10);
73 }
74 
75 }  // anonymous namespace
76