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(1), 0xdead);
43 std::this_thread::sleep_for(milliseconds(100));
44 // This test is unstable, so set the tolerance to 50.
45 ASSERT_EQ_WITH_TOLERANCE(100, counter.load(), 50);
46 }
47
TEST(RecurrentTimerTest,multipleIntervals)48 TEST(RecurrentTimerTest, multipleIntervals) {
49 std::atomic<int64_t> counter1ms { 0L };
50 std::atomic<int64_t> counter5ms { 0L };
51 auto counter1msRef = std::ref(counter1ms);
52 auto counter5msRef = std::ref(counter5ms);
53 RecurrentTimer timer(
54 [&counter1msRef, &counter5msRef](const std::vector<int32_t>& cookies) {
55 for (int32_t cookie : cookies) {
56 if (cookie == 0xdead) {
57 counter1msRef.get()++;
58 } else if (cookie == 0xbeef) {
59 counter5msRef.get()++;
60 } else {
61 FAIL();
62 }
63 }
64 });
65
66 timer.registerRecurrentEvent(milliseconds(1), 0xdead);
67 timer.registerRecurrentEvent(milliseconds(5), 0xbeef);
68
69 std::this_thread::sleep_for(milliseconds(100));
70 // This test is unstable, so set the tolerance to 50.
71 ASSERT_EQ_WITH_TOLERANCE(100, counter1ms.load(), 50);
72 ASSERT_EQ_WITH_TOLERANCE(20, counter5ms.load(), 10);
73 }
74
75 } // anonymous namespace
76