1 | //===-- unit tests for linux's timeout utilities --------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "src/__support/CPP/expected.h" |
10 | #include "src/__support/time/linux/abs_timeout.h" |
11 | #include "src/__support/time/linux/monotonicity.h" |
12 | #include "test/UnitTest/Test.h" |
13 | |
14 | template <class T, class E> |
15 | using expected = LIBC_NAMESPACE::cpp::expected<T, E>; |
16 | using AbsTimeout = LIBC_NAMESPACE::internal::AbsTimeout; |
17 | |
18 | TEST(LlvmLibcSupportLinuxTimeoutTest, NegativeSecond) { |
19 | timespec ts = {-1, 0}; |
20 | expected<AbsTimeout, AbsTimeout::Error> result = |
21 | AbsTimeout::from_timespec(ts, false); |
22 | ASSERT_FALSE(result.has_value()); |
23 | ASSERT_EQ(result.error(), AbsTimeout::Error::BeforeEpoch); |
24 | } |
25 | TEST(LlvmLibcSupportLinuxTimeoutTest, OverflowNano) { |
26 | using namespace LIBC_NAMESPACE::time_units; |
27 | timespec ts = {0, 2_s_ns}; |
28 | expected<AbsTimeout, AbsTimeout::Error> result = |
29 | AbsTimeout::from_timespec(ts, false); |
30 | ASSERT_FALSE(result.has_value()); |
31 | ASSERT_EQ(result.error(), AbsTimeout::Error::Invalid); |
32 | } |
33 | TEST(LlvmLibcSupportLinuxTimeoutTest, UnderflowNano) { |
34 | timespec ts = {0, -1}; |
35 | expected<AbsTimeout, AbsTimeout::Error> result = |
36 | AbsTimeout::from_timespec(ts, false); |
37 | ASSERT_FALSE(result.has_value()); |
38 | ASSERT_EQ(result.error(), AbsTimeout::Error::Invalid); |
39 | } |
40 | TEST(LlvmLibcSupportLinuxTimeoutTest, NoChangeIfClockIsMonotonic) { |
41 | timespec ts = {10000, 0}; |
42 | expected<AbsTimeout, AbsTimeout::Error> result = |
43 | AbsTimeout::from_timespec(ts, false); |
44 | ASSERT_TRUE(result.has_value()); |
45 | ensure_monotonicity(*result); |
46 | ASSERT_FALSE(result->is_realtime()); |
47 | ASSERT_EQ(result->get_timespec().tv_sec, static_cast<time_t>(10000)); |
48 | ASSERT_EQ(result->get_timespec().tv_nsec, static_cast<long int>(0)); |
49 | } |
50 | TEST(LlvmLibcSupportLinuxTimeoutTest, ValidAfterConversion) { |
51 | timespec ts; |
52 | LIBC_NAMESPACE::internal::clock_gettime(CLOCK_REALTIME, &ts); |
53 | expected<AbsTimeout, AbsTimeout::Error> result = |
54 | AbsTimeout::from_timespec(ts, true); |
55 | ASSERT_TRUE(result.has_value()); |
56 | ensure_monotonicity(*result); |
57 | ASSERT_FALSE(result->is_realtime()); |
58 | ASSERT_TRUE( |
59 | AbsTimeout::from_timespec(result->get_timespec(), false).has_value()); |
60 | } |
61 | |