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