scoped_mock_clock_override.h 1.8 KB

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