View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.io.input;
19  
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  
22  import java.io.IOException;
23  import java.time.Duration;
24  
25  import org.junit.jupiter.api.Test;
26  
27  /**
28   * Tests {@link ThrottledInputStream}.
29   */
30  public class ThrottledInputStreamTest extends ProxyInputStreamTest<ThrottledInputStream> {
31  
32      @Override
33      @SuppressWarnings("resource")
34      protected ThrottledInputStream createFixture() throws IOException {
35          return ThrottledInputStream.builder().setInputStream(createProxySource()).get();
36      }
37  
38      @Test
39      public void testCalSleepTimeMs() {
40          // case 0: initial - no read, no sleep
41          assertEquals(0, ThrottledInputStream.toSleepMillis(0, 10_000, 1_000));
42  
43          // case 1: no threshold
44          assertEquals(0, ThrottledInputStream.toSleepMillis(Long.MAX_VALUE, 0, 1_000));
45          assertEquals(0, ThrottledInputStream.toSleepMillis(Long.MAX_VALUE, -1, 1_000));
46  
47          // case 2: too fast
48          assertEquals(1500, ThrottledInputStream.toSleepMillis(5, 2, 1_000));
49          assertEquals(500, ThrottledInputStream.toSleepMillis(5, 2, 2_000));
50          assertEquals(6500, ThrottledInputStream.toSleepMillis(15, 2, 1_000));
51  
52          // case 3: too slow
53          assertEquals(0, ThrottledInputStream.toSleepMillis(1, 2, 1_000));
54          assertEquals(0, ThrottledInputStream.toSleepMillis(2, 2, 2_000));
55          assertEquals(0, ThrottledInputStream.toSleepMillis(1, 2, 1_000));
56      }
57  
58      @Override
59      protected void testEos(final ThrottledInputStream inputStream) {
60          assertEquals(3, inputStream.getByteCount());
61      }
62  
63      @Test
64      public void testGet() throws IOException {
65          try (ThrottledInputStream inputStream = createFixture()) {
66              inputStream.read();
67              assertEquals(Duration.ZERO, inputStream.getTotalSleepDuration());
68          }
69      }
70  
71  }