1 /* 2 * Copyright 2017, OpenCensus Authors 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 io.opencensus.testing.common; 18 19 import static com.google.common.truth.Truth.assertThat; 20 21 import io.opencensus.common.Duration; 22 import io.opencensus.common.Timestamp; 23 import org.junit.Test; 24 import org.junit.runner.RunWith; 25 import org.junit.runners.JUnit4; 26 27 /** Tests for {@link TestClock}. */ 28 @RunWith(JUnit4.class) 29 public final class TestClockTest { 30 private static final int NUM_NANOS_PER_SECOND = 1000 * 1000 * 1000; 31 32 @Test setAndGetTime()33 public void setAndGetTime() { 34 TestClock clock = TestClock.create(Timestamp.create(1, 2)); 35 assertThat(clock.now()).isEqualTo(Timestamp.create(1, 2)); 36 clock.setTime(Timestamp.create(3, 4)); 37 assertThat(clock.now()).isEqualTo(Timestamp.create(3, 4)); 38 } 39 40 @Test advanceTime()41 public void advanceTime() { 42 TestClock clock = TestClock.create(Timestamp.create(1, 500 * 1000 * 1000)); 43 clock.advanceTime(Duration.create(2, 600 * 1000 * 1000)); 44 assertThat(clock.now()).isEqualTo(Timestamp.create(4, 100 * 1000 * 1000)); 45 } 46 47 @Test measureElapsedTime()48 public void measureElapsedTime() { 49 TestClock clock = TestClock.create(Timestamp.create(10, 1)); 50 long nanos1 = clock.nowNanos(); 51 clock.setTime(Timestamp.create(11, 5)); 52 long nanos2 = clock.nowNanos(); 53 assertThat(nanos2 - nanos1).isEqualTo(1000 * 1000 * 1000 + 4); 54 } 55 56 @Test(expected = ArithmeticException.class) catchOverflow()57 public void catchOverflow() { 58 TestClock.create(Timestamp.create(Long.MAX_VALUE / NUM_NANOS_PER_SECOND + 1, 0)); 59 } 60 61 @Test(expected = ArithmeticException.class) catchNegativeOverflow()62 public void catchNegativeOverflow() { 63 TestClock.create(Timestamp.create(Long.MIN_VALUE / NUM_NANOS_PER_SECOND - 1, 0)); 64 } 65 } 66