1 package net.pterodactylus.xdcc.core;
3 import java.time.Clock;
4 import java.time.Instant;
5 import java.time.ZoneId;
7 import net.pterodactylus.xdcc.data.Network;
9 import org.hamcrest.MatcherAssert;
10 import org.hamcrest.Matchers;
11 import org.junit.Test;
12 import org.mockito.Mockito;
15 * Unit test for {@link ConnectionBackoff}.
17 public class ConnectionBackoffTest {
19 private final Network network = Mockito.mock(Network.class);
20 private final Instant now = Instant.now();
21 private final Clock fixedClock = Clock.fixed(now, ZoneId.systemDefault());
22 private final ConnectionBackoff connectionBackoff = new ConnectionBackoff(fixedClock);
25 public void defaultBackoffCanBeCreated() {
26 new ConnectionBackoff();
30 public void firstConnectionIsImmediatelyPossible() {
31 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(0L));
32 MatcherAssert.assertThat(connectionBackoff.getConnectionTime(network), Matchers.is(now.toEpochMilli()));
36 public void afterTheFirstFailedConnectionBackoffIsOneMinute() {
37 connectionBackoff.connectionFailed(network);
38 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(60000L));
39 MatcherAssert.assertThat(connectionBackoff.getConnectionTime(network), Matchers.is(now.toEpochMilli() + 60000));
43 public void secondFailureIncreasesBackoffTo72Seconds() {
44 connectionBackoff.connectionFailed(network);
45 connectionBackoff.connectionFailed(network);
46 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(72000L));
47 MatcherAssert.assertThat(connectionBackoff.getConnectionTime(network), Matchers.is(now.toEpochMilli() + 72000));
51 public void successfulConnectionResetsTheTimer() {
52 connectionBackoff.connectionFailed(network);
53 connectionBackoff.connectionSuccessful(network);
54 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(0L));
55 MatcherAssert.assertThat(connectionBackoff.getConnectionTime(network), Matchers.is(now.toEpochMilli()));
59 public void backoffIsCappedToOneHour() {
60 for (int i = 0; i < 45; i++) {
61 connectionBackoff.connectionFailed(network);
63 MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(3600000L));
64 MatcherAssert.assertThat(connectionBackoff.getConnectionTime(network), Matchers.is(now.toEpochMilli() + 3600000));