Add backoff to reconnects.
[xudocci.git] / src / test / java / net / pterodactylus / xdcc / core / ConnectionBackoffTest.java
diff --git a/src/test/java/net/pterodactylus/xdcc/core/ConnectionBackoffTest.java b/src/test/java/net/pterodactylus/xdcc/core/ConnectionBackoffTest.java
new file mode 100644 (file)
index 0000000..adaae8b
--- /dev/null
@@ -0,0 +1,61 @@
+package net.pterodactylus.xdcc.core;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneId;
+
+import net.pterodactylus.xdcc.data.Network;
+
+import org.hamcrest.MatcherAssert;
+import org.hamcrest.Matchers;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+/**
+ * Unit test for {@link ConnectionBackoff}.
+ */
+public class ConnectionBackoffTest {
+
+       private final Network network = Mockito.mock(Network.class);
+       private final Clock fixedClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
+       private final ConnectionBackoff connectionBackoff = new ConnectionBackoff(fixedClock);
+
+       @Test
+       public void defaultBackoffCanBeCreated() {
+               new ConnectionBackoff();
+       }
+
+       @Test
+       public void firstConnectionIsImmediatelyPossible() {
+               MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(0L));
+       }
+
+       @Test
+       public void afterTheFirstFailedConnectionBackoffIsOneMinute() {
+               connectionBackoff.connectionFailed(network);
+               MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(60000L));
+       }
+
+       @Test
+       public void secondFailureIncreasesBackoffTo72Seconds() {
+               connectionBackoff.connectionFailed(network);
+               connectionBackoff.connectionFailed(network);
+               MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(72000L));
+       }
+
+       @Test
+       public void successfulConnectionResetsTheTimer() {
+               connectionBackoff.connectionFailed(network);
+               connectionBackoff.connectionSuccessful(network);
+               MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(0L));
+       }
+
+       @Test
+       public void backoffIsCappedToOneHour() {
+               for (int i = 0; i < 45; i++) {
+                       connectionBackoff.connectionFailed(network);
+               }
+               MatcherAssert.assertThat(connectionBackoff.getBackoff(network), Matchers.is(3600000L));
+       }
+
+}