1 // Copyright (C) 2019 Google LLC 2 // 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 #ifndef ICING_TESTING_FAKE_CLOCK_H_ 16 #define ICING_TESTING_FAKE_CLOCK_H_ 17 18 #include "icing/util/clock.h" 19 20 namespace icing { 21 namespace lib { 22 23 // A fake timer class for tests. It makes sure that the elapsed time changes 24 // every time it's requested. 25 class FakeTimer : public Timer { 26 public: GetElapsedMilliseconds()27 int64_t GetElapsedMilliseconds() const override { 28 return fake_elapsed_milliseconds_; 29 } 30 SetElapsedMilliseconds(int64_t elapsed_milliseconds)31 void SetElapsedMilliseconds(int64_t elapsed_milliseconds) { 32 fake_elapsed_milliseconds_ = elapsed_milliseconds; 33 } 34 35 private: 36 int64_t fake_elapsed_milliseconds_ = 0; 37 }; 38 39 // Wrapper around real-time clock functions. This is separated primarily so 40 // tests can override this clock and inject it into the class under test. 41 class FakeClock : public Clock { 42 public: GetSystemTimeMilliseconds()43 int64_t GetSystemTimeMilliseconds() const override { return milliseconds_; } 44 SetSystemTimeMilliseconds(int64_t milliseconds)45 void SetSystemTimeMilliseconds(int64_t milliseconds) { 46 milliseconds_ = milliseconds; 47 } 48 GetNewTimer()49 std::unique_ptr<Timer> GetNewTimer() const override { 50 return std::make_unique<FakeTimer>(fake_timer_); 51 } 52 SetTimerElapsedMilliseconds(int64_t timer_elapsed_milliseconds)53 void SetTimerElapsedMilliseconds(int64_t timer_elapsed_milliseconds) { 54 fake_timer_.SetElapsedMilliseconds(timer_elapsed_milliseconds); 55 } 56 57 private: 58 int64_t milliseconds_ = 0; 59 FakeTimer fake_timer_; 60 }; 61 62 } // namespace lib 63 } // namespace icing 64 65 #endif // ICING_TESTING_FAKE_CLOCK_H_ 66