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 23namespace { 24 25using std::chrono::nanoseconds; 26using std::chrono::milliseconds; 27 28#define ASSERT_EQ_WITH_TOLERANCE(val1, val2, tolerance) \ 29ASSERT_LE(val1 - tolerance, val2); \ 30ASSERT_GE(val1 + tolerance, val2); \ 31 32 33TEST(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 ASSERT_EQ_WITH_TOLERANCE(100, counter.load(), 20); 45} 46 47TEST(RecurrentTimerTest, multipleIntervals) { 48 std::atomic<int64_t> counter1ms { 0L }; 49 std::atomic<int64_t> counter5ms { 0L }; 50 auto counter1msRef = std::ref(counter1ms); 51 auto counter5msRef = std::ref(counter5ms); 52 RecurrentTimer timer( 53 [&counter1msRef, &counter5msRef](const std::vector<int32_t>& cookies) { 54 for (int32_t cookie : cookies) { 55 if (cookie == 0xdead) { 56 counter1msRef.get()++; 57 } else if (cookie == 0xbeef) { 58 counter5msRef.get()++; 59 } else { 60 FAIL(); 61 } 62 } 63 }); 64 65 timer.registerRecurrentEvent(milliseconds(1), 0xdead); 66 timer.registerRecurrentEvent(milliseconds(5), 0xbeef); 67 68 std::this_thread::sleep_for(milliseconds(100)); 69 ASSERT_EQ_WITH_TOLERANCE(100, counter1ms.load(), 20); 70 ASSERT_EQ_WITH_TOLERANCE(20, counter5ms.load(), 5); 71} 72 73} // anonymous namespace 74