tests: extract stdout redirection
[platform/core/system/dlog.git] / tests / test_verifytime.c
1 /* DLOG
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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 <assert.h>
18 #include <dlogutil.h>
19 #include <stdlib.h>
20
21 static const int TIMEOUT_MS = 1000;
22
23 /* We allow the maximum difference of 5 seconds between correct and timestamp time.
24  * This is a window big enough to make false negatives almost impossible.
25  * The time skewing by less than 5 seconds consistently is possible, but improbable. */
26 static const int TIMESTAMP_WINDOW_S = 5;
27
28 bool are_timestamps_close(struct timespec a, struct timespec b) {
29         long long nsec_diff = (long long)a.tv_nsec - (long long)b.tv_nsec;
30         int sec_diff = (int)a.tv_sec - (int)b.tv_sec;
31         if (nsec_diff < 0)
32                 sec_diff -= 1;
33         else if (nsec_diff > 0)
34                 sec_diff += 1;
35         return abs(sec_diff) <= TIMESTAMP_WINDOW_S;
36 }
37
38 int main(void) {
39         struct timespec real_goal, mono_goal;
40         assert(clock_gettime(CLOCK_REALTIME, &real_goal) == 0);
41         assert(clock_gettime(CLOCK_MONOTONIC, &mono_goal) == 0);
42
43         dlogutil_config_s *c = dlogutil_config_create();
44         assert(c);
45
46         assert(dlogutil_config_buffer_add(c, LOG_ID_MAIN) == 0);
47         assert(dlogutil_config_mode_set_continuous(c) == 0);
48
49         dlogutil_state_s *s = NULL;
50         assert(dlogutil_config_connect(c, &s) == 0);
51         assert(s);
52
53         dlogutil_entry_s *e;
54         assert(dlogutil_get_log(s, TIMEOUT_MS, &e) == 0);
55
56         struct timespec scratch;
57         if (dlogutil_entry_get_timestamp(e, DLOGUTIL_SORT_RECV_REAL, &scratch) == 0)
58                 assert(are_timestamps_close(real_goal, scratch));
59         if (dlogutil_entry_get_timestamp(e, DLOGUTIL_SORT_SENT_REAL, &scratch) == 0)
60                 assert(are_timestamps_close(real_goal, scratch));
61         if (dlogutil_entry_get_timestamp(e, DLOGUTIL_SORT_RECV_MONO, &scratch) == 0)
62                 assert(are_timestamps_close(mono_goal, scratch));
63         if (dlogutil_entry_get_timestamp(e, DLOGUTIL_SORT_SENT_MONO, &scratch) == 0)
64                 assert(are_timestamps_close(mono_goal, scratch));
65
66         free(e);
67         dlogutil_state_destroy(s);
68         dlogutil_config_destroy(c);
69 }