diff --git a/src/test/java/com/mykola2312/retracker/tracker/Torrent.java b/src/test/java/com/mykola2312/retracker/tracker/Torrent.java new file mode 100644 index 0000000..7f1bc75 --- /dev/null +++ b/src/test/java/com/mykola2312/retracker/tracker/Torrent.java @@ -0,0 +1,39 @@ +package com.mykola2312.retracker.tracker; + +import java.util.Collection; + +public class Torrent { + private InfoHash infoHash; + private PeerSet peers; + + public Torrent(InfoHash infoHash) { + this.infoHash = infoHash; + this.peers = new PeerSet(); + } + + // will construct PeerSet with initial single peer + public Torrent(InfoHash infoHash, Peer initiator) { + this.infoHash = infoHash; + this.peers = new PeerSet(1); + peers.put(initiator); + } + + public InfoHash getInfoHash() { + return infoHash; + } + + /* Copy current set of peers into destination collection. + * Copying over reference is preferable in concurrent environment + */ + public > void copyPeers(T dst) { + for (Peer peer : peers) { + dst.add(peer); + } + } + + public > void updatePeers(T src) { + for (Peer peer : src) { + peers.put(peer); + } + } +} diff --git a/src/test/java/com/mykola2312/retracker/tracker/TorrentTest.java b/src/test/java/com/mykola2312/retracker/tracker/TorrentTest.java new file mode 100644 index 0000000..5fccb82 --- /dev/null +++ b/src/test/java/com/mykola2312/retracker/tracker/TorrentTest.java @@ -0,0 +1,44 @@ +package com.mykola2312.retracker.tracker; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class TorrentTest { + private static InetSocketAddress newAddress(String addr, int port) throws UnknownHostException { + return new InetSocketAddress(InetAddress.getByName(addr), port); + } + + @Test + public void testUpdatePeers() throws Exception { + final InfoHash infoHash = new InfoHash(); + infoHash.fromString("360775c6629eb06e60d90201aed1b7bc49a1ce16"); + + Torrent torrent = new Torrent(infoHash); + { + ArrayList copy = new ArrayList(); + torrent.copyPeers(copy); + + assertEquals(0, copy.size()); + } + + List src = Arrays.asList(new Peer(newAddress("127.0.0.1", 1337)), + new Peer(newAddress("127.0.0.1", 1338))); + torrent.updatePeers(src); + { + ArrayList copy = new ArrayList(); + torrent.copyPeers(copy); + + assertEquals(2, copy.size()); + assertEquals(1337, copy.get(0).getAddress().getPort()); + assertEquals(1338, copy.get(1).getAddress().getPort()); + } + } +}