1 /**
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <gmock/gmock.h>
17 #include <gtest/gtest.h>
18
19 #include <random>
20 #include <thread>
21
22 #include "runtime/include/mem/panda_string.h"
23 #include "runtime/include/runtime.h"
24 #include "runtime/include/time_utils.h"
25
26 #ifndef PANDA_NIGHTLY_TEST_ON
27 constexpr size_t ITERATION = 64;
28 #else
29 constexpr size_t ITERATION = 1024;
30 #endif
31
32 namespace panda::time::test {
33
34 class TimeTest : public testing::Test {
35 public:
TimeTest()36 TimeTest()
37 {
38 RuntimeOptions options;
39 options.SetShouldLoadBootPandaFiles(false);
40 options.SetShouldInitializeIntrinsics(false);
41 Runtime::Create(options);
42 thread_ = panda::MTManagedThread::GetCurrent();
43 thread_->ManagedCodeBegin();
44 }
45
~TimeTest()46 ~TimeTest() override
47 {
48 thread_->ManagedCodeEnd();
49 Runtime::Destroy();
50 }
51
52 protected:
53 panda::MTManagedThread *thread_;
54 };
55
TEST_F(TimeTest,TimerTest)56 TEST_F(TimeTest, TimerTest)
57 {
58 uint64_t duration_ = 0;
59 {
60 Timer timer(&duration_);
61 std::this_thread::sleep_for(std::chrono::nanoseconds(10));
62 }
63 ASSERT_GT(duration_, 0);
64
65 uint64_t last_duration_ = duration_;
66 {
67 Timer timer(&duration_);
68 std::this_thread::sleep_for(std::chrono::nanoseconds(10));
69 }
70 ASSERT_GT(duration_, last_duration_);
71
72 {
73 Timer timer(&duration_, true);
74 ASSERT_EQ(duration_, 0);
75 }
76 // There is some nondeterminism in sleep, moreover with small values
77 // and check (duration_ < last_duration_) may fail
78 ASSERT_GT(duration_, 0);
79 }
80
TEST_F(TimeTest,CurrentTimeStringTest)81 TEST_F(TimeTest, CurrentTimeStringTest)
82 {
83 constexpr auto PATTERN =
84 "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}";
85 for (size_t i = 0; i < ITERATION; i++) {
86 auto date = GetCurrentTimeString();
87 ASSERT_EQ(date.size(), 19);
88 ASSERT_THAT(date.c_str(), ::testing::MatchesRegex(PATTERN));
89 std::this_thread::sleep_for(std::chrono::milliseconds(10));
90 }
91 }
92
93 } // namespace panda::time::test
94