scoped_mock_clock_override.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_TEST_SCOPED_MOCK_CLOCK_OVERRIDE_H_
  5. #define BASE_TEST_SCOPED_MOCK_CLOCK_OVERRIDE_H_
  6. #include <memory>
  7. #include "base/time/time.h"
  8. #include "base/time/time_override.h"
  9. namespace base {
  10. // Override the return value of Time::Now(), Time::NowFromSystemTime(),
  11. // TimeTicks::Now(), and ThreadTicks::Now() through a simple advanceable clock.
  12. //
  13. // This utility is intended to support tests that:
  14. //
  15. // - Depend on large existing codebases that call TimeXYZ::Now() directly or
  16. // - Have no ability to inject a TickClock into the code getting the time
  17. // (e.g. integration tests in which a TickClock would be several layers
  18. // removed from the test code)
  19. //
  20. // For new unit tests, developers are highly encouraged to structure new code
  21. // around a dependency injected base::Clock, base::TickClock, etc. to be able
  22. // to supply a mock time in tests without a global override.
  23. //
  24. // NOTE: ScopedMockClockOverride should be created while single-threaded and
  25. // before the first call to Now() to avoid threading issues and inconsistencies
  26. // in returned values. Nested overrides are not allowed.
  27. class ScopedMockClockOverride {
  28. public:
  29. ScopedMockClockOverride();
  30. ScopedMockClockOverride(const ScopedMockClockOverride&) = delete;
  31. ScopedMockClockOverride& operator=(const ScopedMockClockOverride&) = delete;
  32. ~ScopedMockClockOverride();
  33. static Time Now();
  34. static TimeTicks NowTicks();
  35. static ThreadTicks NowThreadTicks();
  36. void Advance(TimeDelta delta);
  37. private:
  38. std::unique_ptr<base::subtle::ScopedTimeClockOverrides> time_clock_overrides_;
  39. TimeDelta offset_;
  40. static ScopedMockClockOverride* scoped_mock_clock_;
  41. };
  42. } // namespace base
  43. #endif // BASE_TEST_SCOPED_MOCK_CLOCK_OVERRIDE_H_