handlers_test.go 2.34 KB
Newer Older
1 2 3 4
package dht

import (
	"bytes"
5 6 7
	"context"
	"fmt"
	"math/rand"
8
	"testing"
9
	"time"
10 11

	proto "github.com/gogo/protobuf/proto"
12 13 14 15
	"github.com/libp2p/go-libp2p"
	crypto "github.com/libp2p/go-libp2p-core/crypto"
	peer "github.com/libp2p/go-libp2p-core/peer"
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
16
	recpb "github.com/libp2p/go-libp2p-record/pb"
17
	ma "github.com/multiformats/go-multiaddr"
18 19 20 21
)

func TestCleanRecordSigned(t *testing.T) {
	actual := new(recpb.Record)
22
	actual.TimeReceived = "time"
23
	actual.Value = []byte("value")
24
	actual.Key = []byte("key")
25 26 27 28 29 30 31 32 33

	cleanRecord(actual)
	actualBytes, err := proto.Marshal(actual)
	if err != nil {
		t.Fatal(err)
	}

	expected := new(recpb.Record)
	expected.Value = []byte("value")
34
	expected.Key = []byte("key")
35 36 37 38 39 40 41 42 43 44 45 46
	expectedBytes, err := proto.Marshal(expected)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(actualBytes, expectedBytes) {
		t.Error("failed to clean record")
	}
}

func TestCleanRecord(t *testing.T) {
	actual := new(recpb.Record)
47 48
	actual.TimeReceived = "time"
	actual.Key = []byte("key")
49 50 51 52 53 54 55 56 57
	actual.Value = []byte("value")

	cleanRecord(actual)
	actualBytes, err := proto.Marshal(actual)
	if err != nil {
		t.Fatal(err)
	}

	expected := new(recpb.Record)
58
	expected.Key = []byte("key")
59 60 61 62 63 64 65 66 67 68
	expected.Value = []byte("value")
	expectedBytes, err := proto.Marshal(expected)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(actualBytes, expectedBytes) {
		t.Error("failed to clean record")
	}
}
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

func BenchmarkHandleFindPeer(b *testing.B) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	h, err := libp2p.New(ctx)
	if err != nil {
		b.Fatal(err)
	}

	d, err := New(ctx, h)
	if err != nil {
		b.Fatal(err)
	}

	rng := rand.New(rand.NewSource(150))
	var peers []peer.ID
	for i := 0; i < 1000; i++ {
		_, pubk, _ := crypto.GenerateEd25519Key(rng)
		id, err := peer.IDFromPublicKey(pubk)
		if err != nil {
			panic(err)
		}

Aarsh Shah's avatar
Aarsh Shah committed
92
		d.peerFound(ctx, id, true)
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

		peers = append(peers, id)
		a, err := ma.NewMultiaddr(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", 2000+i))
		if err != nil {
			panic(err)
		}

		d.host.Peerstore().AddAddr(id, a, time.Minute*50)
	}

	var reqs []*pb.Message
	for i := 0; i < b.N; i++ {
		reqs = append(reqs, &pb.Message{
			Key: []byte("asdasdasd"),
		})
	}
	b.ReportAllocs()
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
Steven Allen's avatar
Steven Allen committed
113 114 115 116
		_, err = d.handleFindPeer(ctx, peers[0], reqs[i])
		if err != nil {
			b.Error(err)
		}
117 118 119
	}

}