strategy_test.go 1.69 KB
Newer Older
1 2 3 4 5
package strategy

import (
	"testing"

6
	message "github.com/jbenet/go-ipfs/exchange/bitswap/message"
7 8 9 10 11 12
	"github.com/jbenet/go-ipfs/peer"
	"github.com/jbenet/go-ipfs/util/testutil"
)

type peerAndStrategist struct {
	*peer.Peer
13
	Strategy
14 15 16 17
}

func newPeerAndStrategist(idStr string) peerAndStrategist {
	return peerAndStrategist{
18 19
		Peer:     &peer.Peer{ID: peer.ID(idStr)},
		Strategy: New(),
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
	}
}

func TestBlockRecordedAsWantedAfterMessageReceived(t *testing.T) {
	beggar := newPeerAndStrategist("can't be chooser")
	chooser := newPeerAndStrategist("chooses JIF")

	block := testutil.NewBlockOrFail(t, "data wanted by beggar")

	messageFromBeggarToChooser := message.New()
	messageFromBeggarToChooser.AppendWanted(block.Key())

	chooser.MessageReceived(beggar.Peer, messageFromBeggarToChooser)
	// for this test, doesn't matter if you record that beggar sent

35
	if !chooser.BlockIsWantedByPeer(block.Key(), beggar.Peer) {
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
		t.Fatal("chooser failed to record that beggar wants block")
	}
}

func TestPeerIsAddedToPeersWhenMessageReceivedOrSent(t *testing.T) {

	sanfrancisco := newPeerAndStrategist("sf")
	seattle := newPeerAndStrategist("sea")

	m := message.New()

	sanfrancisco.MessageSent(seattle.Peer, m)
	seattle.MessageReceived(sanfrancisco.Peer, m)

	if seattle.Peer.Key() == sanfrancisco.Peer.Key() {
		t.Fatal("Sanity Check: Peers have same Key!")
	}

54
	if !peerIsPartner(seattle.Peer, sanfrancisco.Strategy) {
55 56 57
		t.Fatal("Peer wasn't added as a Partner")
	}

58
	if !peerIsPartner(sanfrancisco.Peer, seattle.Strategy) {
59 60 61 62
		t.Fatal("Peer wasn't added as a Partner")
	}
}

63
func peerIsPartner(p *peer.Peer, s Strategy) bool {
64 65 66 67 68 69 70
	for _, partner := range s.Peers() {
		if partner.Key() == p.Key() {
			return true
		}
	}
	return false
}