aboutsummaryrefslogtreecommitdiffstats
path: root/org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/time/MonotonicFakeClock.java
blob: e5338d36cd1c85df324b16bc1ec91b9ca65f7c40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Copyright (C) 2016, Google Inc. and others
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Distribution License v. 1.0 which is available at
 * https://www.eclipse.org/org/documents/edl-v10.php.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

package org.eclipse.jgit.junit.time;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import org.eclipse.jgit.util.time.MonotonicClock;
import org.eclipse.jgit.util.time.ProposedTimestamp;

/**
 * Fake {@link org.eclipse.jgit.util.time.MonotonicClock} for testing code that
 * uses Clock.
 *
 * @since 4.6
 */
public class MonotonicFakeClock implements MonotonicClock {
	private long now = TimeUnit.SECONDS.toMicros(42);

	/**
	 * Advance the time returned by future calls to {@link #propose()}.
	 *
	 * @param add
	 *            amount of time to add; must be {@code > 0}.
	 * @param unit
	 *            unit of {@code add}.
	 */
	public void tick(long add, TimeUnit unit) {
		if (add <= 0) {
			throw new IllegalArgumentException();
		}
		now += unit.toMillis(add);
	}

	/** {@inheritDoc} */
	@Override
	public ProposedTimestamp propose() {
		long t = now++;
		return new ProposedTimestamp() {
			@Override
			public long read(TimeUnit unit) {
				return unit.convert(t, TimeUnit.MILLISECONDS);
			}

			@Override
			public void blockUntil(Duration maxWait) {
				// Nothing to do, since fake time does not go backwards.
			}
		};
	}
}