90 lines
2.2 KiB
Go
90 lines
2.2 KiB
Go
package kademlia
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"os"
|
|
"testing"
|
|
)
|
|
|
|
var table1 *RoutingTable
|
|
var table5 *RoutingTable
|
|
var nodes []P2PNode
|
|
var nodesSeq []P2PNode
|
|
var nodesSeq2 []P2PNode
|
|
var clientID [32]byte
|
|
var clientNode P2PNode
|
|
|
|
func TestMain(m *testing.M) {
|
|
clientNode = P2PNode{NodeID: clientID}
|
|
table1 = NewRoutingTable(clientNode, 1)
|
|
table5 = NewRoutingTable(clientNode, 5)
|
|
|
|
for i := 0; i < 100; i++ {
|
|
nodes = append(nodes, P2PNode{NodeID: sha256.Sum256([]byte{byte(i)})})
|
|
var id [32]byte
|
|
id[31] = byte(i)
|
|
nodesSeq = append(nodesSeq, P2PNode{NodeID: id})
|
|
var id2 [32]byte
|
|
id2[0] = 1
|
|
id2[1] = byte(i)
|
|
nodesSeq2 = append(nodesSeq2, P2PNode{NodeID: id2})
|
|
}
|
|
code := m.Run()
|
|
os.Exit(code)
|
|
}
|
|
|
|
func TestSimpleInsert(t *testing.T) {
|
|
for i := 0; i < 5; i++ {
|
|
table1.Insert(nodes[i])
|
|
}
|
|
found := table1.FindClosest(clientID, 20)
|
|
|
|
for _, n := range nodes[:5] {
|
|
if !ContainsID(*found, n.NodeID) {
|
|
t.Errorf("Node %s not returned", n.NodeID)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSplit(t *testing.T) {
|
|
// Insert the nodes closest to 0 and some random ones, forcing a split in the table.
|
|
// All the close ones should remain and be returned
|
|
for i := 0; i < 20; i++ {
|
|
table1.Insert(nodes[i])
|
|
table1.Insert(nodesSeq[i])
|
|
table5.Insert(nodes[i])
|
|
table5.Insert(nodesSeq[i])
|
|
}
|
|
found1 := table1.FindClosest(clientID, 20)
|
|
found5 := table5.FindClosest(clientID, 20)
|
|
|
|
for _, n := range nodesSeq[:20] {
|
|
if !ContainsID(*found1, n.NodeID) {
|
|
t.Errorf("Node %s not returned in table1", n.NodeID)
|
|
}
|
|
if !ContainsID(*found5, n.NodeID) {
|
|
t.Errorf("Node %s not returned in table5", n.NodeID)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestPing(t *testing.T) {
|
|
//These all should get sorted into the same bucket as they share a same differing prefix from the hostNode
|
|
//But then differ in the part after that
|
|
for i := 0; i < 50; i++ {
|
|
table1.Insert(nodesSeq2[i])
|
|
table5.Insert(nodesSeq2[i])
|
|
}
|
|
// All Pings should fail, so the last 20 should remain.
|
|
found1 := table1.FindClosest(clientID, 20)
|
|
found5 := table5.FindClosest(clientID, 20)
|
|
for _, n := range nodesSeq2[:30] {
|
|
if ContainsID(*found1, n.NodeID) {
|
|
t.Errorf("Node %s should not have been included in table1", n.NodeID)
|
|
}
|
|
if ContainsID(*found5, n.NodeID) {
|
|
t.Errorf("Node %s should not have been included in table5", n.NodeID)
|
|
}
|
|
}
|
|
}
|