Improve test coverage

This commit is contained in:
anthonyraymond 2018-02-24 01:52:28 +01:00
parent ee2ac8c2b6
commit f63664a146
30 changed files with 574 additions and 65 deletions

View file

@ -23,9 +23,7 @@ import java.io.IOException;
public class CoreEventListener {
private static final Logger logger = LoggerFactory.getLogger(CoreEventListener.class);
@Inject
public CoreEventListener() {
}

View file

@ -1,5 +1,6 @@
package org.araymond.joal.core.bandwith;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.io.FileUtils;
@ -147,7 +148,8 @@ public class BandwidthDispatcher implements BandwidthDispatcherFacade, Runnable
}
}
private void refreshCurrentBandwidth() {
@VisibleForTesting
void refreshCurrentBandwidth() {
if (logger.isDebugEnabled()) {
logger.debug("Refreshing global bandwidth");
}
@ -163,7 +165,8 @@ public class BandwidthDispatcher implements BandwidthDispatcherFacade, Runnable
}
}
private void recomputeSpeeds() {
@VisibleForTesting
void recomputeSpeeds() {
if (logger.isDebugEnabled()) {
logger.debug("Refreshing all torrents speeds");
}
@ -183,25 +186,29 @@ public class BandwidthDispatcher implements BandwidthDispatcherFacade, Runnable
if (speedChangedListener != null) {
this.speedChangedListener.speedsHasChanged(Maps.newHashMap(this.speedMap));
}
if (logger.isDebugEnabled()) {
final StringBuilder sb = new StringBuilder("All torrents speeds has been refreshed:\n");
final double totalWeight = this.weightHolder.getTotalWeight();
this.speedMap.forEach((infoHash, speed) -> {
final String humanReadableSpeed = FileUtils.byteCountToDisplaySize(speed.getBytesPerSeconds());
final double torrentWeight = this.weightHolder.getWeightFor(infoHash);
final double weightInPercent = torrentWeight > 0.0
? totalWeight / torrentWeight * 100
: 0;
sb.append(" ")
.append(infoHash.humanReadableValue())
.append(":")
.append("\n ").append("current speed: ").append(humanReadableSpeed).append("/s")
.append("\n ").append("overall upload: ").append(FileUtils.byteCountToDisplaySize(this.torrentsSeedStats.get(infoHash).getUploaded()))
.append("\n ").append("weight: ").append(weightInPercent).append("% (").append(torrentWeight).append(" out of ").append(totalWeight).append(")")
.append("\n");
});
sb.setLength(sb.length() - 1); // remove last \n
logger.debug(sb.toString());
try {
if (logger.isDebugEnabled()) {
final StringBuilder sb = new StringBuilder("All torrents speeds has been refreshed:\n");
final double totalWeight = this.weightHolder.getTotalWeight();
this.speedMap.forEach((infoHash, speed) -> {
final String humanReadableSpeed = FileUtils.byteCountToDisplaySize(speed.getBytesPerSeconds());
final double torrentWeight = this.weightHolder.getWeightFor(infoHash);
final double weightInPercent = torrentWeight > 0.0
? totalWeight / torrentWeight * 100
: 0;
sb.append(" ")
.append(infoHash.humanReadableValue())
.append(":")
.append("\n ").append("current speed: ").append(humanReadableSpeed).append("/s")
.append("\n ").append("overall upload: ").append(FileUtils.byteCountToDisplaySize(this.torrentsSeedStats.get(infoHash).getUploaded()))
.append("\n ").append("weight: ").append(weightInPercent).append("% (").append(torrentWeight).append(" out of ").append(totalWeight).append(")")
.append("\n");
});
sb.setLength(sb.length() - 1); // remove last \n
logger.debug(sb.toString());
}
} catch (final Exception e) {
logger.debug("Error while printing debug message for speed.", e);
}
}

View file

@ -47,7 +47,11 @@ public abstract class PeerIdGenerator {
public abstract String getPeerId(final InfoHash infoHash, RequestEvent event);
protected String generatePeerId() {
return this.algorithm.generate();
final String peerId = this.algorithm.generate();
if (peerId.length() != PEER_ID_LENGTH) {
throw new IllegalStateException("PeerId length was supposed to be 20. But a PeerId of " + peerId.length() + " was generated. Throw exception to prevent sending invalid PeerId to tracker.");
}
return peerId;
}
@Override

View file

@ -1,6 +1,7 @@
package org.araymond.joal.core.client.emulated.generator.peerid.generation;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import org.apache.commons.lang3.StringUtils;
import org.araymond.joal.core.client.emulated.TorrentClientConfigIntegrityException;
@ -57,7 +58,8 @@ public class RandomPoolWithChecksumPeerIdAlgorithm implements PeerIdAlgorithm {
return base;
}
private byte[] createSecureRandomSeed() {
@VisibleForTesting
byte[] createSecureRandomSeed() {
return Instant.now().toString().getBytes();
}
@ -68,8 +70,8 @@ public class RandomPoolWithChecksumPeerIdAlgorithm implements PeerIdAlgorithm {
return (randNumber + 10);
}
@Override
public String generate() {
@VisibleForTesting
byte[] generateRandomBytes(final int length) {
// This test is subject to multi-thread issues, but in this case it's actually a good news
if (this.generationCount >= this.refreshSeedAfter) {
// Times to times we reset the seed to enforce randomness
@ -80,21 +82,26 @@ public class RandomPoolWithChecksumPeerIdAlgorithm implements PeerIdAlgorithm {
this.generationCount += 1;
final byte[] bytes = new byte[length];
this.random.nextBytes(bytes);
return bytes;
}
@Override
public String generate() {
final int suffixLength = PeerIdGenerator.PEER_ID_LENGTH - this.prefix.length();
final byte[] randomBytes = new byte[suffixLength - 1];
final byte[] randomBytes = this.generateRandomBytes(suffixLength - 1);
final char[] buf = new char[suffixLength];
int val, total = 0;
this.random.nextBytes(randomBytes);
for (int i = 0; i < 11; ++i)
{
val = (randomBytes[i] + 128) % this.base;
for (int i = 0; i < suffixLength - 1; ++i) {
val = randomBytes[i] < 0 ? randomBytes[i] + 256 : randomBytes[i];
val %= base;
total += val;
buf[i] = this.charactersPool.charAt(val);
}
val = (total % this.base) != 0 ? this.base - (total % this.base) : 0;
buf[11] = this.charactersPool.charAt(val);
buf[suffixLength - 1] = this.charactersPool.charAt(val);
return this.prefix + new String(buf);
}

View file

@ -10,7 +10,4 @@ public class UnrecognizedAnnounceParameter extends RuntimeException {
super(message);
}
public UnrecognizedAnnounceParameter(final String message, final Throwable cause) {
super(message, cause);
}
}

View file

@ -7,11 +7,9 @@ import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.net.*;
import java.nio.channels.ServerSocketChannel;
import java.util.Collections;
import java.util.List;
@ -39,7 +37,6 @@ public class ConnectionHandler {
"https://tnx.nl/ip"
};
public ConnectionHandler() {
}
@ -78,11 +75,16 @@ public class ConnectionHandler {
for (final String ipProvider : shuffledList) {
final String ip;
logger.info("Fetching ip from: " + ipProvider);
final URLConnection urlConnection;
try {
logger.info("Fetching ip from: " + ipProvider);
final URL url = new URL(ipProvider);
final BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
urlConnection = new URL(ipProvider).openConnection();
urlConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36");
} catch (final IOException e) {
logger.warn("Failed to fetch Ip from \"" + ipProvider + "\"", e);
return Optional.empty();
}
try (final BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))){
ip = in.readLine();
return Optional.of(InetAddress.getByName(ip));

View file

@ -74,7 +74,7 @@ public class Announcer implements AnnouncerFacade {
this.consecutiveFails = 0;
return responseMessage;
} catch (final AnnounceException e) {
} catch (final Exception e) {
if (logger.isWarnEnabled()) {
logger.warn("{} has failed to announce", this.torrent.getTorrentInfoHash().humanReadableValue(), e);
}

View file

@ -6,6 +6,7 @@ import org.mockito.Matchers;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
@ -14,9 +15,26 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
public class BandwidthDispatcherTest {
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void shouldRefreshRandomSpeedProviderAndRecomputeSpeed() {
final RandomSpeedProvider speedProvider = Mockito.mock(RandomSpeedProvider.class);
Mockito.doReturn(1000000L).when(speedProvider).getInBytesPerSeconds();
final BandwidthDispatcher bandwidthDispatcher = spy(new BandwidthDispatcher(2, speedProvider));
bandwidthDispatcher.refreshCurrentBandwidth();
Mockito.verify(speedProvider, Mockito.times(1)).refresh();
Mockito.verify(bandwidthDispatcher, times(1)).recomputeSpeeds();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void shouldReturnZeroIfInfoHashIsNotRegistered() throws InterruptedException {
final RandomSpeedProvider speedProvider = Mockito.mock(RandomSpeedProvider.class);
@ -34,6 +52,7 @@ public class BandwidthDispatcherTest {
assertThat(seedStats.getLeft()).isEqualTo(0);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void shouldNotIncrementRegisteredTorrentsBeforePeersHaveBeenAdded() throws InterruptedException {
final RandomSpeedProvider speedProvider = Mockito.mock(RandomSpeedProvider.class);
@ -54,6 +73,7 @@ public class BandwidthDispatcherTest {
assertThat(seedStats.getLeft()).isEqualTo(0);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void shouldNotIncrementRegisteredTorrentsWithZeroSeeders() throws InterruptedException {
final RandomSpeedProvider speedProvider = Mockito.mock(RandomSpeedProvider.class);
@ -75,6 +95,7 @@ public class BandwidthDispatcherTest {
assertThat(seedStats.getLeft()).isEqualTo(0);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void shouldNotIncrementRegisteredTorrentsWithZeroLeechers() throws InterruptedException {
final RandomSpeedProvider speedProvider = Mockito.mock(RandomSpeedProvider.class);
@ -96,6 +117,7 @@ public class BandwidthDispatcherTest {
assertThat(seedStats.getLeft()).isEqualTo(0);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void shouldRemoveUnregisteredTorrent() throws InterruptedException {
final RandomSpeedProvider speedProvider = Mockito.mock(RandomSpeedProvider.class);
@ -119,6 +141,7 @@ public class BandwidthDispatcherTest {
bandwidthDispatcher.stop();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void shouldIncrementRegisteredTorrent() throws InterruptedException {
final RandomSpeedProvider speedProvider = Mockito.mock(RandomSpeedProvider.class);
@ -143,6 +166,7 @@ public class BandwidthDispatcherTest {
assertThat(seedStats2.getUploaded()).isGreaterThan(1);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void shouldBeSafeToUpdateTorrentSeedsStatsWhileRegisteringTorrents() throws ExecutionException, InterruptedException {
final RandomSpeedProvider speedProvider = Mockito.mock(RandomSpeedProvider.class);
@ -153,7 +177,7 @@ public class BandwidthDispatcherTest {
bandwidthDispatcher.start();
final ExecutorService executorService = Executors.newFixedThreadPool(5);
final List<Future<?>> futures = new ArrayList<>();
final Collection<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < 100; ++i) {
final InfoHash infoHash = new InfoHash((i + "").getBytes());
futures.add(executorService.submit(() -> {
@ -180,6 +204,7 @@ public class BandwidthDispatcherTest {
bandwidthDispatcher.stop();
}
@SuppressWarnings({"ResultOfMethodCallIgnored", "unchecked"})
@Test
public void shouldNotifyThatSpeedHasChangedAfterRegisteringTorrent() throws InterruptedException {
final RandomSpeedProvider speedProvider = Mockito.mock(RandomSpeedProvider.class);
@ -188,7 +213,7 @@ public class BandwidthDispatcherTest {
final BandwidthDispatcher bandwidthDispatcher = new BandwidthDispatcher(2, speedProvider);
bandwidthDispatcher.start();
final SpeedChangedListener speedListener = Mockito.spy(new VoidSpeedChangedListener());
final SpeedChangedListener speedListener = spy(new VoidSpeedChangedListener());
bandwidthDispatcher.setSpeedListener(speedListener);
final InfoHash infoHash = new InfoHash(new byte[]{12});

View file

@ -16,7 +16,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class BitTorrentClientConfigSerializationTest {
private static final ObjectMapper mapper = new ObjectMapper();
private static final String validJSON = "{\"peerIdGenerator\":{\"refreshOn\":\"NEVER\",\"algorithm\": { \"type\": \"REGEX\", \"pattern\": \"-AZ5750-[a-zA-Z0-9]\" }, \"shouldUrlEncode\": false},\"urlEncoder\":{\"encodingExclusionPattern\":\"[a-z]\",\"encodedHexCase\":\"lower\"},\"numwant\":200,\"numwantOnStop\":0,\"query\":\"info_hash={infohash}&peer_id={peerid}&supportcrypto=1&port={port}&azudp={port}&uploaded={uploaded}&downloaded={downloaded}&left={left}&corrupt=0&event={event}&numwant={numwant}&no_peer_id=1&compact=1&key={key}&azver=3\",\"keyGenerator\":{\"refreshOn\":\"NEVER\",\"algorithm\": { \"type\": \"HASH\", \"length\": 8 },\"keyCase\":\"lower\"},\"requestHeaders\":[{\"name\":\"User-Agent\",\"value\":\"Azureus 5.7.5.0;{os};1.8.0_66\"},{\"name\":\"Connection\",\"value\":\"close\"},{\"name\":\"Accept-Encoding\",\"value\":\"gzip\"},{\"name\":\"Accept\",\"value\":\"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\"}]}";
private static final String validJSON = "{\"peerIdGenerator\":{\"refreshOn\":\"NEVER\",\"algorithm\": { \"type\": \"REGEX\", \"pattern\": \"-AZ5750-[a-zA-Z0-9]{12}\" }, \"shouldUrlEncode\": false},\"urlEncoder\":{\"encodingExclusionPattern\":\"[a-z]\",\"encodedHexCase\":\"lower\"},\"numwant\":200,\"numwantOnStop\":0,\"query\":\"info_hash={infohash}&peer_id={peerid}&supportcrypto=1&port={port}&azudp={port}&uploaded={uploaded}&downloaded={downloaded}&left={left}&corrupt=0&event={event}&numwant={numwant}&no_peer_id=1&compact=1&key={key}&azver=3\",\"keyGenerator\":{\"refreshOn\":\"NEVER\",\"algorithm\": { \"type\": \"HASH\", \"length\": 8 },\"keyCase\":\"lower\"},\"requestHeaders\":[{\"name\":\"User-Agent\",\"value\":\"Azureus 5.7.5.0;{os};1.8.0_66\"},{\"name\":\"Connection\",\"value\":\"close\"},{\"name\":\"Accept-Encoding\",\"value\":\"gzip\"},{\"name\":\"Accept\",\"value\":\"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\"}]}";
@Test
public void shouldFailToDeserializeIfPeerIdInfoIsNotDefined() throws IOException {

View file

@ -0,0 +1,49 @@
package org.araymond.joal.core.client.emulated.generator.key.algorithm;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class HashKeyAlgorithmTest {
@Test
public void shouldGenerateValidHash() {
final HashKeyAlgorithm algo = new HashKeyAlgorithm(8);
assertThat(algo.generate()).matches("[0-9A-F]{8}");
assertThat(algo.generate()).matches("[0-9A-F]{8}");
assertThat(algo.generate()).matches("[0-9A-F]{8}");
assertThat(algo.generate()).matches("[0-9A-F]{8}");
assertThat(algo.generate()).matches("[0-9A-F]{8}");
}
@Test
public void shouldBuild() {
final HashKeyAlgorithm algo = new HashKeyAlgorithm(8);
assertThat(algo.getLength()).isEqualTo(8);
}
@Test
public void shouldBeEqualByLength() {
final HashKeyAlgorithm algo1 = new HashKeyAlgorithm(8);
final HashKeyAlgorithm algo2 = new HashKeyAlgorithm(8);
final HashKeyAlgorithm algo3 = new HashKeyAlgorithm(6);
assertThat(algo1)
.isEqualTo(algo2)
.isNotEqualTo(algo3);
}
@Test
public void shouldHaveSameHashCodeByLength() {
final HashKeyAlgorithm algo1 = new HashKeyAlgorithm(8);
final HashKeyAlgorithm algo2 = new HashKeyAlgorithm(8);
final HashKeyAlgorithm algo3 = new HashKeyAlgorithm(6);
assertThat(algo1.hashCode())
.isEqualTo(algo2.hashCode())
.isNotEqualTo(algo3.hashCode());
}
}

View file

@ -0,0 +1,69 @@
package org.araymond.joal.core.client.emulated.generator.key.algorithm;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class HashNoLeadingZeroKeyAlgorithmTest {
@Test
public void shouldGenerateValidHash() {
final HashNoLeadingZeroKeyAlgorithm algo = new HashNoLeadingZeroKeyAlgorithm(8);
assertThat(algo.generate()).matches("^[0-9A-F]*$");
assertThat(algo.generate()).matches("^[0-9A-F]*$");
assertThat(algo.generate()).matches("^[0-9A-F]*$");
assertThat(algo.generate()).matches("^[0-9A-F]*$");
assertThat(algo.generate()).matches("^[0-9A-F]*$");
}
@Test
public void shouldCallRemoveTrailingZero() {
final HashNoLeadingZeroKeyAlgorithm algo = Mockito.spy(new HashNoLeadingZeroKeyAlgorithm(8));
algo.generate();
Mockito.verify(algo, Mockito.times(1)).removeLeadingZeroes(Matchers.anyString());
}
@Test
public void shouldRemoveTrailingZeros() {
final HashNoLeadingZeroKeyAlgorithm algo = new HashNoLeadingZeroKeyAlgorithm(8);
assertThat(algo.removeLeadingZeroes("00AF32020")).isEqualTo("AF32020");
}
@Test
public void shouldBuild() {
final HashNoLeadingZeroKeyAlgorithm algo = new HashNoLeadingZeroKeyAlgorithm(8);
assertThat(algo.getLength()).isEqualTo(8);
}
@Test
public void shouldBeEqualByLength() {
final HashNoLeadingZeroKeyAlgorithm algo1 = new HashNoLeadingZeroKeyAlgorithm(8);
final HashNoLeadingZeroKeyAlgorithm algo2 = new HashNoLeadingZeroKeyAlgorithm(8);
final HashNoLeadingZeroKeyAlgorithm algo3 = new HashNoLeadingZeroKeyAlgorithm(6);
assertThat(algo1)
.isEqualTo(algo2)
.isNotEqualTo(algo3);
}
@Test
public void shouldHaveSameHashCodeByLength() {
final HashNoLeadingZeroKeyAlgorithm algo1 = new HashNoLeadingZeroKeyAlgorithm(8);
final HashNoLeadingZeroKeyAlgorithm algo2 = new HashNoLeadingZeroKeyAlgorithm(8);
final HashNoLeadingZeroKeyAlgorithm algo3 = new HashNoLeadingZeroKeyAlgorithm(6);
assertThat(algo1.hashCode())
.isEqualTo(algo2.hashCode())
.isNotEqualTo(algo3.hashCode());
}
}

View file

@ -0,0 +1,49 @@
package org.araymond.joal.core.client.emulated.generator.key.algorithm;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class RegexPatternKeyAlgorithmTest {
@Test
public void shouldGeneratePeerIdMatchingPattern() {
final RegexPatternKeyAlgorithm algo = new RegexPatternKeyAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
}
@Test
public void shouldBuild() {
final RegexPatternKeyAlgorithm algo = new RegexPatternKeyAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.getPattern()).isEqualTo("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
}
@Test
public void shouldBeEqualByPattern() {
final RegexPatternKeyAlgorithm algo1 = new RegexPatternKeyAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
final RegexPatternKeyAlgorithm algo2 = new RegexPatternKeyAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
final RegexPatternKeyAlgorithm algo3 = new RegexPatternKeyAlgorithm("-qB33G0-[B-Ea-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo1)
.isEqualTo(algo2)
.isNotEqualTo(algo3);
}
@Test
public void shouldHaveSameHashCodeByPattern() {
final RegexPatternKeyAlgorithm algo1 = new RegexPatternKeyAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
final RegexPatternKeyAlgorithm algo2 = new RegexPatternKeyAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
final RegexPatternKeyAlgorithm algo3 = new RegexPatternKeyAlgorithm("-qB33G0-[B-Ea-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo1.hashCode())
.isEqualTo(algo2.hashCode())
.isNotEqualTo(algo3.hashCode());
}
}

View file

@ -16,7 +16,7 @@ public class AlwaysRefreshPeerIdGeneratorTest {
@Test
public void shouldRefreshKeyEveryTime() {
final PeerIdAlgorithm algo = Mockito.mock(PeerIdAlgorithm.class);
Mockito.when(algo.generate()).thenReturn("do-not-care");
Mockito.when(algo.generate()).thenReturn("do-not-care-too-much");
final PeerIdGenerator generator = new AlwaysRefreshPeerIdGenerator(algo, false);
for (int i = 0; i < 50; ++i) {

View file

@ -16,7 +16,7 @@ public class NeverRefreshKeyGeneratorTest {
@Test
public void shouldNeverRefresh() {
final PeerIdAlgorithm algo = Mockito.mock(PeerIdAlgorithm.class);
Mockito.when(algo.generate()).thenReturn("do-not-care");
Mockito.when(algo.generate()).thenReturn("do-not-care-too-much");
final PeerIdGenerator generator = new NeverRefreshPeerIdGenerator(algo, false);
for (int i = 0; i < 50; ++i) {

View file

@ -46,7 +46,7 @@ public class PeerIdGeneratorTest {
@Test
public void shouldGeneratePeerIdAndBeUpperCase() {
final PeerIdGenerator peerIdGenerator = new DefaultPeerIdGenerator("-my\\.pre-[A-Z]", false);
final PeerIdGenerator peerIdGenerator = new DefaultPeerIdGenerator("-my\\.pre-[A-Z]{12}", false);
for (int i = 0; i < 30; i++) {
assertThat(peerIdGenerator.generatePeerId())
@ -57,7 +57,7 @@ public class PeerIdGeneratorTest {
@Test
public void shouldGeneratePeerIdAndBeLowerCase() {
final PeerIdGenerator peerIdGenerator = new DefaultPeerIdGenerator("-my\\.pre-[a-z]", false);
final PeerIdGenerator peerIdGenerator = new DefaultPeerIdGenerator("-my\\.pre-[a-z]{12}", false);
for (int i = 0; i < 30; i++) {
assertThat(peerIdGenerator.generatePeerId())
@ -68,15 +68,15 @@ public class PeerIdGeneratorTest {
@Test
public void shouldBeEqualsByProperties() {
final PeerIdGenerator peerIdGenerator = new DefaultPeerIdGenerator("-my\\.pre-[a-zA-Z]", false);
final PeerIdGenerator peerIdGenerator2 = new DefaultPeerIdGenerator("-my\\.pre-[a-zA-Z]", false);
final PeerIdGenerator peerIdGenerator = new DefaultPeerIdGenerator("-my\\.pre-[a-zA-Z]{12}", false);
final PeerIdGenerator peerIdGenerator2 = new DefaultPeerIdGenerator("-my\\.pre-[a-zA-Z]{12}", false);
assertThat(peerIdGenerator).isEqualTo(peerIdGenerator2);
}
@Test
public void shouldHaveSameHashCodeWithSameProperties() {
final PeerIdGenerator peerIdGenerator = new DefaultPeerIdGenerator("-my\\.pre-[a-zA-Z]", false);
final PeerIdGenerator peerIdGenerator2 = new DefaultPeerIdGenerator("-my\\.pre-[a-zA-Z]", false);
final PeerIdGenerator peerIdGenerator = new DefaultPeerIdGenerator("-my\\.pre-[a-zA-Z]{12}", false);
final PeerIdGenerator peerIdGenerator2 = new DefaultPeerIdGenerator("-my\\.pre-[a-zA-Z]{12}", false);
assertThat(peerIdGenerator.hashCode()).isEqualTo(peerIdGenerator2.hashCode());
}

View file

@ -41,7 +41,7 @@ public class TimedRefreshPeerIdGeneratorTest {
@Test
public void peerIdShouldNotBeRefreshedIfDelayIsNotElapsedAndRefreshWhenElapsed() throws InterruptedException {
final PeerIdAlgorithm algo = Mockito.mock(PeerIdAlgorithm.class);
Mockito.when(algo.generate()).thenReturn("do-not-care");
Mockito.when(algo.generate()).thenReturn("do-not-care-too-much");
final TimedRefreshPeerIdGenerator generator = new TimedRefreshPeerIdGenerator(1, algo, false);
for( int i = 0; i < 10; ++i) {

View file

@ -22,7 +22,7 @@ public class TorrentPersistentRefreshPeerIdGeneratorTest {
@Test
public void shouldHaveOneKeyPerTorrent() {
final PeerIdAlgorithm algo = Mockito.mock(PeerIdAlgorithm.class);
Mockito.when(algo.generate()).thenReturn("do-not-care");
Mockito.when(algo.generate()).thenReturn("do-not-care-too-much");
final PeerIdGenerator generator = new TorrentPersistentRefreshPeerIdGenerator(algo, false);
final MockedTorrent t1 = Mockito.mock(MockedTorrent.class);
@ -37,7 +37,7 @@ public class TorrentPersistentRefreshPeerIdGeneratorTest {
.isEqualTo(generator.getPeerId(t1.getTorrentInfoHash(), TrackerMessage.AnnounceRequestMessage.RequestEvent.STOPPED));
Mockito.verify(algo, Mockito.times(1)).generate();
Mockito.when(algo.generate()).thenReturn("do-not-care2");
Mockito.when(algo.generate()).thenReturn("!!-not-care-too-much");
assertThat(generator.getPeerId(t2.getTorrentInfoHash(), TrackerMessage.AnnounceRequestMessage.RequestEvent.STARTED))
.isEqualTo(generator.getPeerId(t2.getTorrentInfoHash(), TrackerMessage.AnnounceRequestMessage.RequestEvent.STARTED))
@ -53,7 +53,7 @@ public class TorrentPersistentRefreshPeerIdGeneratorTest {
@Test
public void shouldNotRefreshKeyWhenTorrentHasStopped() {
final PeerIdAlgorithm algo = Mockito.mock(PeerIdAlgorithm.class);
Mockito.when(algo.generate()).thenReturn("do-not-care");
Mockito.when(algo.generate()).thenReturn("do-not-care-too-much");
final PeerIdGenerator generator = new TorrentPersistentRefreshPeerIdGenerator(algo, false);
final MockedTorrent t1 = Mockito.mock(MockedTorrent.class);

View file

@ -17,7 +17,7 @@ public class TorrentVolatileRefreshPeerIdGeneratorTest {
@Test
public void shouldHaveOneKeyPerTorrent() {
final PeerIdAlgorithm algo = Mockito.mock(PeerIdAlgorithm.class);
Mockito.when(algo.generate()).thenReturn("do-not-care");
Mockito.when(algo.generate()).thenReturn("do-not-care-too-much");
final PeerIdGenerator generator = new TorrentVolatileRefreshPeerIdGenerator(algo, false);
final MockedTorrent t1 = Mockito.mock(MockedTorrent.class);
@ -33,7 +33,7 @@ public class TorrentVolatileRefreshPeerIdGeneratorTest {
.isEqualTo(generator.getPeerId(t1.getTorrentInfoHash(), RequestEvent.STOPPED));
Mockito.verify(algo, Mockito.times(1)).generate();
Mockito.when(algo.generate()).thenReturn("do-not-care2");
Mockito.when(algo.generate()).thenReturn("!!-not-care-too-much");
final String keyTwo = generator.getPeerId(t2.getTorrentInfoHash(), RequestEvent.STARTED);
assertThat(keyTwo)
@ -49,7 +49,7 @@ public class TorrentVolatileRefreshPeerIdGeneratorTest {
@Test
public void shouldRefreshKeyWhenTorrentHasStopped() {
final PeerIdAlgorithm algo = Mockito.mock(PeerIdAlgorithm.class);
Mockito.when(algo.generate()).thenReturn("do-not-care");
Mockito.when(algo.generate()).thenReturn("do-not-care-too-much");
final PeerIdGenerator generator = new TorrentVolatileRefreshPeerIdGenerator(algo, false);
final MockedTorrent t1 = Mockito.mock(MockedTorrent.class);

View file

@ -0,0 +1,64 @@
package org.araymond.joal.core.client.emulated.generator.peerid.generation;
import org.araymond.joal.core.client.emulated.generator.peerid.PeerIdGenerator;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class RandomPoolWithChecksumPeerIdAlgorithmTest {
@Test
public void shouldGenerateProperPeerIds() {
final String prefix = "-TR2820-";
final RandomPoolWithChecksumPeerIdAlgorithm algo = Mockito.spy(new RandomPoolWithChecksumPeerIdAlgorithm(prefix, "0123456789abcdefghijklmnopqrstuvwxyz", 36));
Mockito
.doReturn(new byte[]{(byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250})
.doReturn(new byte[]{(byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0})
.doReturn(new byte[]{(byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255})
.doReturn(new byte[]{(byte) 128, (byte) 128, (byte) 128, (byte) 128, (byte) 128, (byte) 128, (byte) 128, (byte) 128, (byte) 128, (byte) 128, (byte) 128})
.doReturn(new byte[]{(byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1})
.doReturn(new byte[]{(byte) 26, (byte) 200, (byte) 124, (byte) 39, (byte) 84, (byte) 248, (byte) 3, (byte) 159, (byte) 64, (byte) 239, (byte) 0})
.when(algo).generateRandomBytes(Matchers.eq(PeerIdGenerator.PEER_ID_LENGTH - prefix.length() - 1));
assertThat(algo.generate()).isEqualTo("-TR2820-yyyyyyyyyyym");
assertThat(algo.generate()).isEqualTo("-TR2820-000000000000");
assertThat(algo.generate()).isEqualTo("-TR2820-333333333333");
assertThat(algo.generate()).isEqualTo("-TR2820-kkkkkkkkkkkw");
assertThat(algo.generate()).isEqualTo("-TR2820-11111111111p");
assertThat(algo.generate()).isEqualTo("-TR2820-qkg3cw3fsn02");
}
@Test
public void shouldGenerateRandomBytes() {
final String prefix = "-TR2820-";
final RandomPoolWithChecksumPeerIdAlgorithm algo = new RandomPoolWithChecksumPeerIdAlgorithm(prefix, "0123456789abcdefghijklmnopqrstuvwxyz", 36);
assertThat(algo.generateRandomBytes(20)).hasSize(20);
assertThat(algo.generateRandomBytes(50)).isNotEqualTo(algo.generateRandomBytes(50));
}
@Test
public void shouldBuild() {
final String prefix = "-TR2820-";
final RandomPoolWithChecksumPeerIdAlgorithm algo = new RandomPoolWithChecksumPeerIdAlgorithm(prefix, "0123456789abcdefghijklmnopqrstuvwxyz", 36);
assertThat(algo.getPrefix()).isEqualTo(prefix);
assertThat(algo.getCharactersPool()).isEqualTo("0123456789abcdefghijklmnopqrstuvwxyz");
assertThat(algo.getBase()).isEqualTo(36);
}
@Test
public void shouldRefreshRandomSpeedOneInAWhile() {
final String prefix = "-TR2820-";
final RandomPoolWithChecksumPeerIdAlgorithm algo = Mockito.spy(new RandomPoolWithChecksumPeerIdAlgorithm(prefix, "0123456789abcdefghijklmnopqrstuvwxyz", 36));
for (int i = 0; i < 51; i++) {
algo.generateRandomBytes(10);
}
Mockito.verify(algo, Mockito.atLeast(1)).createSecureRandomSeed();
}
}

View file

@ -0,0 +1,50 @@
package org.araymond.joal.core.client.emulated.generator.peerid.generation;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class RegexPatternPeerIdAlgorithmTest {
@Test
public void shouldGeneratePeerIdMatchingPattern() {
final RegexPatternPeerIdAlgorithm algo = new RegexPatternPeerIdAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.generate()).matches("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
}
@Test
public void shouldBuild() {
final RegexPatternPeerIdAlgorithm algo = new RegexPatternPeerIdAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo.getPattern()).isEqualTo("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
}
@Test
public void shouldBeEqualByPattern() {
final RegexPatternPeerIdAlgorithm algo1 = new RegexPatternPeerIdAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
final RegexPatternPeerIdAlgorithm algo2 = new RegexPatternPeerIdAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
final RegexPatternPeerIdAlgorithm algo3 = new RegexPatternPeerIdAlgorithm("-qB33G0-[B-Ea-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo1)
.isEqualTo(algo2)
.isNotEqualTo(algo3);
}
@Test
public void shouldHaveSameHashCodeByPattern() {
final RegexPatternPeerIdAlgorithm algo1 = new RegexPatternPeerIdAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
final RegexPatternPeerIdAlgorithm algo2 = new RegexPatternPeerIdAlgorithm("-qB33G0-[A-Za-z0-9_~\\(\\)\\!\\.\\*-]{12}");
final RegexPatternPeerIdAlgorithm algo3 = new RegexPatternPeerIdAlgorithm("-qB33G0-[B-Ea-z0-9_~\\(\\)\\!\\.\\*-]{12}");
assertThat(algo1.hashCode())
.isEqualTo(algo2.hashCode())
.isNotEqualTo(algo3.hashCode());
}
}

View file

@ -0,0 +1,20 @@
package org.araymond.joal.core.events.config;
import org.araymond.joal.core.config.AppConfiguration;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class ConfigurationIsInDirtyStateEventTest {
@Test
public void shouldBuild() {
final AppConfiguration appConfiguration = mock(AppConfiguration.class);
final ConfigurationIsInDirtyStateEvent event = new ConfigurationIsInDirtyStateEvent(appConfiguration);
assertThat(event.getConfiguration()).isEqualTo(appConfiguration);
}
}

View file

@ -0,0 +1,21 @@
package org.araymond.joal.core.events.config;
import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class ListOfClientFilesEventTest {
@Test
public void shouldBuild() {
final List<String> clientFiles = Lists.newArrayList();
final ListOfClientFilesEvent event = new ListOfClientFilesEvent(clientFiles);
assertThat(event.getClients()).isEqualTo(clientFiles);
}
}

View file

@ -0,0 +1,20 @@
package org.araymond.joal.core.events.global.state;
import org.araymond.joal.core.client.emulated.BitTorrentClient;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class GlobalSeedStartedEventTest {
@Test
public void shouldBuild() {
final BitTorrentClient client = mock(BitTorrentClient.class);
final GlobalSeedStartedEvent event = new GlobalSeedStartedEvent(client);
assertThat(event.getBitTorrentClient()).isEqualTo(client);
}
}

View file

@ -0,0 +1,14 @@
package org.araymond.joal.core.events.global.state;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class GlobalSeedStoppedEventTest {
@Test
public void shouldBuild() {
new GlobalSeedStoppedEvent();
}
}

View file

@ -0,0 +1,23 @@
package org.araymond.joal.core.events.speed;
import com.google.common.collect.Maps;
import org.araymond.joal.core.bandwith.Speed;
import org.araymond.joal.core.torrent.torrent.InfoHash;
import org.junit.Test;
import java.util.Map;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class SeedingSpeedsHasChangedEventTest {
@Test
public void shouldBuild() {
final Map<InfoHash, Speed> speeds = Maps.newHashMap();
final SeedingSpeedsHasChangedEvent event = new SeedingSpeedsHasChangedEvent(speeds);
assertThat(event.getSpeeds()).isEqualTo(speeds);
}
}

View file

@ -0,0 +1,18 @@
package org.araymond.joal.core.events.torrent.files;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class FailedToAddTorrentFileEventTest {
@Test
public void shouldBuild() {
final FailedToAddTorrentFileEvent event = new FailedToAddTorrentFileEvent("dd", "err");
assertThat(event.getFileName()).isEqualTo("dd");
assertThat(event.getError()).isEqualTo("err");
}
}

View file

@ -0,0 +1,20 @@
package org.araymond.joal.core.events.torrent.files;
import org.araymond.joal.core.torrent.torrent.MockedTorrent;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class TorrentFileAddedEventTest {
@Test
public void shouldBuild() {
final MockedTorrent torrent = mock(MockedTorrent.class);
final TorrentFileAddedEvent event = new TorrentFileAddedEvent(torrent);
assertThat(event.getTorrent()).isEqualTo(torrent);
}
}

View file

@ -0,0 +1,20 @@
package org.araymond.joal.core.events.torrent.files;
import org.araymond.joal.core.torrent.torrent.MockedTorrent;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class TorrentFileDeletedEventTest {
@Test
public void shouldBuild() {
final MockedTorrent torrent = mock(MockedTorrent.class);
final TorrentFileDeletedEvent event = new TorrentFileDeletedEvent(torrent);
assertThat(event.getTorrent()).isEqualTo(torrent);
}
}

View file

@ -25,6 +25,18 @@ import static org.mockito.Mockito.*;
public class AnnouncerTest {
@Test
public void shouldProvideRequiredInfoForAnnouncerFacade() {
final MockedTorrent torrent = MockedTorrentTest.createOneMock();
final AnnouncerFacade facade = new Announcer(torrent, null);
assertThat(facade.getConsecutiveFails()).isEqualTo(0);
assertThat(facade.getLastKnownInterval()).isEqualTo(5);
assertThat(facade.getTorrentName()).isEqualTo(torrent.getName());
assertThat(facade.getTorrentSize()).isEqualTo(torrent.getSize());
assertThat(facade.getTorrentInfoHash()).isEqualTo(torrent.getTorrentInfoHash());
}
@Test
public void shouldThrowTooManyFailsExceptionIfFailsFiveTimesInARaw() throws AnnounceException {
final MockedTorrent torrent = MockedTorrentTest.createOneMock("abcd");

View file

@ -0,0 +1,20 @@
package org.araymond.joal.core.ttorrent.client.announcer.exceptions;
import org.araymond.joal.core.torrent.torrent.MockedTorrent;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class TooMuchAnnouncesFailedInARawExceptionTest {
@Test
public void shouldBuild() {
final MockedTorrent torrent = mock(MockedTorrent.class);
final TooMuchAnnouncesFailedInARawException exception = new TooMuchAnnouncesFailedInARawException(torrent);
assertThat(exception.getTorrent()).isEqualTo(torrent);
}
}