View Javadoc
1   /*
2    * Copyright (C) 2016, Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.junit.time;
12  
13  import java.time.Duration;
14  import java.util.concurrent.TimeUnit;
15  
16  import org.eclipse.jgit.util.time.MonotonicClock;
17  import org.eclipse.jgit.util.time.ProposedTimestamp;
18  
19  /**
20   * Fake {@link org.eclipse.jgit.util.time.MonotonicClock} for testing code that
21   * uses Clock.
22   *
23   * @since 4.6
24   */
25  public class MonotonicFakeClock implements MonotonicClock {
26  	private long now = TimeUnit.SECONDS.toMicros(42);
27  
28  	/**
29  	 * Advance the time returned by future calls to {@link #propose()}.
30  	 *
31  	 * @param add
32  	 *            amount of time to add; must be {@code > 0}.
33  	 * @param unit
34  	 *            unit of {@code add}.
35  	 */
36  	public void tick(long add, TimeUnit unit) {
37  		if (add <= 0) {
38  			throw new IllegalArgumentException();
39  		}
40  		now += unit.toMillis(add);
41  	}
42  
43  	/** {@inheritDoc} */
44  	@Override
45  	public ProposedTimestamp propose() {
46  		long t = now++;
47  		return new ProposedTimestamp() {
48  			@Override
49  			public long read(TimeUnit unit) {
50  				return unit.convert(t, TimeUnit.MILLISECONDS);
51  			}
52  
53  			@Override
54  			public void blockUntil(Duration maxWait) {
55  				// Nothing to do, since fake time does not go backwards.
56  			}
57  		};
58  	}
59  }