]>
Commit | Line | Data |
---|---|---|
11fdf7f2 TL |
1 | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved. |
2 | // This source code is licensed under both the GPLv2 (found in the | |
3 | // COPYING file in the root directory) and Apache 2.0 License | |
4 | // (found in the LICENSE.Apache file in the root directory). | |
5 | ||
6 | #include <atomic> | |
7 | #include <memory> | |
8 | ||
9 | #include "db/db_test_util.h" | |
10 | #include "util/repeatable_thread.h" | |
11 | #include "util/testharness.h" | |
12 | ||
13 | class RepeatableThreadTest : public testing::Test { | |
14 | public: | |
15 | RepeatableThreadTest() | |
16 | : mock_env_(new rocksdb::MockTimeEnv(rocksdb::Env::Default())) {} | |
17 | ||
18 | protected: | |
19 | std::unique_ptr<rocksdb::MockTimeEnv> mock_env_; | |
20 | }; | |
21 | ||
22 | TEST_F(RepeatableThreadTest, TimedTest) { | |
23 | constexpr uint64_t kSecond = 1000000; // 1s = 1000000us | |
24 | constexpr int kIteration = 3; | |
25 | rocksdb::Env* env = rocksdb::Env::Default(); | |
26 | rocksdb::port::Mutex mutex; | |
27 | rocksdb::port::CondVar test_cv(&mutex); | |
28 | int count = 0; | |
29 | uint64_t prev_time = env->NowMicros(); | |
30 | rocksdb::RepeatableThread thread( | |
31 | [&] { | |
32 | rocksdb::MutexLock l(&mutex); | |
33 | count++; | |
34 | uint64_t now = env->NowMicros(); | |
35 | assert(count == 1 || prev_time + 1 * kSecond <= now); | |
36 | prev_time = now; | |
37 | if (count >= kIteration) { | |
38 | test_cv.SignalAll(); | |
39 | } | |
40 | }, | |
41 | "rt_test", env, 1 * kSecond); | |
42 | // Wait for execution finish. | |
43 | { | |
44 | rocksdb::MutexLock l(&mutex); | |
45 | while (count < kIteration) { | |
46 | test_cv.Wait(); | |
47 | } | |
48 | } | |
49 | ||
50 | // Test cancel | |
51 | thread.cancel(); | |
52 | } | |
53 | ||
54 | TEST_F(RepeatableThreadTest, MockEnvTest) { | |
55 | constexpr uint64_t kSecond = 1000000; // 1s = 1000000us | |
56 | constexpr int kIteration = 3; | |
57 | mock_env_->set_current_time(0); // in seconds | |
58 | std::atomic<int> count{0}; | |
59 | rocksdb::RepeatableThread thread([&] { count++; }, "rt_test", mock_env_.get(), | |
60 | 1 * kSecond, 1 * kSecond); | |
61 | for (int i = 1; i <= kIteration; i++) { | |
62 | // Bump current time | |
63 | thread.TEST_WaitForRun([&] { mock_env_->set_current_time(i); }); | |
64 | } | |
65 | // Test function should be exectued exactly kIteraion times. | |
66 | ASSERT_EQ(kIteration, count.load()); | |
67 | ||
68 | // Test cancel | |
69 | thread.cancel(); | |
70 | } | |
71 | ||
72 | int main(int argc, char** argv) { | |
73 | ::testing::InitGoogleTest(&argc, argv); | |
74 | ||
75 | return RUN_ALL_TESTS(); | |
76 | } |