1 /*
2 * Copyright 2016 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_NDEBUG 0
18 #define LOG_TAG "cam_semaphore_tests"
19 #include <utils/Log.h>
20
21 #include <gtest/gtest.h>
22
23 #include "cam_semaphore.h"
24
25 #define NS_PER_S 1000000000
26
27 //10 ms is about standard timer resolution for most non-RTOS.
28 #define TIME_THRESHOLD_IN_NS 10000000
29
timespec_add_ms(timespec & ts,size_t ms)30 static inline void timespec_add_ms(timespec& ts, size_t ms) {
31 ts.tv_sec += ms / 1000;
32 ts.tv_nsec += (ms % 1000) * 1000000;
33 if (ts.tv_nsec >= NS_PER_S) {
34 ts.tv_sec++;
35 ts.tv_nsec -= NS_PER_S;
36 }
37 }
38
time_diff(timespec & ts_start,timespec & ts_end)39 static inline int64_t time_diff(timespec& ts_start, timespec& ts_end) {
40 if (ts_start.tv_sec == ts_end.tv_sec) {
41 return (int64_t)ts_end.tv_nsec - ts_start.tv_nsec;
42 } else {
43 return (int64_t)(ts_end.tv_sec - 1 - ts_start.tv_sec) * NS_PER_S +
44 ts_end.tv_nsec + NS_PER_S - ts_start.tv_nsec;
45 }
46 }
47
48 // Test cam_semaphore_timedwait
TEST(cam_semaphore_tests,cam_semaphore_timedwait)49 TEST(cam_semaphore_tests, cam_semaphore_timedwait) {
50
51 cam_semaphore_t sem;
52 cam_sem_init(&sem, 0);
53
54 // Test timeout
55 timespec ts;
56 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
57 timespec_add_ms(ts, 100);
58
59 errno = 0;
60 ASSERT_EQ(-1, cam_sem_timedwait(&sem, &ts));
61 timespec ts_end;
62 clock_gettime(CLOCK_MONOTONIC, &ts_end);
63
64 ASSERT_EQ(ETIMEDOUT, errno);
65 // Check time after timeout ~= time before call + timeout
66 ASSERT_GE(time_diff(ts, ts_end), 0);
67 ASSERT_LT(time_diff(ts, ts_end), TIME_THRESHOLD_IN_NS);
68
69 // Test successful wait
70 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
71 timespec_add_ms(ts, 100);
72
73 errno = 0;
74 cam_sem_post(&sem);
75 ASSERT_EQ(0, cam_sem_timedwait(&sem, &ts));
76 ASSERT_EQ(0, errno);
77 }
78