1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.testutils;
18 
19 import android.os.SystemClock;
20 
21 import java.util.function.LongSupplier;
22 
23 /**
24  * A time supplier (in the format of a {@code long} as the amount of milliseconds) similar
25  * to {@link SystemClock#uptimeMillis()}, but with the ability to {@link #fastForward}
26  * and {@link #rewind}
27  *
28  * Implements {@link LongSupplier} to be interchangeable with {@code SystemClock::uptimeMillis}
29  *
30  * Can be provided to {@link TestHandler} to "mock time" for the delayed execution testing
31  *
32  * @see OffsettableClock.Stopped for a version of this clock that does not advance on its own
33  */
34 public class OffsettableClock implements LongSupplier {
35     private long mOffset = 0L;
36 
37     /**
38      * @return Current time in milliseconds, according to this clock
39      */
now()40     public long now() {
41         return realNow() + mOffset;
42     }
43 
44     /**
45      * Can be overriden with a constant for a clock that stands still, and is only ever moved
46      * manually
47      */
realNow()48     public long realNow() {
49         return SystemClock.uptimeMillis();
50     }
51 
fastForward(long timeMs)52     public void fastForward(long timeMs) {
53         mOffset += timeMs;
54     }
rewind(long timeMs)55     public void rewind(long timeMs) {
56         fastForward(-timeMs);
57     }
reset()58     public void reset() {
59         mOffset = 0;
60     }
61 
62     /** @deprecated Only present for {@link LongSupplier} contract */
63     @Override
64     @Deprecated
getAsLong()65     public long getAsLong() {
66         return now();
67     }
68 
69     /**
70      * An {@link OffsettableClock} that does not advance with real time, and can only be
71      * advanced manually via {@link #fastForward}
72      */
73     public static class Stopped extends OffsettableClock {
74         @Override
realNow()75         public long realNow() {
76             return 0L;
77         }
78     }
79 }
80