Java

Форк
0
185 строк · 6.3 Кб
1
/*
2
 * Copyright (C) 2008 The Guava 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 com.google.common.testing;
18

19
import com.google.common.annotations.GwtCompatible;
20
import com.google.common.annotations.GwtIncompatible;
21
import java.time.Duration;
22
import java.util.EnumSet;
23
import java.util.concurrent.Callable;
24
import java.util.concurrent.CountDownLatch;
25
import java.util.concurrent.ExecutorService;
26
import java.util.concurrent.Executors;
27
import java.util.concurrent.Future;
28
import java.util.concurrent.TimeUnit;
29
import junit.framework.TestCase;
30
import org.checkerframework.checker.nullness.qual.Nullable;
31

32
/**
33
 * Unit test for {@link FakeTicker}.
34
 *
35
 * @author Jige Yu
36
 */
37
@GwtCompatible(emulated = true)
38
public class FakeTickerTest extends TestCase {
39

40
  @GwtIncompatible // NullPointerTester
41
  public void testNullPointerExceptions() {
42
    NullPointerTester tester = new NullPointerTester();
43
    tester.testAllPublicInstanceMethods(new FakeTicker());
44
  }
45

46
  @GwtIncompatible // java.time.Duration
47
  @SuppressWarnings("Java7ApiChecker") // guava-android can rely on library desugaring now.
48
  public void testAdvance() {
49
    FakeTicker ticker = new FakeTicker();
50
    assertEquals(0, ticker.read());
51
    assertSame(ticker, ticker.advance(10));
52
    assertEquals(10, ticker.read());
53
    ticker.advance(1, TimeUnit.MILLISECONDS);
54
    assertEquals(1000010L, ticker.read());
55
    ticker.advance(Duration.ofMillis(1));
56
    assertEquals(2000010L, ticker.read());
57
  }
58

59
  public void testAutoIncrementStep_returnsSameInstance() {
60
    FakeTicker ticker = new FakeTicker();
61
    assertSame(ticker, ticker.setAutoIncrementStep(10, TimeUnit.NANOSECONDS));
62
  }
63

64
  public void testAutoIncrementStep_nanos() {
65
    FakeTicker ticker = new FakeTicker().setAutoIncrementStep(10, TimeUnit.NANOSECONDS);
66
    assertEquals(0, ticker.read());
67
    assertEquals(10, ticker.read());
68
    assertEquals(20, ticker.read());
69
  }
70

71
  public void testAutoIncrementStep_millis() {
72
    FakeTicker ticker = new FakeTicker().setAutoIncrementStep(1, TimeUnit.MILLISECONDS);
73
    assertEquals(0, ticker.read());
74
    assertEquals(1000000, ticker.read());
75
    assertEquals(2000000, ticker.read());
76
  }
77

78
  public void testAutoIncrementStep_seconds() {
79
    FakeTicker ticker = new FakeTicker().setAutoIncrementStep(3, TimeUnit.SECONDS);
80
    assertEquals(0, ticker.read());
81
    assertEquals(3000000000L, ticker.read());
82
    assertEquals(6000000000L, ticker.read());
83
  }
84

85
  @GwtIncompatible // java.time.Duration
86
  @SuppressWarnings("Java7ApiChecker") // guava-android can rely on library desugaring now.
87
  public void testAutoIncrementStep_duration() {
88
    FakeTicker ticker = new FakeTicker().setAutoIncrementStep(Duration.ofMillis(1));
89
    assertEquals(0, ticker.read());
90
    assertEquals(1000000, ticker.read());
91
    assertEquals(2000000, ticker.read());
92
  }
93

94
  public void testAutoIncrementStep_resetToZero() {
95
    FakeTicker ticker = new FakeTicker().setAutoIncrementStep(10, TimeUnit.NANOSECONDS);
96
    assertEquals(0, ticker.read());
97
    assertEquals(10, ticker.read());
98
    assertEquals(20, ticker.read());
99

100
    for (TimeUnit timeUnit : EnumSet.allOf(TimeUnit.class)) {
101
      ticker.setAutoIncrementStep(0, timeUnit);
102
      assertEquals(
103
          "Expected no auto-increment when setting autoIncrementStep to 0 " + timeUnit,
104
          30,
105
          ticker.read());
106
    }
107
  }
108

109
  public void testAutoIncrement_negative() {
110
    FakeTicker ticker = new FakeTicker();
111
    try {
112
      ticker.setAutoIncrementStep(-1, TimeUnit.NANOSECONDS);
113
      fail("Expected IllegalArgumentException");
114
    } catch (IllegalArgumentException expected) {
115
    }
116
  }
117

118
  @GwtIncompatible // concurrency
119

120
  public void testConcurrentAdvance() throws Exception {
121
    final FakeTicker ticker = new FakeTicker();
122

123
    int numberOfThreads = 64;
124
    runConcurrentTest(
125
        numberOfThreads,
126
        new Callable<@Nullable Void>() {
127
          @Override
128
          public @Nullable Void call() throws Exception {
129
            // adds two nanoseconds to the ticker
130
            ticker.advance(1L);
131
            Thread.sleep(10);
132
            ticker.advance(1L);
133
            return null;
134
          }
135
        });
136

137
    assertEquals(numberOfThreads * 2, ticker.read());
138
  }
139

140
  @GwtIncompatible // concurrency
141

142
  public void testConcurrentAutoIncrementStep() throws Exception {
143
    int incrementByNanos = 3;
144
    final FakeTicker ticker =
145
        new FakeTicker().setAutoIncrementStep(incrementByNanos, TimeUnit.NANOSECONDS);
146

147
    int numberOfThreads = 64;
148
    runConcurrentTest(
149
        numberOfThreads,
150
        new Callable<@Nullable Void>() {
151
          @Override
152
          public @Nullable Void call() throws Exception {
153
            long unused = ticker.read();
154
            return null;
155
          }
156
        });
157

158
    assertEquals(incrementByNanos * numberOfThreads, ticker.read());
159
  }
160

161
  /** Runs {@code callable} concurrently {@code numberOfThreads} times. */
162
  @GwtIncompatible // concurrency
163
  private void runConcurrentTest(int numberOfThreads, final Callable<@Nullable Void> callable)
164
      throws Exception {
165
    ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
166
    final CountDownLatch startLatch = new CountDownLatch(numberOfThreads);
167
    final CountDownLatch doneLatch = new CountDownLatch(numberOfThreads);
168
    for (int i = numberOfThreads; i > 0; i--) {
169
      @SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
170
      Future<?> possiblyIgnoredError =
171
          executorService.submit(
172
              new Callable<@Nullable Void>() {
173
                @Override
174
                public @Nullable Void call() throws Exception {
175
                  startLatch.countDown();
176
                  startLatch.await();
177
                  callable.call();
178
                  doneLatch.countDown();
179
                  return null;
180
                }
181
              });
182
    }
183
    doneLatch.await();
184
  }
185
}
186

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.