Add backoff to reconnects.
[xudocci.git] / src / test / java / net / pterodactylus / xdcc / core / ConnectionBackoffTest.java
1 package net.pterodactylus.xdcc.core;
2
3 import java.time.Clock;
4 import java.time.Instant;
5 import java.time.ZoneId;
6
7 import net.pterodactylus.xdcc.data.Network;
8
9 import org.hamcrest.MatcherAssert;
10 import org.hamcrest.Matchers;
11 import org.junit.Test;
12 import org.mockito.Mockito;
13
14 /**
15  * Unit test for {@link ConnectionBackoff}.
16  */
17 public class ConnectionBackoffTest {
18
19         private final Network network = Mockito.mock(Network.class);
20         private final Clock fixedClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
21         private final ConnectionBackoff connectionBackoff = new ConnectionBackoff(fixedClock);
22
23         @Test
24         public void defaultBackoffCanBeCreated() {
25                 new ConnectionBackoff();
26         }
27
28         @Test
29         public void firstConnectionIsImmediatelyPossible() {
30                 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(0L));
31         }
32
33         @Test
34         public void afterTheFirstFailedConnectionBackoffIsOneMinute() {
35                 connectionBackoff.connectionFailed(network);
36                 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(60000L));
37         }
38
39         @Test
40         public void secondFailureIncreasesBackoffTo72Seconds() {
41                 connectionBackoff.connectionFailed(network);
42                 connectionBackoff.connectionFailed(network);
43                 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(72000L));
44         }
45
46         @Test
47         public void successfulConnectionResetsTheTimer() {
48                 connectionBackoff.connectionFailed(network);
49                 connectionBackoff.connectionSuccessful(network);
50                 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(0L));
51         }
52
53         @Test
54         public void backoffIsCappedToOneHour() {
55                 for (int i = 0; i < 45; i++) {
56                         connectionBackoff.connectionFailed(network);
57                 }
58                 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(3600000L));
59         }
60
61 }